code
stringlengths 67
15.9k
| labels
listlengths 1
4
|
---|---|
package dotcommonitor
import (
"fmt"
"log"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/mitchellh/hashstructure"
"github.com/rymancl/terraform-provider-dotcommonitor/dotcommonitor/client"
)
func dataLocations() *schema.Resource {
return &schema.Resource{
Read: dataLocationsRead,
Schema: map[string]*schema.Schema{
"all_locations": {
Type: schema.TypeBool,
Optional: true,
ExactlyOneOf: []string{"all_locations", "all_public_locations", "all_private_locations", "ids", "names"},
},
"all_public_locations": {
Type: schema.TypeBool,
Optional: true,
ExactlyOneOf: []string{"all_locations", "all_public_locations", "all_private_locations", "ids", "names"},
},
"all_private_locations": {
Type: schema.TypeBool,
Optional: true,
ExactlyOneOf: []string{"all_locations", "all_public_locations", "all_private_locations", "ids", "names"},
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeInt},
ExactlyOneOf: []string{"all_locations", "all_public_locations", "all_private_locations", "ids", "names"},
},
"names": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
ExactlyOneOf: []string{"all_locations", "all_public_locations", "all_private_locations", "ids", "names"},
},
"platform_id": {
Type: schema.TypeInt,
Optional: true,
Default: 1, // ServerView, currently only valid other than UserView which isn't supported by the API
ValidateFunc: validation.IntInSlice([]int{1}), // 1=ServerView
},
"include_unavailable": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"include_restrictive": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
},
}
}
func dataLocationsRead(d *schema.ResourceData, meta interface{}) error {
mutex.Lock()
defer mutex.Unlock()
var locations []client.Location
api := meta.(*client.APIClient)
all := d.Get("all_locations").(bool)
allPublic := d.Get("all_public_locations").(bool)
allPrivate := d.Get("all_private_locations").(bool)
ids := convertInterfaceListToIntList(d.Get("ids").([]interface{}))
names := convertInterfaceListToStringList(d.Get("names").([]interface{}))
platformID := d.Get("platform_id").(int)
includeUnavailable := d.Get("include_unavailable").(bool)
includeRestrictive := d.Get("include_restrictive").(bool)
// check which agrument was provided and make the appropriate API call
if (all) {
err := api.GetLocations(platformID, includeUnavailable, &locations)
if err != nil {
return fmt.Errorf("[Dotcom-Monitor] Failed to get all locations: %s", err)
}
} else if (allPublic) {
err := api.GetPublicLocations(platformID, includeUnavailable, &locations)
if err != nil {
return fmt.Errorf("[Dotcom-Monitor] Failed to get all public locations: %s", err)
}
} else if (allPrivate) {
err := api.GetPrivateLocations(platformID, includeUnavailable, &locations)
if err != nil {
return fmt.Errorf("[Dotcom-Monitor] Failed to get all public locations: %s", err)
}
} else if (len(ids) > 0) {
var allTemp []client.Location
err := api.GetLocations(platformID, includeUnavailable, &allTemp)
if err != nil {
return fmt.Errorf("[Dotcom-Monitor] Failed to get all locations: %s", err)
}
// check all locations to ensure ID is valid
for _, item := range allTemp {
if (!locationListContainsLocationID(allTemp, item.ID)) {
return fmt.Errorf("[Dotcom-Monitor] No valid location return from API for ID: %v", item.ID)
}
locations = append(locations, item)
}
} else if (len(names) > 0) {
var allTemp []client.Location
err := api.GetLocations(platformID, includeUnavailable, &allTemp)
if err != nil {
return fmt.Errorf("[Dotcom-Monitor] Failed to get all locations: %s", err)
}
// check all locations to ensure name is valid
for _, item := range allTemp {
if (!locationListContainsLocationName(allTemp, item.Name)) {
return fmt.Errorf("[Dotcom-Monitor] No valid location return from API for name: %v", item.ID)
}
locations = append(locations, item)
}
}
// No locations found on the platform
if len(locations) < 1 {
return fmt.Errorf("[Dotcom-Monitor] Query did not return any locations from API")
}
// remove restrictive locations if requested
if (!includeRestrictive) {
locations = removeRestrictiveLocations(locations)
}
if err1 := populateLocationsAttributes(d, locations); err1 != nil {
log.Printf("[Dotcom-Monitor] Error setting location attributes: %v", err1)
}
return nil
}
// populateLocationAttributes ... fills in necessary schema attributes of the data source
func populateLocationsAttributes(d *schema.ResourceData, locations []client.Location) error {
hash, err := hashstructure.Hash(locations, nil) // this may not generate a unique ID, but it is fine for data sources
if err != nil {
panic("[Dotcom-Monitor] Error hashing location data to create ID")
}
strHash := fmt.Sprint(hash)
d.SetId(strHash)
// fill ids and names
ids := []int{}
names := []string{}
for _, item := range(locations) {
ids = append(ids, item.ID)
names = append(names, item.Name)
}
d.Set("ids", ids)
d.Set("names", names)
return nil
}
|
[
5
] |
package business
import (
"fmt"
"github.com/kiali/kiali/kubernetes"
"github.com/kiali/kiali/log"
"github.com/kiali/kiali/services/business/checkers"
"github.com/kiali/kiali/services/models"
)
type IstioValidationsService struct {
k8s kubernetes.IstioClientInterface
}
type ObjectChecker interface {
Check() models.IstioValidations
}
// GetServiceValidations returns an IstioValidations object with all the checks found when running
// all the enabled checkers.
func (in *IstioValidationsService) GetServiceValidations(namespace, service string) (models.IstioValidations, error) {
// Get all the Istio objects from a Namespace and service
istioDetails, err := in.k8s.GetIstioDetails(namespace, service)
if err != nil {
return nil, err
}
pods, err := in.k8s.GetServicePods(namespace, service, "")
if err != nil {
log.Warningf("Cannot get pods for service %v.%v.", namespace, service)
return nil, err
}
objectCheckers := []ObjectChecker{
checkers.VirtualServiceChecker{namespace, istioDetails.DestinationRules,
istioDetails.VirtualServices},
checkers.PodChecker{Pods: pods.Items},
}
// Get groupal validations for same kind istio objects
return runObjectCheckers(objectCheckers), nil
}
func (in *IstioValidationsService) GetNamespaceValidations(namespace string) (models.NamespaceValidations, error) {
// Get all the Istio objects from a Namespace
istioDetails, err := in.k8s.GetIstioDetails(namespace, "")
if err != nil {
return nil, err
}
serviceList, err := in.k8s.GetServices(namespace)
if err != nil {
return nil, err
}
objectCheckers := []ObjectChecker{
checkers.VirtualServiceChecker{namespace, istioDetails.DestinationRules,
istioDetails.VirtualServices},
checkers.NoServiceChecker{Namespace: namespace, IstioDetails: istioDetails, ServiceList: serviceList},
}
return models.NamespaceValidations{namespace: runObjectCheckers(objectCheckers)}, nil
}
func (in *IstioValidationsService) GetIstioObjectValidations(namespace string, objectType string, object string) (models.IstioValidations, error) {
serviceList, err := in.k8s.GetServices(namespace)
if err != nil {
return nil, err
}
// Get only the given Istio Object
var dr kubernetes.IstioObject
var vss []kubernetes.IstioObject
var objectCheckers []ObjectChecker
noServiceChecker := checkers.NoServiceChecker{Namespace: namespace, ServiceList: serviceList}
istioDetails := kubernetes.IstioDetails{}
noServiceChecker.IstioDetails = &istioDetails
switch objectType {
case "gateways":
// Validations on Gateways are not yet in place
case "virtualservices":
if vss, err = in.k8s.GetVirtualServices(namespace, ""); err == nil {
if drs, err := in.k8s.GetDestinationRules(namespace, ""); err == nil {
istioDetails.VirtualServices = vss
istioDetails.DestinationRules = drs
virtualServiceChecker := checkers.VirtualServiceChecker{Namespace: namespace, VirtualServices: istioDetails.VirtualServices, DestinationRules: istioDetails.DestinationRules}
objectCheckers = []ObjectChecker{noServiceChecker, virtualServiceChecker}
}
}
case "destinationrules":
if dr, err = in.k8s.GetDestinationRule(namespace, object); err == nil {
istioDetails.DestinationRules = []kubernetes.IstioObject{dr}
objectCheckers = []ObjectChecker{noServiceChecker}
}
case "serviceentries":
// Validations on ServiceEntries are not yet in place
case "rules":
// Validations on Istio Rules are not yet in place
case "quotaspecs":
// Validations on QuotaSpecs are not yet in place
case "quotaspecbindings":
// Validations on QuotaSpecBindings are not yet in place
default:
err = fmt.Errorf("Object type not found: %v", objectType)
}
if objectCheckers == nil || err != nil {
return models.IstioValidations{}, err
}
return runObjectCheckers(objectCheckers).FilterByKey(models.ObjectTypeSingular[objectType], object), nil
}
func runObjectCheckers(objectCheckers []ObjectChecker) models.IstioValidations {
objectTypeValidations := models.IstioValidations{}
validationsChannels := make([]chan models.IstioValidations, len(objectCheckers))
// Run checks for each IstioObject type
for i, objectChecker := range objectCheckers {
validationsChannels[i] = make(chan models.IstioValidations)
go func(channel chan models.IstioValidations, checker ObjectChecker) {
channel <- checker.Check()
close(channel)
}(validationsChannels[i], objectChecker)
}
// Receive validations and merge them into one object
for _, validation := range validationsChannels {
objectTypeValidations.MergeValidations(<-validation)
}
return objectTypeValidations
}
|
[
6
] |
package main
import (
"fmt"
"math/rand"
"runtime"
"sync"
"testing"
"time"
)
type integrityTester struct {
sync.Mutex
lastValue uint64
lastTime time.Time
seen []uint64
}
func newIntegrityTester() *integrityTester {
return &integrityTester{
lastValue: 0,
lastTime: time.Now(),
seen: make([]uint64, 0),
}
}
func (it *integrityTester) check(val uint64) error {
now := time.Now()
it.Lock()
defer it.Unlock()
if val < it.lastValue {
// this is okay, as long as it's not more than a second in the past.
if it.lastTime.Before(now.Add(-1 * time.Second)) {
return fmt.Errorf("value %v before %v and more than a second in that past (%v)", val, it.lastValue, now.Sub(it.lastTime))
}
}
for _, i := range it.seen {
if i == val {
return fmt.Errorf("already seen %v", val)
}
}
it.lastValue = val
it.lastTime = now
it.seen = append(it.seen, val)
return nil
}
func newTestPool(delay time.Duration) *pool {
notify := make(chan uint64)
pool := newPool(notify)
i := uint64(1000)
var mutex sync.Mutex
go func() {
for size := range notify {
time.Sleep(delay)
mutex.Lock()
start := i
i = i + size
mutex.Unlock()
pool.addRange(newIDRange(start, start+size, ""))
}
}()
return pool
}
func getRange(start uint64, end uint64, pool *pool, t *testing.T) {
for i := uint64(start); i < end; i++ {
id := pool.getID()
if i != id {
t.Errorf("invalid id %v, expected %v", id, i)
}
}
}
func getTicker(delay int32, amount int) chan bool {
ticker := make(chan bool, amount)
// do this in it's own thread to mimic the real world a bit better.
go func() {
for i := 0; i < amount; i++ {
time.Sleep(time.Duration(rand.Int31n(delay)) * time.Millisecond)
ticker <- true
}
close(ticker)
}()
return ticker
}
func getAmount(amount int, pool *pool, t *testing.T) {
var last uint64
for range getTicker(25, amount) {
id := pool.getID()
if id <= last {
t.Error("got the same id twice!")
}
last = id
}
}
func TestAddAndConsumeRange(t *testing.T) {
pool := newTestPool(0)
pool.addRange(newIDRange(100, 110, ""))
getRange(100, 110, pool, t)
}
func TestAddAndConsumeMultipleRanges(t *testing.T) {
pool := newTestPool(0)
pool.addRange(newIDRange(100, 105, ""))
pool.addRange(newIDRange(150, 155, ""))
pool.addRange(newIDRange(175, 180, ""))
getRange(100, 105, pool, t)
getRange(150, 155, pool, t)
getRange(175, 180, pool, t)
}
func TestAutoAddRanges(t *testing.T) {
pool := newTestPool(100 * time.Millisecond)
// just go!
getAmount(1000, pool, t)
}
func TestMultipleThreads(t *testing.T) {
// just make super-sure we're in a multi-threaded environmet
runtime.GOMAXPROCS(runtime.NumCPU())
tester := newIntegrityTester()
pool := newTestPool(100)
threads := runtime.NumCPU()
done := make(chan bool)
run := func() {
for range getTicker(500, 50) {
if err := tester.check(pool.getID()); err != nil {
t.Error(err.Error())
}
}
done <- true
}
for i := 0; i < threads; i++ {
go run()
}
for i := 0; i < threads; i++ {
<-done
}
}
|
[
0,
6
] |
package main
import (
"encoding/json"
"log"
"net/http"
"regexp"
"github.com/golang/protobuf/proto"
"github.com/jarod/skynet/skynet"
"github.com/jarod/skynet/skynet/net"
)
type HttpServer struct {
}
func NewHttpServer() *HttpServer {
return &HttpServer{}
}
func (h *HttpServer) ListenAndServe(addr string) {
log.Println("Serve http on ", addr)
log.Fatal(http.ListenAndServe(addr, h))
}
func (h *HttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//log.Println(r.URL.String())
switch r.URL.Path {
case "/matrix/apps":
h.findApps(w, r)
case "/matrix/cmd":
h.execAgentCmd(w, r)
default:
log.Printf("http: no handler for request. %s %s\n", r.Method, r.RequestURI)
}
}
func (h *HttpServer) findApps(w http.ResponseWriter, req *http.Request) {
err := req.ParseForm()
if err != nil {
log.Println("agent http: findApps - ", err)
return
}
pattern := req.FormValue("pattern")
var infos []*skynet.AppInfo
enc := json.NewEncoder(w)
for k, v := range appInfos {
matched, err := regexp.MatchString(pattern, k)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//log.Printf("k:%s,v:%v,pattern:%s\n", k, v, pattern)
if matched {
infos = append(infos, v)
}
}
err = enc.Encode(map[string]interface{}{
"Data": infos})
if err != nil {
log.Println("agent http: findApps - ", err)
return
}
}
/*
URL: /matrix/cmd?agent=agent_addr&cmd=
send command to agent and run on agent machine
@param agent: addr of agent server
@param cmd: shell command to execute
*/
func (h *HttpServer) execAgentCmd(w http.ResponseWriter, r *http.Request) {
addr := r.FormValue("agent")
mutex.Lock()
agent := tcpServer.FindAgentByAddr(addr)
mutex.Unlock()
if agent == nil {
log.Printf("No agent of addr=%s\n", addr)
return
}
cmd := r.FormValue("cmd")
log.Printf("exec agent command - agent=%s,cmd=%s,\n", addr, cmd)
p, err := net.NewMessagePacket(0x0020, &skynet.Pstring{Value: proto.String(cmd)})
if err != nil {
log.Println(err)
return
}
agent.Write(p)
}
|
[
3
] |
package game
import (
"time"
log "github.com/sirupsen/logrus"
"github.com/talesmud/talesmud/pkg/entities"
"github.com/talesmud/talesmud/pkg/mudserver/game/messages"
)
func (game *Game) handleDefaultMessage(message *messages.Message) {
user := ""
if message.FromUser != nil {
user = message.FromUser.Nickname
if message.Character != nil {
user = message.Character.Name
}
}
out := messages.NewRoomBasedMessage(user, message.Data)
if message.Character != nil {
out.AudienceID = message.Character.CurrentRoomID
}
game.SendMessage() <- out
}
func (game *Game) handleUserQuit(user *entities.User) {
log.Info("Handle User Quit " + user.Nickname)
// set user offline
user.IsOnline = false
game.Facade.UsersService().Update(user.RefID, user)
character, _ := game.Facade.CharactersService().FindByID(user.LastCharacter)
room, _ := game.Facade.RoomsService().FindByID(character.CurrentRoomID)
//TOOD: move update to queue
room.RemoveCharacter(character.ID)
game.Facade.RoomsService().Update(room.ID, room)
game.SendMessage() <- messages.CharacterLeftRoom{
MessageResponse: messages.MessageResponse{
Audience: messages.MessageAudienceRoomWithoutOrigin,
OriginID: character.ID,
AudienceID: character.CurrentRoomID,
Message: character.Name + " left.",
},
}
}
// Find the matching character for the user where the message originated
func (game *Game) attachCharacterToMessage(msg *messages.Message) {
if msg.Character != nil {
return
}
// could be a processed message that got the user removed
if msg.FromUser == nil || msg.FromUser.LastCharacter == "" {
return
}
if character, err := game.Facade.CharactersService().FindByID(msg.FromUser.LastCharacter); err == nil {
msg.Character = character
} else {
log.Error("Couldt not load character for user")
}
}
func (game *Game) handleUserJoined(user *entities.User) {
// get active character for user
if user.LastCharacter == "" {
if chars, err := game.Facade.CharactersService().FindAllForUser(user.ID); err == nil {
// take first character for now
// TODO: let the player choose?
if len(chars) > 0 {
user.LastCharacter = chars[0].ID
user.LastSeen = time.Now()
user.IsOnline = true
//TODO: send updates via message queue?
game.Facade.UsersService().Update(user.RefID, user)
}
} else {
// player has no character yet, respnd with createCharacter Message
game.SendMessage() <- messages.NewCreateCharacterMessage(user.ID)
return
}
}
if character, err := game.Facade.CharactersService().FindByID(user.LastCharacter); err != nil {
log.WithField("user", user.Name).Error("Could not select character for user")
// player character may be broken, let the user create a new one
//game.SendMessage(messages.NewCreateCharacterMessage(user.ID))
// send list characters command
game.onMessageReceived <- messages.NewMessage(user, "lc")
} else {
// send message as userwould do it
selectCharacterMsg := messages.NewMessage(user, "selectcharacter "+character.Name)
game.OnMessageReceived() <- selectCharacterMsg
}
}
|
[
3
] |
package algorithms
//Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
//
//Example:
//
//Input: "babad"
//
//Output: "bab"
//
//Note: "aba" is also a valid answer.
//Example:
//
//Input: "cbbd"
//
//Output: "bb"
// 增加一个字符后有三种可能
// 1. 回环长度+1 如 a + a
// 2. 回环长度+2 如 ab + a
// 3. 回环长度不变 如 a + b
// 起始位置start=0 回环长度maxLen=1
// 截取末尾 maxLen+2长度字符 如果对称 则回环长度+2 变更起始位置
// 截取末尾 maxLen+1长度字符 如果对称 则回环长度+1 变更起始位置
func longestPalindrome(s string) string {
if len(s) == 0 {
return ""
}
start := 0
maxLen := 1
for index := range s {
l := index - maxLen
end := index + 1
if l >= 1 && sym(s[l-1:end]) {
start = l - 1
maxLen += 2
} else if l >= 0 && sym(s[l:end]) {
start = l
maxLen += 1
}
}
return s[start : start+maxLen]
}
// 当odd长度时对比中轴前后字符
// 当even长度时对比中轴前后字符
// 时间复杂度O(n/2)
// 当然还能选择反转字符对比字符串是否相等,但是相应的时间复杂度会变成 O(n)
func sym(s string) bool {
end := len(s) - 1
if len(s)&1 == 1 {
mid := len(s) / 2
for i := 0; i < mid; i++ {
if s[i] != s[end-i] {
return false
}
}
} else {
mid := len(s)/2 - 1
for i := 0; i <= mid; i++ {
if s[i] != s[end-i] {
return false
}
}
}
return true
}
|
[
3
] |
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"text/tabwriter"
)
//Rankins represents team ranking response
type Rankins struct {
Response []TeamRanking `json:"response"`
}
// Team represents a Formula 1 team
type Team struct {
ID int `json:"id"`
Name string `json:"name"`
}
// TeamRanking represens a ranking of a team
type TeamRanking struct {
Position int `json:"position"`
Team Team `json:"team"`
Points int `json:"points"`
Season int `json:"season"`
}
func main() {
//api key almak için https://rapidapi.com/api-sports/api/api-formula-1 adresini ziyaret edebilirsiniz
apiKey := flag.String("apikey", "", "API key for team rankings")
season := flag.String("season", "2019", "Season information for team rankings")
flag.Parse()
url := "https://api-formula-1.p.rapidapi.com/rankings/teams?season=" + *season
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("x-rapidapi-host", "api-formula-1.p.rapidapi.com")
req.Header.Add("x-rapidapi-key", string(*apiKey))
if err != nil {
panic(err.Error())
}
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err.Error())
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var rankings Rankins
json.Unmarshal(body, &rankings)
w := tabwriter.NewWriter(os.Stdout, 35, 0, 2, ' ', tabwriter.TabIndent)
for _, ranking := range rankings.Response {
fmt.Fprintf(w, "%s\t\t%d\n", ranking.Team.Name, ranking.Points)
}
w.Flush()
}
|
[
3
] |
//Following Resources were found helpful in completing this task
// https://tour.golang.org/
// https://github.com/vladimirvivien/go-networking/tree/master/currency/servertxt0
// https://golangcode.com/how-to-read-a-csv-file-into-a-struct/
//
// This program implements COVID-19 related data lookup service
// over TCP or Unix Data Socket. It loads data stored in a CSV
// file downloaded fromand uses a simple
// text-based protocol to interact with the user and send
// the data.
//
// Users send Date/Region search requests as a textual command in the form:
//
// <Region/Date> e.g. <Punjab> or <2020-03-14> or <KP>
//
// When the server receives the request, it is parsed and is then used
// to search the related data. The search result is then printed
// line-by-line back to the client.
// Testing:
// Netcat or telnet can be used to test this server by connecting and
// sending command using the format described above.
package main
import (
"encoding/csv"
"flag"
"fmt"
"log"
"net"
"os"
)
var D []Data //Slice of Data Structs containing all the information
type Data struct {
TestPos string // # ofPositive Tests
TestPer string // # of Tests Performed
Date string //Date
Discharged string // # of Patients Discharged
Expired string // # of Patients Expired
Admitted string // # of Patients Admitted
Region string //Region
}
func main() {
var addr string
var network string
flag.StringVar(&addr, "e", ":4040", "service endpoint [ip addr or socket path]")
flag.StringVar(&network, "n", "tcp", "network protocol [tcp,unix]")
flag.Parse()
// Open the file
csvfile, err := os.Open("TimeSeries_KeyIndicators.csv")
if err != nil {
log.Fatalln("Couldn't open the csv file", err)
}
// Parse the file
r, err := csv.NewReader(csvfile).ReadAll()
for i, d := range r {
if i > 0 {
info := Data{
TestPos: d[0],
TestPer: d[1],
Date: d[2],
Discharged: d[3],
Expired: d[4],
Admitted: d[5],
Region: d[6],
}
D = append(D, info)
}
}
// validate supported network protocols
switch network {
case "tcp", "tcp4", "tcp6", "unix":
default:
log.Fatalln("unsupported network protocol:", network)
}
// create a listener for provided network and host address
ln, err := net.Listen(network, addr)
if err != nil {
log.Fatal("failed to create listener:", err)
}
defer ln.Close()
log.Println("**** Corona Virus Data [Pakistan] ***")
log.Printf("Service started: (%s) %s\n", network, addr)
// connection-loop - handle incoming requests
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
if err := conn.Close(); err != nil {
log.Println("failed to close listener:", err)
}
continue
}
log.Println("Connected to", conn.RemoteAddr())
go handleConnection(conn)
}
}
//"Look for Given Input in the Data"
func Find(param string) []Data {
var res []Data
for _, d := range D {
if d.Date == param || d.Region == param {
res = append(res, d)
}
}
return res
}
func handleConnection(conn net.Conn) {
defer func() {
if err := conn.Close(); err != nil {
log.Println("error closing connection:", err)
}
}()
if _, err := conn.Write([]byte("Connected to Server...!\nUsage: Please Type REGION or DATE[yyyy-mm-dd]\n[Punjab,Balochistan,ICT,KP,2020-04-04 etc.]\n")); err != nil {
log.Println("error writing:", err)
return
}
// loop to stay connected with client until client breaks connection
for {
// buffer for client command
cmdLine := make([]byte, (1024 * 4))
n, err := conn.Read(cmdLine)
if n == 0 || err != nil {
log.Println("connection read error:", err)
return
}
param := string(cmdLine[:n-1])
result := Find(param)
if len(result) == 0 {
if _, err := conn.Write([]byte("Invalid Input / Nothing found\n")); err != nil {
log.Println("failed to write:", err)
}
continue
}
// send info line by line to the client with fmt.Sprintf()
for _, data := range result {
//JS, _ := json.Marshal(data)
_, err := conn.Write([]byte(
fmt.Sprintf(
"{\n Positive: %s,\n Performed: %s,\n Date: %s,\n Discharged: %s,\n Expired: %s,\n Admitted: %s,\n Region: %s,\n },\n\n",
data.TestPos, data.TestPer, data.Date, data.Discharged, data.Expired, data.Admitted, data.Region,
),
// fmt.Sprintf(string(JS)),
))
if err != nil {
log.Println("failed to write response:", err)
return
}
}
}
}
|
[
3
] |
package business
import (
"carrinho-api-gorm/model"
"carrinho-api-gorm/repository"
)
//IItensCarrinhoBusiness ...
type IItensCarrinhoBusiness interface {
ItensCarrinhoByCarrinhoID(carrinhoID string) (*[]model.ItensCarrinho, error)
}
//ItensCarrinhoBusiness ...
type ItensCarrinhoBusiness struct {
ItensCarrinhoRepository repository.IItensCarrinhoRepository
}
//NewItensCarrinhoBusiness ...
func NewItensCarrinhoBusiness(ItensCarrinhoRepository repository.IItensCarrinhoRepository) IItensCarrinhoBusiness {
return &ItensCarrinhoBusiness{ItensCarrinhoRepository}
}
//ItensCarrinhoByCarrinhoID ...
func (l *ItensCarrinhoBusiness) ItensCarrinhoByCarrinhoID(carrinhoID string) (*[]model.ItensCarrinho, error) {
return l.ItensCarrinhoRepository.ItensCarrinhoByCarrinhoID(carrinhoID)
}
|
[
2,
3
] |
package sign_up
import (
"github.com/kataras/iris"
authbase "grpc-demo/core/auth"
signUpEnum "grpc-demo/enums/sign_up"
accountException "grpc-demo/exceptions/account"
signupException "grpc-demo/exceptions/signup"
"grpc-demo/models/db"
paramsUtils "grpc-demo/utils/params"
)
func CreatSignUp(ctx iris.Context,auth authbase.AuthAuthorization) {
auth.CheckLogin()
userid := auth.AccountModel().Id
//TODO 选课码-班
params := paramsUtils.NewParamsParser(paramsUtils.RequestJsonInterface(ctx))
//classid := params.Int("class_id","班级id")
cid := params.Int("course_id","course_id")
//post方法写选课码
code := params.Str("code","选课码")
var s db.SignUp
if err := db.Driver.Where("user_id = ? and course_id = ?",auth.AccountModel().Id,cid).First(&s).Error;err == nil{
panic(signupException.SignedUp())
}
//var v db.Class
var c db.PartyClass
//通过选课码查找class1.id
if err := db.Driver.Where("code = ? and party_course_id = ?",code,cid).First(&c).Error;err != nil{
panic(signupException.SignupClassIdNotfound())
}
//classid = v.Id
//if err := db.Driver.GetOne("class1",classcode,&c);err != nil{
// panic(signupException.SignupClassIdNotfound())
// }
var signup db.SignUp
signup = db.SignUp{
//CourseId: v.CourseId,
UserId: userid,
ClassId: c.Id,
CourseId: cid,
Status: signUpEnum.NoDone,
}
db.Driver.Create(&signup)
ctx.JSON(iris.Map{
"id":signup.Id,
"class_id":c.Id,
})
}
//todo //error
func DeleteSignUp(ctx iris.Context,auth authbase.AuthAuthorization,sid int){
//todo 权限——管理员/创建人可删除
auth.CheckLogin()
tid := auth.AccountModel().Id
//判断管理员登录
var SignUpUser db.SignUp
if err := db.Driver.GetOne("sign_up",sid,&SignUpUser);err == nil{
if !auth.IsAdmin() && tid != SignUpUser.UserId{
panic(signupException.SignupUserNotHaveAuthority())
}
db.Driver.Delete(SignUpUser)
}
ctx.JSON(iris.Map{
"id":sid,
})
}
func PutSignUp(ctx iris.Context, cid int,auth authbase.AuthAuthorization) {
//修改表 修改cid传入的人的状态
auth.CheckLogin()
//判断登录
tid := auth.AccountModel().Id
var signup db.SignUp
if err := db.Driver.GetOne("sign_up", cid, &signup); err != nil {
panic(signupException.SignupUsernotfound())
}
//tid对比account_id 为空——无权限 或 非管理员——无权限
if !auth.IsAdmin() && tid != signup.UserId{
panic(accountException.NoPermission())
}
params := paramsUtils.NewParamsParser(paramsUtils.RequestJsonInterface(ctx))
params.Diff(signup)
//解释:params.Diff() 就是自己写的方法,如果前端传过来的请求体有这个字段,就修改,如果没有就从原来的这条记录拿。所以就不用if params.Has()
//修改对应的数据
if params.Has("status"){
signup.Status = int16(params.Int("status","状态"))
}
statusEnums := signUpEnum.NewStatusEnums()
if !statusEnums.Has(int(signup.Status)){
panic(signupException.StatusIsNotAllow())
}
db.Driver.Save(&signup)
ctx.JSON(iris.Map{
"id":signup.Id,
})
}
//todo
func SignUpListByCid(ctx iris.Context,auth authbase.AuthAuthorization,uid int) {
auth.CheckLogin()
tid := auth.AccountModel().Id
var Lists []struct{
Id int `json:"id"`
UserId int `json:"user_id"`
ClassId int `json:"class_id"`
CourseId int `json:"course_id"`
Status int16 `json:"status"`
}
var count int
var sg db.SignUp
table := db.Driver.Table("sign_up")
table = table.Where("class_id = ?",uid).First(&sg)
if !auth.IsAdmin() && tid != sg.UserId{
panic(signupException.SignupUserNotHaveAuthority())
}
limit := ctx.URLParamIntDefault("limit", 10)
page := ctx.URLParamIntDefault("page", 1)
table.Count(&count).Offset((page - 1) * limit).Limit(limit).
Select("id,user_id,class_id,course_id,status").Find(&Lists)
ctx.JSON(iris.Map{
"Lists" : Lists,
"total": count,
"limit": limit,
"page": page,
})
}
func SignUpListByAid(ctx iris.Context,auth authbase.AuthAuthorization,aid int){
auth.CheckLogin()
tid := auth.AccountModel().Id
var Lists []struct{
Id int `json:"id"`
UserId int `json:"user_id"`
ClassId int `json:"class_id"`
CourseId int `json:"course_id"`
Status int16 `json:"status"`
}
var count int
//TODO 判断登录
table := db.Driver.Table("sign_up")
table = table.Where("user_id = ?",aid)
if !auth.IsAdmin() && tid != aid{
panic(signupException.SignupUserNotHaveAuthority())
}
limit := ctx.URLParamIntDefault("limit", 10)
page := ctx.URLParamIntDefault("page", 1)
table.Count(&count).Offset((page - 1) * limit).Limit(limit).
Select("id,user_id,class_id,course_id,status").Find(&Lists)
ctx.JSON(iris.Map{
"Lists" : Lists,
"total": count,
"limit": limit,
"page": page,
})
}
func SignUpList(ctx iris.Context,auth authbase.AuthAuthorization){
auth.CheckAdmin()
var Lists []struct{
Id int `json:"id"`
UserId int `json:"user_id"`
ClassId int `json:"class_id"`
CourseId int `json:"course_id"`
Status int16 `json:"status"`
}
var count int
//TODO 判断登录
table := db.Driver.Table("sign_up")
limit := ctx.URLParamIntDefault("limit", 10)
page := ctx.URLParamIntDefault("page", 1)
table.Count(&count).Offset((page - 1) * limit).Limit(limit).
Select("id,user_id,class_id,course_id,status").Find(&Lists)
ctx.JSON(iris.Map{
"Lists" : Lists,
"total": count,
"limit": limit,
"page": page,
})
}
//func SignUpMegt(ctx iris.Context) {
// params := paramsUtils.NewParamsParser(paramsUtils.RequestJsonInterface(ctx))
// ids := params.List("ids", "id列表")
// Registrant_data := make([]interface{}, 0, len(ids))
// Registrants := db.Driver.GetMany("signup", ids, db.SignUp{})
// for _, Registrant := range Registrants {
// func(Registrant_data *[]interface{}) {
// info := paramsUtils.ModelToDict(Registrant, []string{"Id","UserId",
// "ClassId"})
// *Registrant_data = append(*Registrant_data, info)
// defer func() {
// recover()
// }()
// }(&Registrant_data)
// }
//
// ctx.JSON(Registrant_data)
//}
|
[
3
] |
package accounts
import (
"errors"
"fmt"
)
// Account struct should be exported
type Account struct {
owner string
balance int
}
var errNoMoney = errors.New("Can't withdraw")
// NewAccount creates Account
func NewAccount(owner string) *Account {
account := Account{owner: owner, balance: 0}
return &account
}
//Deposit x amount on your account
func (theAccount *Account) Deposit(amount int) {
theAccount.balance += amount
}
//Balance of your account
func (theAccount Account) Balance() int {
return theAccount.balance
}
//Withdraw x amount from your account
func (theAccount *Account) Withdraw(amount int) error {
if theAccount.balance < amount {
return errNoMoney
}
theAccount.balance -= amount
return nil
}
//ChangeOwner of the account
func (theAccount *Account) ChangeOwner(newOwner string) {
theAccount.owner = newOwner
}
//Owner of the account
func (theAccount Account) Owner() string {
return theAccount.owner
}
func (theAccount Account) String() string {
return fmt.Sprint(theAccount.Owner(), "'s account.\nHas: ", theAccount.Balance())
}
|
[
3
] |
package models
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/jrallison/go-workers"
opentracing "github.com/opentracing/opentracing-go"
"github.com/spf13/viper"
"github.com/topfreegames/extensions/v9/mongo/interfaces"
"github.com/topfreegames/extensions/v9/tracing"
"github.com/topfreegames/khan/mongo"
"github.com/uber-go/zap"
)
// MongoWorker is the worker that will update mongo
type MongoWorker struct {
Logger zap.Logger
MongoDB interfaces.MongoDB
MongoCollectionTemplate string
}
// NewMongoWorker creates and returns a new mongo worker
func NewMongoWorker(logger zap.Logger, config *viper.Viper) *MongoWorker {
w := &MongoWorker{
Logger: logger,
}
w.configureMongoWorker(config)
return w
}
func (w *MongoWorker) configureMongoWorker(config *viper.Viper) {
w.MongoCollectionTemplate = config.GetString("mongodb.collectionTemplate")
w.MongoDB = mongo.GetConfiguredMongoClient()
}
// PerformUpdateMongo updates the clan into mongodb
func (w *MongoWorker) PerformUpdateMongo(m *workers.Msg) {
tags := opentracing.Tags{"component": "go-workers"}
span := opentracing.StartSpan("PerformUpdateMongo", tags)
defer span.Finish()
defer tracing.LogPanic(span)
ctx := opentracing.ContextWithSpan(context.Background(), span)
item := m.Args()
data := item.MustMap()
game := data["game"].(string)
op := data["op"].(string)
clan := data["clan"].(map[string]interface{})
clanID := data["clanID"].(string)
w.updateClanIntoMongoDB(ctx, game, op, clan, clanID)
}
// InsertGame creates a game inside Mongo
func (w *MongoWorker) InsertGame(ctx context.Context, gameID string, clan *Clan) error {
clanWithNamePrefixes := clan.NewClanWithNamePrefixes()
clanJSON, err := json.Marshal(clanWithNamePrefixes)
if err != nil {
return errors.New("Could not serialize clan")
}
var clanMap map[string]interface{}
json.Unmarshal(clanJSON, &clanMap)
w.updateClanIntoMongoDB(ctx, gameID, "update", clanMap, clan.PublicID)
return nil
}
func (w *MongoWorker) updateClanIntoMongoDB(
ctx context.Context, gameID string, op string, clan map[string]interface{}, clanID string,
) {
logger := w.Logger.With(
zap.String("game", gameID),
zap.String("operation", op),
zap.String("clanId", clanID),
zap.String("source", "PerformUpdateMongo"),
)
if w.MongoDB != nil {
mongoCol, mongoSess := w.MongoDB.WithContext(ctx).C(fmt.Sprintf(w.MongoCollectionTemplate, gameID))
defer mongoSess.Close()
if op == "update" {
logger.Debug(fmt.Sprintf("updating clan %s into mongodb", clanID))
info, err := mongoCol.UpsertId(clanID, clan)
if err != nil {
panic(err)
} else {
logger.Debug(fmt.Sprintf("ChangeInfo: updated %d, removed %d, matched %d", info.Updated, info.Removed, info.Matched))
}
} else if op == "delete" {
logger.Debug(fmt.Sprintf("deleting clan %s from mongodb", clanID))
err := mongoCol.RemoveId(clanID)
if err != nil {
panic(err)
}
}
}
}
|
[
6
] |
package pakpos_test_1
import (
"fmt"
//. "github.com/eaciit/pakpos/v1"
"github.com/eaciit/toolkit"
. "pakpos/v1"
//"strings"
"testing"
"time"
//"net/http"
"os"
)
var (
b *Broadcaster
broadcastSecret string = "uliyamahalin"
userSecret string
userid string = "arief"
password string = "darmawan"
subs []*Subscriber
)
func init() {
basepath, _ := os.Getwd()
b = new(Broadcaster)
//fmt.Println(basepath)
cert := basepath + "/cert.pem"
key := basepath + "/key.pem"
b.Start("https://localhost:12345", broadcastSecret, cert, key)
/*
for i := 0; i < 3; i++ {
subs = append(subs, new(Subscriber))
address := fmt.Sprintf("localhost:%d", 2345+i)
subs[i].BroadcasterAddress = "http://" + b.Address
subs[i].Start(address)
}
*/
}
func TestLogin(t *testing.T) {
r, e := call(b.Address+"/broadcaster/login", "POST",
toolkit.M{}.Set("userid", userid).Set("password", password).ToBytes("json", nil), 200)
if e != nil {
t.Errorf("Fail to login. " + e.Error())
return
}
userSecret = r.Data.(string)
t.Logf("Login success. Secret token is " + userSecret)
}
func TestAddNodes(t *testing.T) {
for i := 0; i < 3; i++ {
sub := new(Subscriber)
//sub.Broadcaster = "http://localhost:12345"
e := sub.Start(fmt.Sprintf("localhost:%d", 54321+i), b.Address, broadcastSecret)
if e != nil {
t.Errorf("Fail start node %d : %s", i, e.Error())
} else {
t.Logf("%s has been subscribed with secret: %s", sub.Address, sub.Secret)
}
subs = append(subs, sub)
}
}
func TestBroadcast(t *testing.T) {
_, e := call(b.Address+"/broadcaster/broadcast", "POST",
toolkit.M{}.
Set("userid", userid).
Set("secret", userSecret).
Set("key", "BC01").
Set("data", "Ini adalah Broadcast Message 01").
ToBytes("json", nil),
200)
if e != nil {
t.Errorf("%s %s", b.Address+"/broadcaster/broadcast", e.Error())
return
}
time.Sleep(2 * time.Second)
/*
var msg Message
//toolkit.Unjson(toolkit.Jsonify(r.Data.(map[string]interface{})), &msg)
e = r.Cast(&msg, "json")
if e != nil {
t.Errorf("Unable to serde result: %s", e.Error())
return
}
expiry := msg.Expiry
for {
r, e := call(b.Address+"/broadcaster/msgstatus", "POST",
toolkit.M{}.Set("userid", userid).
Set("secret", userSecret).
Set("key", "BC01").
ToBytes("json", nil),
200)
if e == nil {
t.Logf("%v %s", time.Now(), r.Data.(string))
} else {
str := e.Error()
if strings.Contains(str, "not exist") {
break
} else {
t.Errorf(str)
break
}
}
time.Sleep(1 * time.Second)
if time.Now().After(expiry) {
t.Errorf("Message expiry exceeded. Process will be exited")
return
}
}
*/
}
func TestSubcribeChannel(t *testing.T) {
_, e := toolkit.CallResult(b.Address+"/broadcaster/subscribechannel", "POST",
toolkit.M{}.Set("Subscriber", subs[1].Address).Set("Secret", subs[1].Secret).Set("Channel", "Ch01").ToBytes("json", nil))
if e != nil {
t.Error(e)
return
}
_, e = call(b.Address+"/broadcaster/broadcast", "POST",
toolkit.M{}.
Set("userid", userid).
Set("secret", userSecret).
Set("key", "Ch01:Message01").
Set("data", "Ini adalah Channel 01 - Broadcast Message 01").
ToBytes("json", nil),
200)
if e != nil {
t.Errorf("%s %s", b.Address+"/broadcaster/broadcast", e.Error())
return
}
time.Sleep(2 * time.Second)
}
func TestQue(t *testing.T) {
_, e := toolkit.CallResult(b.Address+"/broadcaster/que", "POST",
toolkit.M{}.Set("userid", userid).Set("secret", userSecret).Set("key", "Ch01:QueMessage01").Set("data", "Ini adalah Channel 01 Que Message 01").ToBytes("json", nil))
if e != nil {
t.Errorf("Sending Que Error: " + e.Error())
return
}
time.Sleep(3 * time.Second)
found := 0
for _, s := range subs {
_, e = toolkit.CallResult(s.Address+"/subscriber/collectmessage", "POST",
toolkit.M{}.Set("subscriber", "http://localhost:12345").Set("secret", s.Secret).Set("key", "").ToBytes("json", nil))
if e == nil {
found++
} else {
t.Logf("Node %s, could not collect message: %s", s.Address, e.Error())
}
}
if found != 1 {
t.Errorf("Que not collected properly. Should only 1 subscriber collecting it, got %d", found)
}
}
func TestQueInvalid(t *testing.T) {
_, e := toolkit.CallResult(b.Address+"/broadcaster/que", "POST",
toolkit.M{}.Set("userid", userid).Set("secret", userSecret).Set("key", "Ch01:QueMessage02").Set("data", "Ini adalah Channel 02 Que Message 02").ToBytes("json", nil))
if e != nil {
t.Errorf("Sending Que Error: " + e.Error())
return
}
time.Sleep(15 * time.Second)
}
func TestClose0(t *testing.T) {
_, e := call(b.Address+"/broadcaster/stop", "GET",
toolkit.M{}.Set("userid", userid).Set("secret", userSecret).ToBytes("json", nil), 200)
if e != nil {
t.Errorf(e.Error())
}
}
func call(url, call string, data []byte, expectedStatus int) (*toolkit.Result, error) {
cfg := toolkit.M{}
if expectedStatus != 0 {
cfg.Set("expectedstatus", expectedStatus)
}
r, e := toolkit.HttpCall(url, call, data, cfg)
if e != nil {
return nil, fmt.Errorf(url + " Call Error: " + e.Error())
}
result := toolkit.NewResult()
bs := toolkit.HttpContent(r)
edecode := toolkit.Unjson(bs, result)
if edecode != nil {
return nil, fmt.Errorf(url + " Http Result Decode Error: " + edecode.Error() + "\nFollowing got: " + string(bs))
}
if result.Status == toolkit.Status_NOK {
return nil, fmt.Errorf(url + " Http Result Error: " + result.Message)
}
return result, nil
}
|
[
3
] |
package client
import (
"../datastruc"
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
b64 "encoding/base32"
"encoding/binary"
"encoding/gob"
"fmt"
"log"
"math/rand"
"net"
"os"
"time"
)
type ClienKeys struct {
Clienprivks map[int]string
Clientpubkstrs map[int]string
}
type Client struct {
id int
miners []int
minerIPAddress map[int]string
sendtxCh chan datastruc.Datatosend
sendtxtooneCh []chan datastruc.Datatosend
nodePubKey *ecdsa.PublicKey
nodePrvKey *ecdsa.PrivateKey
nodePubkeystr string
nodePrvkeystr string
nodeaccountstr string // a base64 string
sendvolume int
starttime time.Time
}
func (clk *ClienKeys) GetSerialize() []byte {
var buff bytes.Buffer
gob.Register(elliptic.P256())
enc := gob.NewEncoder(&buff)
err := enc.Encode(clk)
if err != nil {
log.Panic(err)
}
content := buff.Bytes()
return content
}
func (clk *ClienKeys) GetDeserializeFromFile(fn string) {
var conten []byte
file, err := os.Open(fn)
if err != nil {
fmt.Println("open clientkey file error")
}
dec := gob.NewDecoder(file)
err = dec.Decode(&conten)
if err != nil {
fmt.Println("read clientkey file error")
}
var buff bytes.Buffer
buff.Write(conten)
gob.Register(elliptic.P256())
decc := gob.NewDecoder(&buff)
err = decc.Decode(clk)
if err != nil {
fmt.Println("serialized client key decoding error")
}
}
func CreateClient(id int, servernum int, privateKey *ecdsa.PrivateKey, allips []string, inseach int) *Client {
client := &Client{}
client.starttime = time.Now()
client.id = id
client.miners = make([]int, 0)
client.minerIPAddress = make(map[int]string)
total := servernum * inseach
for i := 0; i < total; i++ {
client.miners = append(client.miners, i)
order := i / inseach
client.minerIPAddress[i] = allips[order] + ":4" + datastruc.GenerateTwoBitId(i) + "1"
}
//client.generateServerOrderIp(servernum)
fmt.Println("client ", id, "will send tx to the following servers", client.miners)
fmt.Println("client ", id, "will send tx to the following address", client.minerIPAddress)
client.sendtxCh = make(chan datastruc.Datatosend)
client.sendtxtooneCh = make([]chan datastruc.Datatosend, total)
for i := 0; i < total; i++ {
client.sendtxtooneCh[i] = make(chan datastruc.Datatosend)
}
publicKey := &privateKey.PublicKey
client.nodePrvKey = privateKey
client.nodePubKey = publicKey
client.nodePrvkeystr = datastruc.EncodePrivate(privateKey)
client.nodePubkeystr = datastruc.EncodePublic(publicKey)
hv := sha256.Sum256([]byte(client.nodePubkeystr))
client.nodeaccountstr = b64.StdEncoding.EncodeToString(hv[:])
//fmt.Println("client", client.id, "privatekey is", client.nodePrvKey)
fmt.Println("client", client.id, "pubkey string is", client.nodePubkeystr)
return client
}
func (client *Client) Run() {
fmt.Println("client", client.id, "starts running")
time.Sleep(time.Second * 4)
go client.sendloop()
val := rand.Intn(400)
time.Sleep(time.Millisecond * time.Duration(val))
rand.Seed(time.Now().UTC().UnixNano() + int64(client.id))
for i := 0; i < 40000; i++ {
rannum := rand.Uint64()
ok, newtx := datastruc.MintNewTransaction(rannum, client.nodeaccountstr, client.nodePrvKey)
//fmt.Println("analysing tx:")
//fmt.Println("tx kind", newtx.Kind, "length:", len(newtx.Kind))
//fmt.Println("tx timestamp", newtx.Timestamp, "length:", unsafe.Sizeof(newtx.Timestamp))
//fmt.Println("tx source", newtx.Source, "length:", len(newtx.Source))
//fmt.Println("tx recipient", newtx.Recipient, "length:", len(newtx.Recipient))
//fmt.Println("tx value", newtx.Value, "length:", unsafe.Sizeof(newtx.Value))
//fmt.Println("tx sig", newtx.Sig, "length:", unsafe.Sizeof(newtx.Sig))
if ok {
client.BroadcastMintedTransaction(newtx, client.id, client.miners)
if i%1000 == 0 {
//fmt.Println("tx", i, "timestamp is", newtx.Timestamp)
elaps := time.Since(client.starttime).Seconds()
fmt.Println("client", client.id, "sends", i, "txs in", elaps, "s")
}
}
if i%5 == 0 {
time.Sleep(time.Millisecond * 50) // 25ms seems good, 30ms also good for test.
}
//val := rand.Intn(2) + 1
//val := 10000
//time.Sleep(time.Millisecond*10)
}
fmt.Println("client", client.id, "stops, time:", time.Since(client.starttime).Seconds(), "s")
}
func (client *Client) sendloop() {
for i := 0; i < len(client.minerIPAddress); i++ {
go client.sendtooneloop(i)
}
for {
select {
case datatosend := <-client.sendtxCh:
for i := 0; i < len(client.sendtxtooneCh); i++ {
client.sendtxtooneCh[i] <- datatosend
}
}
}
}
func (client *Client) sendtooneloop(destid int) {
trytime := 0
for {
destip := client.minerIPAddress[destid]
conn, err := net.Dial("tcp", destip)
if err != nil {
fmt.Println("connect failed, will retry later\n", err.Error())
if trytime <= 3 {
fmt.Println("will re connect soon, time:", time.Since(client.starttime).Seconds(), "s")
t := rand.Intn(1000)
time.Sleep(time.Millisecond * time.Duration(t))
trytime += 1
} else {
fmt.Println("try time reaches the upper bound, stops")
time.Sleep(time.Second * 40)
}
} else {
defer conn.Close()
innerloop:
for {
select {
case datatosend := <-client.sendtxtooneCh[destid]:
data := append(datastruc.CommandToBytes(datatosend.MsgType), datatosend.Msg...)
l := len(data)
magicNum := make([]byte, 4)
binary.BigEndian.PutUint32(magicNum, 0x123456)
lenNum := make([]byte, 2)
binary.BigEndian.PutUint16(lenNum, uint16(l))
packetBuf := bytes.NewBuffer(magicNum)
packetBuf.Write(lenNum)
packetBuf.Write(data)
client.sendvolume += len(packetBuf.Bytes())
_, err := conn.Write(packetBuf.Bytes())
//datalen := len(packetBuf.Bytes())
//blank := make([]byte, 1000-datalen)
//packetBuf.Write(blank)
if err != nil {
fmt.Println("write failed, time:", time.Since(client.starttime).Seconds(), "s")
fmt.Printf("err: %v", err)
t := rand.Intn(100)
fmt.Println("will re connect soon, time:", time.Since(client.starttime).Seconds(), "s")
time.Sleep(time.Millisecond * time.Duration(t))
break innerloop
} else {
//fmt.Println("client", client.id, "total bytes sent is ", client.sendvolume)
}
}
}
}
}
}
func (client *Client) BroadcastMintedTransaction(newTransaction datastruc.Transaction, id int, dest []int) {
var buff bytes.Buffer
gob.Register(elliptic.P256())
enc := gob.NewEncoder(&buff)
err := enc.Encode(newTransaction)
if err != nil {
log.Panic(err)
}
content := buff.Bytes()
//fmt.Println("the tx has size:", len(content))
datatosend := datastruc.Datatosend{dest, "mintedtx", content}
client.sendtxCh <- datatosend
}
func commandToBytes(command string) []byte {
//command -> byte
var bytees [commandLength]byte
for i, c := range command {
bytees[i] = byte(c)
}
return bytees[:]
}
func sendData(data []byte, addr string, id int) {
conn, err := net.Dial(protocol, addr)
if err != nil {
fmt.Println("client", id, ":", addr, "is not available")
//fmt.Printf("%s is not available\n", addr)
} else {
defer conn.Close()
_, err = conn.Write(data)
if err != nil {
fmt.Println("send error")
log.Panic(err)
}
}
}
|
[
3,
6
] |
package validation
import (
"fmt"
"regexp"
"strings"
"github.com/nginxinc/kubernetes-ingress/internal/configs"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
const (
escapedStringsFmt = `([^"\\]|\\.)*`
escapedStringsErrMsg = `must have all '"' (double quotes) escaped and must not end with an unescaped '\' (backslash)`
)
var escapedStringsFmtRegexp = regexp.MustCompile("^" + escapedStringsFmt + "$")
// ValidateEscapedString validates an escaped string.
func ValidateEscapedString(body string, examples ...string) error {
if !escapedStringsFmtRegexp.MatchString(body) {
msg := validation.RegexError(escapedStringsErrMsg, escapedStringsFmt, examples...)
return fmt.Errorf(msg)
}
return nil
}
func validateVariable(nVar string, validVars map[string]bool, fieldPath *field.Path) field.ErrorList {
if !validVars[nVar] {
msg := fmt.Sprintf("'%v' contains an invalid NGINX variable. Accepted variables are: %v", nVar, mapToPrettyString(validVars))
return field.ErrorList{field.Invalid(fieldPath, nVar, msg)}
}
return nil
}
// isValidSpecialHeaderLikeVariable validates special variables $http_, $jwt_header_, $jwt_claim_
func isValidSpecialHeaderLikeVariable(value string) []string {
// underscores in a header-like variable represent '-'.
errMsgs := validation.IsHTTPHeaderName(strings.Replace(value, "_", "-", -1))
if len(errMsgs) >= 1 || strings.Contains(value, "-") {
return []string{"a valid special variable must consists of alphanumeric characters or '_'"}
}
return nil
}
func parseSpecialVariable(nVar string, fieldPath *field.Path) (name string, value string, allErrs field.ErrorList) {
// parse NGINX Plus variables
if strings.HasPrefix(nVar, "jwt_header") || strings.HasPrefix(nVar, "jwt_claim") {
parts := strings.SplitN(nVar, "_", 3)
if len(parts) != 3 {
allErrs = append(allErrs, field.Invalid(fieldPath, nVar, "is invalid variable"))
return name, value, allErrs
}
// ex: jwt_header_name_one -> jwt_header, name_one
return strings.Join(parts[:2], "_"), parts[2], allErrs
}
// parse common NGINX and NGINX Plus variables
parts := strings.SplitN(nVar, "_", 2)
if len(parts) != 2 {
allErrs = append(allErrs, field.Invalid(fieldPath, nVar, "is invalid variable"))
return name, value, allErrs
}
// ex: http_name_one -> http, name_one
return parts[0], parts[1], allErrs
}
func validateSpecialVariable(nVar string, fieldPath *field.Path, isPlus bool) field.ErrorList {
name, value, allErrs := parseSpecialVariable(nVar, fieldPath)
if len(allErrs) > 0 {
return allErrs
}
addErrors := func(errors []string) {
for _, msg := range errors {
allErrs = append(allErrs, field.Invalid(fieldPath, nVar, msg))
}
}
switch name {
case "arg":
addErrors(isArgumentName(value))
case "http":
addErrors(isValidSpecialHeaderLikeVariable(value))
case "cookie":
addErrors(isCookieName(value))
case "jwt_header", "jwt_claim":
if !isPlus {
allErrs = append(allErrs, field.Forbidden(fieldPath, "is only supported in NGINX Plus"))
} else {
addErrors(isValidSpecialHeaderLikeVariable(value))
}
default:
allErrs = append(allErrs, field.Invalid(fieldPath, nVar, "unknown special variable"))
}
return allErrs
}
func validateStringWithVariables(str string, fieldPath *field.Path, specialVars []string, validVars map[string]bool, isPlus bool) field.ErrorList {
if strings.HasSuffix(str, "$") {
return field.ErrorList{field.Invalid(fieldPath, str, "must not end with $")}
}
allErrs := field.ErrorList{}
for i, c := range str {
if c == '$' {
msg := "variables must be enclosed in curly braces, for example ${host}"
if str[i+1] != '{' {
return field.ErrorList{field.Invalid(fieldPath, str, msg)}
}
if !strings.Contains(str[i+1:], "}") {
return field.ErrorList{field.Invalid(fieldPath, str, msg)}
}
}
}
nginxVars := captureVariables(str)
for _, nVar := range nginxVars {
special := false
for _, specialVar := range specialVars {
if strings.HasPrefix(nVar, specialVar) {
special = true
break
}
}
if special {
allErrs = append(allErrs, validateSpecialVariable(nVar, fieldPath, isPlus)...)
} else {
allErrs = append(allErrs, validateVariable(nVar, validVars, fieldPath)...)
}
}
return allErrs
}
func validateTime(time string, fieldPath *field.Path) field.ErrorList {
if time == "" {
return nil
}
if _, err := configs.ParseTime(time); err != nil {
return field.ErrorList{field.Invalid(fieldPath, time, err.Error())}
}
return nil
}
// http://nginx.org/en/docs/syntax.html
const offsetErrMsg = "must consist of numeric characters followed by a valid size suffix. 'k|K|m|M|g|G"
func validateOffset(offset string, fieldPath *field.Path) field.ErrorList {
if offset == "" {
return nil
}
if _, err := configs.ParseOffset(offset); err != nil {
msg := validation.RegexError(offsetErrMsg, configs.OffsetFmt, "16", "32k", "64M", "2G")
return field.ErrorList{field.Invalid(fieldPath, offset, msg)}
}
return nil
}
// http://nginx.org/en/docs/syntax.html
const sizeErrMsg = "must consist of numeric characters followed by a valid size suffix. 'k|K|m|M"
func validateSize(size string, fieldPath *field.Path) field.ErrorList {
if size == "" {
return nil
}
if _, err := configs.ParseSize(size); err != nil {
msg := validation.RegexError(sizeErrMsg, configs.SizeFmt, "16", "32k", "64M")
return field.ErrorList{field.Invalid(fieldPath, size, msg)}
}
return nil
}
// validateSecretName checks if a secret name is valid.
// It performs the same validation as ValidateSecretName from k8s.io/kubernetes/pkg/apis/core/validation/validation.go.
func validateSecretName(name string, fieldPath *field.Path) field.ErrorList {
if name == "" {
return nil
}
allErrs := field.ErrorList{}
for _, msg := range validation.IsDNS1123Subdomain(name) {
allErrs = append(allErrs, field.Invalid(fieldPath, name, msg))
}
return allErrs
}
func mapToPrettyString(m map[string]bool) string {
var out []string
for k := range m {
out = append(out, k)
}
return strings.Join(out, ", ")
}
// ValidateParameter validates a parameter against a map of valid parameters for the directive
func ValidateParameter(nPar string, validParams map[string]bool, fieldPath *field.Path) field.ErrorList {
if !validParams[nPar] {
msg := fmt.Sprintf("'%v' contains an invalid NGINX parameter. Accepted parameters are: %v", nPar, mapToPrettyString(validParams))
return field.ErrorList{field.Invalid(fieldPath, nPar, msg)}
}
return nil
}
|
[
6
] |
// Copyright 2015, Yahoo Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package arachni
import (
"fmt"
"os/exec"
"strings"
"github.com/yahoo/gryffin"
)
type Fuzzer struct{}
func (s *Fuzzer) Fuzz(g *gryffin.Scan) (count int, err error) {
var cookies []string
for _, c := range g.Cookies {
cookies = append(cookies, c.String())
}
args := []string{
"--checks", "xss*", "--output-only-positives",
"--http-request-concurrency", "1",
"--http-request-timeout", "10000",
"--timeout", "00:03:00",
"--scope-dom-depth-limit", "0",
"--scope-directory-depth-limit", "0",
"--scope-page-limit", "1",
"--audit-with-both-methods",
"--report-save-path", "/dev/null",
"--snapshot-save-path", "/dev/null",
}
args = append(args, g.Request.URL.String())
cmd := exec.Command("arachni", args...)
//...
}
func (s *Fuzzer) extract(g *gryffin.Scan, output string) (count int) {
for _, l := range strings.Split(output, "\n") {
l = strings.TrimSpace(l)
switch {
case strings.HasPrefix(l, "[~] Affected page"):
g.Logm("Arachni.Findings", l)
count++
}
}
return
}
|
[
3,
7
] |
package mysql
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"os"
)
var db *sql.DB
func init() {
// MySQLSource : 要连接的数据库源;
// 其中test:test 是用户名密码;
// 127.0.0.1:3306 是ip及端口;
// fileserver 是数据库名;
// charset=utf8 指定了数据以utf8字符编码进行传输
db, _ = sql.Open("mysql", "root:123qwe!@#@tcp(10.10.10.33:3306)/test?charset=utf8&parseTime=true&loc=Asia%2FChongqing")
db.SetMaxOpenConns(100)
err := db.Ping()
if err != nil {
fmt.Println("Connect to mysql error : ", err)
os.Exit(1)
}
}
/**
获取链接对象
*/
func GetDBConn() *sql.DB {
return db
}
/**
获取链接对象
*/
func ExecSql(sql string, params ...interface{}) bool {
stmt, e := GetDBConn().Prepare(sql)
if e != nil {
fmt.Println("Sql Prepare error : ", e)
return false
}
defer stmt.Close()
result, e := stmt.Exec(params...)
if e != nil {
fmt.Println(" Exec sql error : ", e)
return false
}
rf, e := result.RowsAffected()
if nil != e {
fmt.Println("err:", e, "rf:", rf)
return false
}
if rf == 0 {
return false
}
return true
}
func ParseRows(rows *sql.Rows) []map[string]interface{} {
columns, _ := rows.Columns()
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for j := range values {
scanArgs[j] = &values[j]
}
record := make(map[string]interface{})
records := make([]map[string]interface{}, 0)
for rows.Next() {
//将行数据保存到record字典
err := rows.Scan(scanArgs...)
checkErr(err)
for i, col := range values {
if col != nil {
record[columns[i]] = col
}
}
records = append(records, record)
}
return records
}
func checkErr(err error) {
if err != nil {
log.Fatal(err)
panic(err)
}
}
|
[
3
] |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package model
import (
"encoding/json"
"github.com/InsZVA/incubator-rocketmq-externals/rocketmq-go/api/model"
)
//ConsumerRunningInfo this client's consumer running info
type ConsumerRunningInfo struct {
Properties map[string]string `json:"properties"`
MqTable map[rocketmqm.MessageQueue]ProcessQueueInfo `json:"mqTable"`
}
//Encode ConsumerRunningInfo to byte array
func (c *ConsumerRunningInfo) Encode() (jsonByte []byte, err error) {
mqTableJsonStr := "{"
first := true
var keyJson []byte
var valueJson []byte
for key, value := range c.MqTable {
keyJson, err = json.Marshal(key)
if err != nil {
return
}
valueJson, err = json.Marshal(value)
if err != nil {
return
}
if first == false {
mqTableJsonStr = mqTableJsonStr + ","
}
mqTableJsonStr = mqTableJsonStr + string(keyJson) + ":" + string(valueJson)
first = false
}
mqTableJsonStr = mqTableJsonStr + "}"
var propertiesJson []byte
propertiesJson, err = json.Marshal(c.Properties)
if err != nil {
return
}
jsonByte = c.formatEncode("\"properties\"", string(propertiesJson), "\"mqTable\"", string(mqTableJsonStr))
return
}
func (c *ConsumerRunningInfo) formatEncode(kVList ...string) []byte {
jsonStr := "{"
first := true
for i := 0; i+1 < len(kVList); i += 2 {
if first == false {
jsonStr = jsonStr + ","
}
keyJson := kVList[i]
valueJson := kVList[i+1]
jsonStr = jsonStr + string(keyJson) + ":" + string(valueJson)
first = false
}
jsonStr = jsonStr + "}"
return []byte(jsonStr)
}
|
[
0,
3
] |
package main
import (
"fmt"
"strconv"
"../../aoc"
)
func Part1(input string) string {
result := 0
for _, c := range input {
if c == '(' {
result += 1
} else if c == ')' {
result -= 1
} else {
// log.Fatal("found unknown rune", c)
}
}
return strconv.Itoa(result)
}
func Part2(input string) string {
result := 0
for i, c := range input {
if c == '(' {
result += 1
} else if c == ')' {
result -= 1
}
if result == -1 {
return strconv.Itoa(i + 1)
}
}
return strconv.Itoa(-1)
}
func main() {
fmt.Println(Part1(aoc.ReadInput())) // 138
fmt.Println(Part2(aoc.ReadInput())) // 1771
}
|
[
5
] |
// 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 trr
import (
"errors"
"fmt"
"log"
"math/rand"
"net"
"net/rpc"
"sync"
"syscall"
"github.com/coreos/etcd/raft/raftpb"
)
const Debug = 1
func DPrintf(format string, a ...interface{}) (n int, err error) {
if Debug > 0 {
log.Printf(format, a...)
}
return
}
type KVRaft struct {
mu sync.Mutex
l net.Listener
me int
dead bool // for testing
unreliable bool // for testing
// Your definitions here.
store *kvstore
srvStopc chan struct{}
}
func (kv *KVRaft) Get(args *GetArgs, reply *GetReply) error {
log.Println("[GET]", args)
if args.Key == "" {
log.Println("[GET]", InvalidParam)
return errors.New(InvalidParam)
}
if v, ok := kv.store.Lookup(args.Key); ok {
reply.Value = v
return nil
}
reply.Err = ErrNoKey
return errors.New(ErrNoKey)
}
func (kv *KVRaft) Put(args *PutArgs, reply *PutReply) error {
log.Println("[PUT]", args)
if args.Key == "" || len(args.Value) == 0 {
log.Println("[PUT]", InvalidParam)
err := errors.New(InvalidParam)
reply.Err = InvalidParam
return err
}
if v, ok := kv.store.Lookup(args.Key); ok {
reply.PreviousValue = v
}
reply.Err = "NIL"
log.Println("[PUT] ", args)
kv.store.Propose(args.Key, args.Value)
return nil
}
// tell the server to shut itself down.
// please do not change this function.
func (kv *KVRaft) kill() {
DPrintf("Kill(%d): die\n", kv.me)
kv.dead = true
close(kv.srvStopc)
//remove socket file
}
func StartServer(rpcPort string, me int) *KVRaft {
return startServer(rpcPort, me, []string{rpcPort}, false)
}
func StartClusterServers(rpcPort string, me int, cluster []string) *KVRaft {
return startServer(rpcPort, me, cluster, false)
}
func StarServerJoinCluster(rpcPort string, me int) *KVRaft {
return startServer(rpcPort, me, []string{rpcPort}, true)
}
func startServer(serversPort string, me int, cluster []string, join bool) *KVRaft {
//gob.Register(Op{})
kv := new(KVRaft)
rpcs := rpc.NewServer()
rpcs.Register(kv)
proposeC := make(chan string)
//defer close(proposeC)
confChangeC := make(chan raftpb.ConfChange)
//defer close(confChangeC)
//node
commitC, errorC, stopc := newRaftNode(me, cluster, join, proposeC, confChangeC)
kv.srvStopc = stopc
//kvstore
kv.store = newKVStore(proposeC, commitC, errorC)
log.Println("[server] ", me, " ==> ", serversPort)
l, e := net.Listen("tcp", serversPort)
if e != nil {
log.Fatal("listen error: ", e)
}
kv.l = l
go func() {
for kv.dead == false {
conn, err := kv.l.Accept()
if err == nil && kv.dead == false {
if kv.unreliable && (rand.Int63()%1000) < 100 {
// discard the request.
conn.Close()
} else if kv.unreliable && (rand.Int63()%1000) < 200 {
// process the request but force discard of reply.
c1 := conn.(*net.UnixConn)
f, _ := c1.File()
err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
if err != nil {
fmt.Printf("shutdown: %v\n", err)
}
go rpcs.ServeConn(conn)
} else {
go rpcs.ServeConn(conn)
}
} else if err == nil {
conn.Close()
}
if err != nil && kv.dead == false {
fmt.Printf("KVRaft(%v) accept: %v\n", me, err.Error())
kv.kill()
}
}
}()
return kv
}
|
[
3,
5
] |
/*
@Time : 2020/4/19 1:38 下午
@Author : Rebeta
@Email : [email protected]
@File : chaos
@Software: GoLand
*/
package gin
import (
"context"
"github.com/offcn-jl/gscf/fake-http"
"github.com/tencentyun/scf-go-lib/cloudevents/scf"
"github.com/tencentyun/scf-go-lib/cloudfunction"
)
// HandlerFunc defines the handler used by gin middleware as return value. // fixme 翻译
type HandlerFunc func(*Context)
// HandlersChain defines a HandlerFunc array. // fixme 翻译
type HandlersChain []HandlerFunc
// Last returns the last handler in the chain. ie. the last handler is the main own. // fixme 翻译
func (c HandlersChain) Last() HandlerFunc {
if length := len(c); length > 0 {
return c[length-1]
}
return nil
}
// Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
// Create an instance of Engine, by using New() or Default() // fixme 翻译
type Engine struct {
Handlers HandlersChain // 将中间件列表从 router 中提取到 engine 中
}
// New returns a new blank Engine instance without any middleware attached.
// By default the configuration is:
// - RedirectTrailingSlash: true
// - RedirectFixedPath: false
// - HandleMethodNotAllowed: false
// - ForwardedByClientIP: true
// - UseRawPath: false
// - UnescapePathValues: true // fixme 翻译
func New() *Engine {
debugPrintWARNINGNew()
engine := &Engine{
//trees: make(methodTrees, 0, 9), fixme 未确定是否保留
//delims: render.Delims{Left: "{{", Right: "}}"}, fixme 未确定是否保留
}
//engine.RouterGroup.engine = engine fixme 未确定是否保留
//engine.pool.New = func() interface{} { fixme 未确定是否保留
// return engine.allocateContext()
//}
return engine
}
// Default returns an Engine instance with the Logger and Recovery middleware already attached. // fixme 翻译
func Default() *Engine {
debugPrintWARNINGDefault()
engine := New()
engine.Use(Logger(), Recovery())
return engine
}
func (engine *Engine) allocateContext() *Context {
return &Context{engine: engine}
}
// Use attaches a global middleware to the router. ie. the middleware attached though Use() will be
// included in the handlers chain for every single request. Even 404, 405, static files...
// For example, this is the right place for a logger or error management middleware. // fixme 翻译
func (engine *Engine) Use(middleware ...HandlerFunc) *Engine {
engine.Handlers = append(engine.Handlers, middleware...) // 将添加中间件的逻辑从 router 中提取到 engine 中进行处理,并且精简掉了 router 中的 GET、 POST 等方法,直接将最终的处理函数作为 USE 的最后一个参数即可
return engine
}
// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens. // fixme 翻译
// 此函数与 Gin 不同, 没有会返回 err 的步骤, 所以去掉了返回值中的 err, 以及用于 handle err 的 defer
func (engine *Engine) Run() {
debugPrint("Start Running.")
cloudfunction.Start(engine.start)
}
// 基于 scf 实现 handleHTTPRequest 的逻辑
func (engine *Engine) start(ctx context.Context, event scf.APIGatewayProxyRequest) (scf.APIGatewayProxyResponse, error) {
// 初始化上下文
c := new(Context)
// 向上下文添加引擎
c.engine = engine
// 向上下文添加请求内容
c.Request = event
// 初始化引擎
c.reset()
// 执行调用链
c.Next()
// 如果未设置响应状态码, 则添加默认响应状态码 StatusOK
if c.Response.StatusCode == 0 {
c.Response.StatusCode = http.StatusOK
}
// 返回响应体给 SCF
return c.Response, nil
}
|
[
3
] |
package tracer
import (
"github.com/eriklupander/pathtracer/internal/app/geom"
"github.com/eriklupander/pathtracer/internal/app/shapes"
"math"
)
// Position multiplies direction of ray with the passed distance and adds the result onto the origin.
// Used for finding the position along a ray.
func Position(r geom.Ray, distance float64) geom.Tuple4 {
add := geom.MultiplyByScalar(r.Direction, distance)
pos := geom.Add(r.Origin, add)
return pos
}
func PositionPtr(r geom.Ray, distance float64, out *geom.Tuple4) {
add := geom.MultiplyByScalar(r.Direction, distance)
geom.AddPtr(r.Origin, add, out)
}
// TODO only used by unit tests, fix so tests use IntersectRayWithShapePtr and remove
//func IntersectRayWithShape(s shapes.Shape, r2 geom.Ray) []shapes.Intersection {
//
// // transform ray with inverse of shape transformation matrix to be able to intersect a translated/rotated/skewed shape
// r := TransformRay(r2, s.GetInverse())
//
// // Call the intersect function provided by the shape implementation (e.g. Sphere, Plane osv)
// return s.IntersectLocal(r)
//}
//func IntersectRayWithShapePtr(s shapes.Shape, r2 geom.Ray, in *geom.Ray) []shapes.Intersection {
// //calcstats.Incr()
// // transform ray with inverse of shape transformation matrix to be able to intersect a translated/rotated/skewed shape
// TransformRayPtr(r2, s.GetInverse(), in)
//
// // Call the intersect function provided by the shape implementation (e.g. Sphere, Plane osv)
// return s.IntersectLocal(*in)
//}
// Hit finds the first intersection with a positive T (the passed intersections are assumed to have been sorted already)
func Hit(intersections []shapes.Intersection) (shapes.Intersection, bool) {
// Filter out all negatives
for i := 0; i < len(intersections); i++ {
if intersections[i].T > 0.0 {
return intersections[i], true
}
}
return shapes.Intersection{}, false
}
func TransformRay(r geom.Ray, m1 geom.Mat4x4) geom.Ray {
origin := geom.MultiplyByTuple(m1, r.Origin)
direction := geom.MultiplyByTuple(m1, r.Direction)
return geom.NewRay(origin, direction)
}
func TransformRayPtr(r geom.Ray, m1 geom.Mat4x4, out *geom.Ray) {
geom.MultiplyByTuplePtr(&m1, &r.Origin, &out.Origin)
geom.MultiplyByTuplePtr(&m1, &r.Direction, &out.Direction)
}
func Schlick(comps Computation) float64 {
// find the cosine of the angle between the eye and normal vectors using Dot
cos := geom.Dot(comps.EyeVec, comps.NormalVec)
// total internal reflection can only occur if n1 > n2
if comps.N1 > comps.N2 {
n := comps.N1 / comps.N2
sin2Theta := (n * n) * (1.0 - (cos * cos))
if sin2Theta > 1.0 {
return 1.0
}
// compute cosine of theta_t using trig identity
cosTheta := math.Sqrt(1.0 - sin2Theta)
// when n1 > n2, use cos(theta_t) instead
cos = cosTheta
}
temp := (comps.N1 - comps.N2) / (comps.N1 + comps.N2)
r0 := temp * temp
return r0 + (1-r0)*math.Pow(1-cos, 5)
}
//
//func IntersectWithWorldPtr(scene *scenes.Scene, r geom.Ray, intersections shapes.Intersections, inRay *geom.Ray) []shapes.Intersection {
// for idx := range scene.Objects {
// intersections := IntersectRayWithShapePtr(scene.Objects[idx], r, inRay)
//
// for innerIdx := range intersections {
// intersections = append(intersections, intersections[innerIdx])
// }
// }
// if len(intersections) > 1 {
// sort.Sort(intersections)
// }
// return intersections
//}
|
[
3
] |
package lstm
import (
"fmt"
"io"
"math/rand"
"github.com/owulveryck/lstm/datasetter"
G "gorgonia.org/gorgonia"
"gorgonia.org/tensor"
)
// testBackends returns a backend with predictabale values for the test
// biais are zeroes and matrices are 1
func testBackends(inputSize, outputSize int, hiddenSize int) *backends {
var back backends
initValue := float32(1e-3)
back.InputSize = inputSize
back.OutputSize = outputSize
back.HiddenSize = hiddenSize
back.Wi = make([]float32, hiddenSize*inputSize)
for i := 0; i < hiddenSize*inputSize; i++ {
back.Wi[i] = initValue * rand.Float32()
}
back.Ui = make([]float32, hiddenSize*hiddenSize)
for i := 0; i < hiddenSize*hiddenSize; i++ {
back.Ui[i] = initValue * rand.Float32()
}
back.BiasI = make([]float32, hiddenSize)
back.Wo = make([]float32, hiddenSize*inputSize)
for i := 0; i < hiddenSize*inputSize; i++ {
back.Wo[i] = initValue * rand.Float32()
}
back.Uo = make([]float32, hiddenSize*hiddenSize)
for i := 0; i < hiddenSize*hiddenSize; i++ {
back.Uo[i] = initValue * rand.Float32()
}
back.BiasO = make([]float32, hiddenSize)
back.Wf = make([]float32, hiddenSize*inputSize)
for i := 0; i < hiddenSize*inputSize; i++ {
back.Wf[i] = initValue * rand.Float32()
}
back.Uf = make([]float32, hiddenSize*hiddenSize)
for i := 0; i < hiddenSize*hiddenSize; i++ {
back.Uf[i] = initValue * rand.Float32()
}
back.BiasF = make([]float32, hiddenSize)
back.Wc = make([]float32, hiddenSize*inputSize)
for i := 0; i < hiddenSize*inputSize; i++ {
back.Wc[i] = initValue * rand.Float32()
}
back.Uc = make([]float32, hiddenSize*hiddenSize)
for i := 0; i < hiddenSize*hiddenSize; i++ {
back.Uc[i] = initValue * rand.Float32()
}
back.BiasC = make([]float32, hiddenSize)
back.Wy = make([]float32, hiddenSize*outputSize)
for i := 0; i < hiddenSize*outputSize; i++ {
back.Wy[i] = initValue * rand.Float32()
}
back.BiasY = make([]float32, outputSize)
return &back
}
type testSet struct {
values [][]float32
expectedValues []int
offset int
output G.Nodes
outputValues [][]float32
epoch int
maxEpoch int
}
func (t *testSet) ReadInputVector(g *G.ExprGraph) (*G.Node, error) {
if t.offset >= len(t.values) {
return nil, io.EOF
}
size := len(t.values[t.offset])
inputTensor := tensor.New(tensor.WithShape(size), tensor.WithBacking(t.values[t.offset]))
node := G.NewVector(g, tensor.Float32, G.WithName(fmt.Sprintf("input_%v", t.offset)), G.WithShape(size), G.WithValue(inputTensor))
t.offset++
return node, nil
}
func (t *testSet) flush() error {
t.outputValues = make([][]float32, len(t.output))
for i, node := range t.output {
t.outputValues[i] = node.Value().Data().([]float32)
}
return nil
}
func (t *testSet) WriteComputedVector(n *G.Node) error {
t.output = append(t.output, n)
return nil
}
func (t *testSet) GetComputedVectors() G.Nodes {
return t.output
}
func (t *testSet) GetExpectedValue(offset int) (int, error) {
return t.expectedValues[offset], nil
}
func (t *testSet) GetTrainer() (datasetter.Trainer, error) {
if t.epoch <= t.maxEpoch {
t.epoch++
t.offset = 0
t.output = make([]*G.Node, 0)
return t, nil
}
return nil, io.EOF
}
|
[
6
] |
package main
import (
"fmt"
"sort"
)
func getMagority(mas []int) (int, bool) {
var max int = 0
var maxCount int = 1
var count int = 1
for i := 0; i < len(mas); i++ {
count = 1
for j := i + 1; j < len(mas); j++ {
if mas[i] == mas[j] {
count++
}
}
if count > maxCount {
maxCount = count
max = mas[i]
}
}
if maxCount > len(mas)/2 {
return max, true
}
return 0, false
}
func getMagority2(mas []int) (int, bool) {
var count int = 0
sort.Ints(mas)
for i := 0; i < len(mas); i++ {
if mas[i] == mas[len(mas)/2] {
count++
}
}
if count > len(mas)/2 {
return mas[len(mas)/2], true
}
return 0, false
}
func getMagority3(mas []int) (int, bool) {
var count int = 1
index := 0
for i := 1; i < len(mas); i++ {
if mas[i] == mas[index] {
count++
} else {
count--
}
if count == 0 {
index = i
count = 1
}
}
count = 0
for i := 0; i < len(mas); i++ {
if mas[index] == mas[i] {
count++
}
}
if count > len(mas)/2 {
return mas[index], true
}
return 0, false
}
func main() {
mas := []int{5, 5, 3, 1, 5, 5, 1, 5, 3, 5, 6}
fmt.Println(getMagority(mas))
fmt.Println(getMagority2(mas))
fmt.Println(getMagority3(mas))
}
|
[
1
] |
package main
import (
"server"
"json"
)
func main(){
messages := make(chan string)
//go server.StartServer(messages)
server.StartServer(messages)
println("Waiting for messages")
for{
message := <- messages
//Do whatever has to be done when receiving a message
repo := json.Decode(message)
println(repo.Full_name)
}
}
|
[
3
] |
package forest
import (
"fmt"
)
// Automaton cell
type Cell uint
const (
Tree Cell = iota
Space
Fire
Ready
Ash
T, S, F, R, A = 'T', 'S', 'F', 'R', 'A'
)
func (c *Cell) Scan(state fmt.ScanState, verb rune) error {
state.SkipSpace()
r, _, err := state.ReadRune()
if err != nil {
return err
} else if r == T {
*c = Tree
} else if r == S {
*c = Space
} else if r == F {
*c = Fire
} else if r == R {
*c = Ready
} else if r == A {
*c = Ash
} else {
state.UnreadRune()
return fmt.Errorf(
"The rune '%c' does not represent a cell's content.",
r,
)
}
return nil
}
func (c Cell) String() string {
var r rune
if c == Tree {
r = T
} else if c == Fire {
r = F
} else if c == Space {
r = S
} else if c == Ash {
r = A
} else if c == Ready {
r = R
}
return fmt.Sprintf("%c", r)
}
// A square grid of cells
type Grid [][]Cell
func NewGrid(width, height int) Grid {
g := make([][]Cell, height)
for i, _ := range g {
g[i] = make([]Cell, width)
}
return Grid(g)
}
func (g Grid) Size() (width, height int) {
height = len(g)
width = len(g[0])
return
}
func (g Grid) Copy() (g_ Grid) {
w, h := g.Size()
g_ = NewGrid(w, h)
for i := 0; i < h; i++ {
for j := 0; j < w; j++ {
g_[i][j] = g[i][j]
}
}
return
}
func (g *Grid) Scan(state fmt.ScanState, verb rune) error {
var w, h int
_, err := fmt.Fscan(state, &w)
defer func() {
if err != nil {
g = nil
}
}()
if err != nil {
return err
}
_, err = fmt.Fscan(state, &h)
if err != nil {
return err
}
*g = NewGrid(w, h)
var c Cell
for i := 0; i < h; i++ {
for j := 0; j < w; j++ {
_, err = fmt.Fscan(state, &c)
if err != nil {
return err
}
(*g)[i][j] = c
}
}
return err
}
func (g Grid) Format(state fmt.State, c rune) {
w, h := g.Size()
fmt.Fprintf(state, "%d %d\n", w, h)
for i := 0; i < h; i++ {
for j := 0; j < w; j++ {
fmt.Fprintf(state, "%s", g[i][j])
if j+1 == w {
fmt.Fprintln(state)
} else {
fmt.Fprint(state, " ")
}
}
}
}
|
[
5
] |
package main
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"bloat/config"
"bloat/renderer"
"bloat/repo"
"bloat/service"
"bloat/util"
)
var (
configFile = "/etc/bloat.conf"
)
func errExit(err error) {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
func main() {
opts, _, err := util.Getopts(os.Args, "f:")
if err != nil {
errExit(err)
}
for _, opt := range opts {
switch opt.Option {
case 'f':
configFile = opt.Value
}
}
config, err := config.ParseFile(configFile)
if err != nil {
errExit(err)
}
if !config.IsValid() {
errExit(errors.New("invalid config"))
}
templatesGlobPattern := filepath.Join(config.TemplatesPath, "*")
renderer, err := renderer.NewRenderer(templatesGlobPattern)
if err != nil {
errExit(err)
}
err = os.Mkdir(config.DatabasePath, 0755)
if err != nil && !os.IsExist(err) {
errExit(err)
}
sessionDBPath := filepath.Join(config.DatabasePath, "session")
sessionDB, err := util.NewDatabse(sessionDBPath)
if err != nil {
errExit(err)
}
appDBPath := filepath.Join(config.DatabasePath, "app")
appDB, err := util.NewDatabse(appDBPath)
if err != nil {
errExit(err)
}
sessionRepo := repo.NewSessionRepo(sessionDB)
appRepo := repo.NewAppRepo(appDB)
customCSS := config.CustomCSS
if len(customCSS) > 0 && !strings.HasPrefix(customCSS, "http://") &&
!strings.HasPrefix(customCSS, "https://") {
customCSS = "/static/" + customCSS
}
var logger *log.Logger
if len(config.LogFile) < 1 {
logger = log.New(os.Stdout, "", log.LstdFlags)
} else {
lf, err := os.OpenFile(config.LogFile,
os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
errExit(err)
}
defer lf.Close()
logger = log.New(lf, "", log.LstdFlags)
}
s := service.NewService(config.ClientName, config.ClientScope,
config.ClientWebsite, customCSS, config.SingleInstance,
config.PostFormats, renderer, sessionRepo, appRepo)
handler := service.NewHandler(s, logger, config.StaticDirectory)
logger.Println("listening on", config.ListenAddress)
err = http.ListenAndServe(config.ListenAddress, handler)
if err != nil {
errExit(err)
}
}
|
[
7
] |
package main
import (
"encoding/json"
"log"
"net/http"
"time"
mysql "AstralBackend/mysql"
gorillactx "github.com/gorilla/context"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
)
var jwtKey = []byte("Secret_Key_Shop")
type Claims struct {
UserID string `json:"userID"`
jwt.StandardClaims
}
func Welcome(w http.ResponseWriter, r *http.Request) {
// log.Println("Welcome")
// credets := &mysql.User{}
// err := json.NewDecoder(r.Body).Decode(&credets)
// log.Printf("%+v", credets)
// if err != nil {
// http.Error(w, "Wrong JSON", http.StatusBadRequest)
// return
// }
// json, _ := json.Marshal(map[string]string{"token": "userToken123"})
// fmt.Fprintf(w, string(json))
}
func AuthCheck(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("jwt-token")
if err != nil {
if err == http.ErrNoCookie {
// If the cookie is not set, return an unauthorized status
w.WriteHeader(http.StatusUnauthorized)
return
}
// For any other type of error, return a bad request status
w.WriteHeader(http.StatusBadRequest)
return
}
tokenString := c.Value
claims := &Claims{}
tkn, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
if !tkn.Valid {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
gorillactx.Set(r, "user_id", claims.UserID)
next(w, r)
}
}
func SignIn(w http.ResponseWriter, r *http.Request) {
log.Println("SignIn")
credets := &mysql.User{}
err := json.NewDecoder(r.Body).Decode(&credets)
log.Printf("%+v", credets)
if err != nil {
http.Error(w, "Wrong JSON", http.StatusBadRequest)
return
}
//get password hash by login in DB
userID, password, err := db.GetUserByLogin([]interface{}{credets.Login})
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
//check if the password is not empty
if password == "" {
http.Error(w, "Wrong Login", http.StatusUnauthorized)
return
}
//check recieved password with has from DB
if !CheckPasswordHash(credets.Password, password) {
http.Error(w, "Wrong Password", http.StatusUnauthorized)
return
}
//if the password is valid then generate JWT-Token
token, expTime, err := GenerateJWTToken(userID)
if err != nil {
http.Error(w, "Token error", http.StatusInternalServerError)
return
}
if err != nil {
http.Error(w, "Can't generate auth token", http.StatusInternalServerError)
return
}
//Set JWT token in Cookie
http.SetCookie(w, &http.Cookie{
Name: "jwt-token",
Value: token,
Expires: expTime,
Path: "/",
})
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func GenerateJWTToken(user_id string) (string, time.Time, error) {
expirationTime := time.Now().Add(60 * time.Minute)
claims := &Claims{
UserID: user_id,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
var err error
tokenSigned, err := token.SignedString(jwtKey)
if err != nil {
return "", time.Time{}, err
}
return tokenSigned, expirationTime, nil
}
|
[
3
] |
package state
import (
"fmt"
"reflect"
"runtime"
"strings"
. "github.com/zxh0/lua.go/api"
)
// [-0, +0, –]
// http://www.lua.org/manual/5.3/manual.html#lua_gethook
func (state *luaState) GetHook() LuaHook {
return state.hook
}
func (state *luaState) SetHook(f LuaHook, mask, count int) {
panic("todo: SetHook!")
}
// [-0, +0, –]
// http://www.lua.org/manual/5.3/manual.html#lua_gethookcount
func (state *luaState) GetHookCount() int {
return 0 // todo
}
// [-0, +0, –]
// http://www.lua.org/manual/5.3/manual.html#lua_gethookmask
func (state *luaState) GetHookMask() int {
return state.hookMask
}
// [-0, +0, –]
// http://www.lua.org/manual/5.3/manual.html#lua_getstack
func (state *luaState) GetStack(level int, ar *LuaDebug) bool {
if level < 0 || level >= state.callDepth-1 {
return false
}
if state.callDepth > 1 {
if s := state.getLuaStack(level); s != nil {
ar.CallInfo = s
return true
}
}
return false
}
// [-(0|1), +(0|1|2), e]
// http://www.lua.org/manual/5.3/manual.html#lua_getinfo
func (state *luaState) GetInfo(what string, ar *LuaDebug) bool {
if len(what) > 0 && what[0] == '>' {
what = what[1:]
val := state.stack.pop()
if c, ok := val.(*closure); ok {
return state.loadInfo(ar, c, what)
}
panic("function expected")
}
if ci := ar.CallInfo; ci != nil {
if c := ci.(*luaStack).closure; c != nil {
return state.loadInfo(ar, c, what)
}
}
return false
}
func (state *luaState) loadInfo(ar *LuaDebug, c *closure, what string) bool {
for len(what) > 0 {
switch what[0] {
case 'n': // fills in the field name and namewhat;
ar.Name = _getFuncName(c)
ar.NameWhat = "" // todo
case 'S': // fills in the fields source, short_src, linedefined, lastlinedefined, and what;
_setFuncInfoS(ar, c)
case 'l': // fills in the field currentline;
_setCurrentLine(ar, c)
case 't': // fills in the field istailcall;
ar.IsTailCall = false // todo
case 'u': // fills in the fields nups, nparams, and isvararg;
ar.NUps = 0 // todo
ar.NParams = 0 // todo
ar.IsVararg = false // todo
case 'f': // pushes onto the stack the function that is running at the given level;
state.stack.push(c)
case 'L': // pushes onto the stack a table whose indices are the numbers of the lines that are valid on the function.
//panic("todo: what->L")
state.PushNil()
default:
return false
}
what = what[1:]
}
return true
}
func _getFuncName(c *closure) string {
if gof := c.goFunc; gof != nil {
pc := reflect.ValueOf(gof).Pointer()
if f := runtime.FuncForPC(pc); f != nil {
name := f.Name()
if strings.HasPrefix(name, "github.com/zxh0/lua.go/stdlib.") {
name = name[13:] // remove "github.com/zxh0/lua.go/stdlib."
for len(name) > 0 && name[0] >= 'a' && name[0] <= 'z' { // remove prefix
name = name[1:]
}
return strings.ToLower(name)
}
}
}
return "?"
}
// the string "Lua" if the function is a Lua function,
// "C" if it is a C function, "main" if it is the main part of a chunk.
func _setFuncInfoS(ar *LuaDebug, c *closure) {
if c.proto == nil {
ar.Source = "=[C]"
ar.LineDefined = -1
ar.LastLineDefined = -1
ar.What = "C"
} else {
p := c.proto
if p.Source == "" {
ar.Source = "=?"
} else {
ar.Source = p.Source
}
ar.LineDefined = int(p.LineDefined)
ar.LastLineDefined = int(p.LastLineDefined)
if ar.LineDefined == 0 {
ar.What = "main"
} else {
ar.What = "Lua"
}
}
ar.ShortSrc = _getShortSrc(ar.Source)
}
func _getShortSrc(src string) string {
if len(src) > 0 { /* 'literal' source */
if src[0] == '=' {
src = src[1:]
if strLen := len(src); strLen > LUA_IDSIZE {
src = src[:LUA_IDSIZE-1]
}
} else if src[0] == '@' { /* file name */
src = src[1:]
if strLen := len(src); strLen > LUA_IDSIZE {
src = "..." + src[strLen-LUA_IDSIZE+4:]
}
} else { /* string; format as [string "source"] */
if i := strings.IndexByte(src, '\n'); i >= 0 {
src = src[0:i] + "..."
}
maxSrcLen := LUA_IDSIZE - len(`[string " "]`)
if len(src) > maxSrcLen {
src = src[0:maxSrcLen-3] + "..."
}
src = fmt.Sprintf(`[string "%s"]`, src)
}
}
return src
}
func _setCurrentLine(ar *LuaDebug, c *closure) {
if ci := ar.CallInfo; ci != nil {
c := ci.(*luaStack).closure
pc := ci.(*luaStack).pc
if c.proto == nil || pc < 1 || pc > len(c.proto.LineInfo) {
ar.CurrentLine = -1
} else {
ar.CurrentLine = int(c.proto.LineInfo[pc-1])
}
}
}
func (state *luaState) GetLocal(ar *LuaDebug, n int) string {
panic("todo: GetLocal!")
}
func (state *luaState) SetLocal(ar *LuaDebug, n int) string {
panic("todo: SetLocal!")
}
// [-0, +(0|1), –]
// http://www.lua.org/manual/5.3/manual.html#lua_getupvalue
func (state *luaState) GetUpvalue(funcIdx, n int) string {
val := state.stack.get(funcIdx)
if c, ok := val.(*closure); ok {
if len(c.upvals) >= n {
state.stack.push(c.getUpvalue(n - 1))
return c.getUpvalueName(n - 1)
}
}
return ""
}
// [-(0|1), +0, –]
// http://www.lua.org/manual/5.3/manual.html#lua_setupvalue
func (state *luaState) SetUpvalue(funcIdx, n int) string {
val := state.stack.get(funcIdx)
if c, ok := val.(*closure); ok {
if len(c.upvals) >= n {
c.setUpvalue(n-1, state.stack.pop())
return c.getUpvalueName(n - 1)
}
}
return ""
}
// [-0, +0, –]
// http://www.lua.org/manual/5.3/manual.html#lua_upvalueid
func (state *luaState) UpvalueId(funcIdx, n int) interface{} {
val := state.stack.get(funcIdx)
if c, ok := val.(*closure); ok {
if len(c.upvals) >= n {
return c.upvals[n-1]
}
}
return nil // todo
}
// [-0, +0, –]
// http://www.lua.org/manual/5.3/manual.html#lua_upvaluejoin
func (state *luaState) UpvalueJoin(funcIdx1, n1, funcIdx2, n2 int) {
v1 := state.stack.get(funcIdx1)
v2 := state.stack.get(funcIdx2)
if c1, ok := v1.(*closure); ok && len(c1.upvals) >= n1 {
if c2, ok := v2.(*closure); ok && len(c2.upvals) >= n2 {
c1.upvals[n1-1] = c2.upvals[n2-1]
}
}
}
|
[
3,
5
] |
//author tyf
//date 2017-02-09 18:06
//desc
package comm
import (
"bufio"
"database/sql"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/jmcvetta/randutil"
"github.com/tanyfx/ent/comm/consts"
"gopkg.in/redis.v5"
)
func ReadConf(filename string) (dbHandler, redisAddr, redisPasswd string, err error) {
user := "root"
passwd := ""
host := "localhost"
port := "3306"
dbName := "ent"
dbHandler = ""
redisHost := "localhost"
redisPort := "6379"
redisPasswd = ""
redisAddr = consts.RedisAddr
f, err := os.Open(filename)
if err != nil {
return
}
r := bufio.NewReader(f)
for {
line, _, err := r.ReadLine()
if err != nil {
break
}
if strings.HasPrefix(strings.TrimSpace(string(line)), "#") {
continue
}
m := strings.Split(string(line), "=")
if len(m) < 2 {
continue
}
k := strings.TrimSpace(m[0])
v := strings.TrimSpace(strings.Join(m[1:], "="))
switch strings.TrimSpace(k) {
case "user":
user = v
case "host":
host = v
case "port":
port = v
case "passwd":
passwd = v
case "db_name":
dbName = v
case "redis_host":
redisHost = v
case "redis_port":
redisPort = v
case "redis_passwd":
redisPasswd = v
default:
continue
}
}
//dbHandler = "root:123456@tcp(localhost:3306)/ent"
dbHandler = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, passwd, host, port, dbName)
//dbHandler = fmt.Sprint(user, ":", passwd, "@tcp(", host, ":", port, ")/", dbName)
redisAddr = fmt.Sprintf("%s:%s", redisHost, redisPort)
return
}
func DownloadImage(imgURL, folderPath string) (string, error) {
emptyStr := ""
suffix := ".jpg"
suffixRegexp := regexp.MustCompile(`(\.\w+)$`)
m := suffixRegexp.FindStringSubmatch(imgURL)
if len(m) == 2 {
suffix = m[1]
}
fileName, err := randutil.AlphaStringRange(30, 40)
if err != nil {
return emptyStr, err
}
imgName := fileName + suffix
resp, err := getThrice(imgURL)
if err != nil {
return emptyStr, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return emptyStr, errors.New("return code not 200 OK")
}
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return emptyStr, err
}
//fmt.Println(time.Now().Format(TimeFormat), "img", imgURL, "length", len(content))
imgWriter, err := os.Create(strings.TrimSuffix(folderPath, "/") + "/" + imgName)
if err != nil {
return emptyStr, err
}
defer imgWriter.Close()
_, err = imgWriter.Write(content)
if err != nil {
return emptyStr, err
}
return imgName, nil
}
func getThrice(link string) (resp *http.Response, err error) {
resp = nil
client := http.Client{
Timeout: time.Duration(10 * time.Second),
}
req, err := http.NewRequest("GET", link, nil)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", consts.UserAgent)
err = nil
for i := 0; i < 3; i++ {
if err != nil {
log.Println(err.Error(), "try again", link)
}
resp, err = client.Do(req)
if err != nil {
continue
}
if resp.StatusCode != 200 {
resp.Body.Close()
err = errors.New("return code not 200 OK")
continue
} else {
break
}
}
return resp, err
}
func FindStar(star string, pairs []StarIDPair) bool {
flag := false
for _, pair := range pairs {
if star == pair.NameCN {
flag = true
break
}
}
return flag
}
//input: 2017-01-02 15:09:02
func GetDuration(inputTime string) time.Duration {
preTime, err := time.Parse("2006-01-02 15:04:05", inputTime)
if err != nil {
return 0
}
pre := preTime.Unix()
cur := time.Now().Unix()
if pre > cur {
return 0
}
return time.Duration(cur - pre)
}
//starIDMap: map[starName] = starID, idStarMap: map[starID] = starName
func GetRedisStarID(client *redis.Client) (starIDMap, idStarMap map[string]string, err error) {
starIDMap = map[string]string{}
idStarMap = map[string]string{}
names, err := client.Keys(consts.RedisNamePrefix + "*").Result()
if err != nil {
return starIDMap, idStarMap, errors.New("error while get star name key from redis: " + err.Error())
}
for _, tmpName := range names {
name := strings.TrimPrefix(tmpName, consts.RedisNamePrefix)
starID := client.Get(tmpName).Val()
starIDMap[name] = starID
idStarMap[starID] = name
}
return FixStarNameMap(starIDMap), idStarMap, nil
}
//nicknameMap: map[nickname] = starID
func GetNickname(db *sql.DB) (NicknameMap map[string]string, err error) {
NicknameMap = map[string]string{}
queryStr := "select name, star_id from nickname"
rows, err := db.Query(queryStr)
if err != nil {
return NicknameMap, errors.New("error while get stars from table nickname: " + err.Error())
}
for rows.Next() {
var starID, nickname sql.NullString
err = rows.Scan(&nickname, &starID)
if err != nil {
log.Println("error while scan nickname rows:", err.Error())
continue
}
if nickname.Valid && starID.Valid {
NicknameMap[nickname.String] = starID.String
}
}
return FixStarNameMap(NicknameMap), nil
}
func FixStarNameMap(nameMap map[string]string) map[string]string {
delete(nameMap, "信")
delete(nameMap, "苹果")
delete(nameMap, "L")
return nameMap
}
//get input keys to lower case to make sure keys match
//starIDMap: star_name->star_id
//map[string]StarIDPair : star name -> star id pair
func GetSearchStarList(filename string, starIDMap map[string]string) map[string]StarIDPair {
resultMap := map[string]StarIDPair{}
pairMap := map[string]StarIDPair{}
for name, starID := range starIDMap {
tmpPair := StarIDPair{
NameCN: name,
StarID: starID,
}
name = strings.ToLower(name)
pairMap[name] = tmpPair
}
content, err := ioutil.ReadFile(filename)
if err != nil {
log.Println("error while read file:", filename, err.Error())
return resultMap
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if len(line) == 0 || strings.HasPrefix(line, "#") {
continue
}
names := strings.Split(line, ",")
if len(names) == 0 {
continue
}
tmpName := strings.ToLower(names[0])
tmpPair, found := pairMap[tmpName]
if !found {
log.Println("star name not found in star_name table:", names[0])
continue
}
if len(names) > 1 {
resultMap[names[1]] = tmpPair
//tmpName = names[1]
} else {
resultMap[names[0]] = tmpPair
}
fmt.Println(time.Now().Format(consts.TimeFormat), "name in db:", tmpPair.NameCN, "search name:", tmpName,
"star id:", tmpPair.StarID)
}
return resultMap
}
//转义字符串,用于MySQL存储
func EscapeStr(str string) string {
result := strings.TrimSpace(str)
result = strings.Replace(str, ";", ";", -1)
result = strings.Replace(result, ",", ",", -1)
result = strings.Replace(result, "'", "\"", -1)
return result
}
//sql.NullString => string
func ConvertStrings(input []sql.NullString) []string {
result := []string{}
for _, tmpStr := range input {
result = append(result, tmpStr.String)
}
return result
}
//用于插入分页符
//a input string slice
//sep separator
//m gaps between two break
func JoinWithBreak(a []string, brk string, sep string, m int) string {
if len(a) == 0 || m < 1 {
return ""
}
if len(a) <= m {
return strings.Join(a, sep)
}
remain := len(a) % m
x := len(a) / m
if remain == 0 {
remain = m
x--
}
n := len(brk)*x + len(sep)*(len(a)-1-x)
for i := 0; i < len(a); i++ {
n += len(a[i])
}
b := make([]byte, n)
bp := copy(b, a[0])
for i := 1; i < remain; i++ {
bp += copy(b[bp:], sep)
bp += copy(b[bp:], a[i])
}
count := 0
for _, s := range a[remain:] {
if count%m == 0 {
bp += copy(b[bp:], brk)
} else {
bp += copy(b[bp:], sep)
}
bp += copy(b[bp:], s)
count++
}
return string(b)
}
func InterfaceToString(x interface{}) string {
result := ""
switch x.(type) {
case float64:
result = strconv.Itoa(int(x.(float64)))
case float32:
result = strconv.Itoa(int(x.(float32)))
case int:
result = strconv.Itoa(x.(int))
case string:
result = x.(string)
default:
result = ""
}
return result
}
|
[
2,
3,
6
] |
package main
import (
"fmt"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/hfantin/clientgov2/controllers"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/v1/clients", controllers.GetClients).Methods("GET")
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
fmt.Println(port)
err := http.ListenAndServe(":"+port, router) //Launch the app, visit localhost:8000/api
if err != nil {
fmt.Print(err)
}
}
|
[
3
] |
package api_server
import (
"crypto/tls"
"github.com/DawnBreather/go-commons/ssl"
"github.com/gorilla/mux"
"log"
"net/http"
)
// ApiServer has router
type ApiServer struct {
Ssl ssl.Ssl
Router *mux.Router
Config map[string]interface{}
}
func (a *ApiServer) SetSslMetadata(locality, country, organization, province, postalCode, streetAddress string){
a.Ssl.
SetLocality(locality).
SetCountry(country).
SetOrganization(organization).
SetProvince(province).
SetPostalCode(postalCode).
SetStreetAddress(streetAddress)
}
// Initialize initializes the app with predefined configuration
func (a *ApiServer) Initialize(config map[string]interface{}) *ApiServer{
//func (a *ApiServer) Initialize() *ApiServer{
a.Ssl.InitializeCertificateAuthority()
a.Router = mux.NewRouter()
return a
}
//func (a *ApiServer) setRouters() {
// // Routing for handling the projects
// a.Get("/projects", a.handleRequest(handler.GetAllProjects))
// a.Post("/projects", a.handleRequest(handler.CreateProject))
// a.Get("/projects/{title}", a.handleRequest(handler.GetProjects))
// a.Put("/projects/{title}", a.handleRequest(handler.UpdateProject))
// a.Delete("/projects/{title}", a.handleRequest(handler.DeleteProject))
// a.Put("/projects/{title}/archive", a.handleRequest(handler.ArchiveProject))
// a.Delete("/projects/{title}/archive", a.handleRequest(handler.RestoreProject))
//
// // Routing for handling the tasks
// a.Get("/projects/{title}/tasks", a.handleRequest(handler.GetAllTasks))
// a.Post("/projects/{title}/tasks", a.handleRequest(handler.CreateTask))
// a.Get("/projects/{title}/tasks/{id:[0-9]+}", a.handleRequest(handler.GetTask))
// a.Put("/projects/{title}/tasks/{id:[0-9]+}", a.handleRequest(handler.UpdateTask))
// a.Delete("/projects/{title}/tasks/{id:[0-9]+}", a.handleRequest(handler.DeleteTask))
// a.Put("/projects/{title}/tasks/{id:[0-9]+}/complete", a.handleRequest(handler.CompleteTask))
// a.Delete("/projects/{title}/tasks/{id:[0-9]+}/complete", a.handleRequest(handler.UndoTask))
//}
// Get wraps the router for GET method
func (a *ApiServer) Get(path string, f func(w http.ResponseWriter, r *http.Request)) *ApiServer{
a.Router.HandleFunc(path, f).Methods("GET")
return a
}
// Post wraps the router for POST method
func (a *ApiServer) Post(path string, f func(w http.ResponseWriter, r *http.Request)) *ApiServer{
a.Router.HandleFunc(path, f).Methods("POST")
return a
}
// Put wraps the router for PUT method
func (a *ApiServer) Put(path string, f func(w http.ResponseWriter, r *http.Request)) *ApiServer{
a.Router.HandleFunc(path, f).Methods("PUT")
return a
}
// Delete wraps the router for DELETE method
func (a *ApiServer) Delete(path string, f func(w http.ResponseWriter, r *http.Request)) *ApiServer{
a.Router.HandleFunc(path, f).Methods("DELETE")
return a
}
// Run the app on it's router
func (a *ApiServer) Run(host string) {
log.Fatal(http.ListenAndServe(host, a.Router))
}
func (a *ApiServer) RunSslSelfSigned(host string, DNSNames []string) {
_, _, keyPair := a.Ssl.GenerateSignedCertificate(DNSNames)
server := &http.Server{
Addr: host,
Handler: a.Router,
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{keyPair},
},
}
//log.Fatal(http.ListenAndServeTLS(host, "", "", a.Router))
log.Fatal(server.ListenAndServeTLS("", ""))
}
type RequestHandlerFunction func(w http.ResponseWriter, r *http.Request)
func (a *ApiServer) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
handler(w, r)
}
}
|
[
2,
3
] |
// Bootstrap script for Database deployment and migration
package main
import (
"context"
"flag"
"fmt"
"log"
"math"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/coreos/go-semver/semver"
"github.com/golang-migrate/migrate/v4"
"github.com/interuss/dss/pkg/cockroach"
"github.com/interuss/dss/pkg/cockroach/flags"
"go.uber.org/zap"
_ "github.com/golang-migrate/migrate/v4/database/cockroachdb" // Force registration of cockroachdb backend
_ "github.com/golang-migrate/migrate/v4/source/file" // Force registration of file source
)
// MyMigrate is an alias for extending migrate.Migrate
type MyMigrate struct {
*migrate.Migrate
postgresURI string
database string
}
// Direction is an alias for int indicating the direction and steps of migration
type Direction int
func (d Direction) String() string {
if d > 0 {
return "Up"
} else if d < 0 {
return "Down"
}
return "No Change"
}
var (
path = flag.String("schemas_dir", "", "path to db migration files directory. the migrations found there will be applied to the database whose name matches the folder name.")
dbVersion = flag.String("db_version", "", "the db version to migrate to (ex: 1.0.0) or use \"latest\" to automatically upgrade to the latest version")
step = flag.Int("migration_step", 0, "the db migration step to go to")
)
func main() {
flag.Parse()
if *path == "" {
log.Panic("Must specify schemas_dir path")
}
if (*dbVersion == "" && *step == 0) || (*dbVersion != "" && *step != 0) {
log.Panic("Must specify one of [db_version, migration_step] to goto, use --help to see options")
}
latest := strings.ToLower(*dbVersion) == "latest"
var (
desiredVersion *semver.Version
)
if *dbVersion != "" && !latest {
if v, err := semver.NewVersion(*dbVersion); err == nil {
desiredVersion = v
} else {
log.Panic("db_version must be in a valid format ex: 1.2.3", err)
}
}
params := flags.ConnectParameters()
params.ApplicationName = "SchemaManager"
params.DBName = filepath.Base(*path)
postgresURI, err := params.BuildURI()
if err != nil {
log.Panic("Failed to build URI", zap.Error(err))
}
myMigrater, err := New(*path, postgresURI, params.DBName)
if err != nil {
log.Panic(err)
}
defer func() {
if _, err := myMigrater.Close(); err != nil {
log.Println(err)
}
}()
preMigrationStep, _, err := myMigrater.Version()
if err != migrate.ErrNilVersion && err != nil {
log.Panic(err)
}
if latest {
if err := myMigrater.Up(); err != nil {
log.Panic(err)
}
} else {
if err := myMigrater.DoMigrate(*desiredVersion, *step); err != nil {
log.Panic(err)
}
}
postMigrationStep, dirty, err := myMigrater.Version()
if err != nil {
log.Fatal("Failed to get Migration Step for confirmation")
}
totalMoves := int(postMigrationStep - preMigrationStep)
if totalMoves == 0 && !latest {
log.Println("No Changes")
} else {
log.Printf("Moved %d step(s) in total from Step %d to Step %d", intAbs(totalMoves), preMigrationStep, postMigrationStep)
}
currentDBVersion, err := getCurrentDBVersion(postgresURI, params.DBName)
if err != nil {
log.Fatal("Failed to get Current DB version for confirmation")
}
log.Printf("DB Version: %s, Migration Step # %d, Dirty: %v", currentDBVersion, postMigrationStep, dirty)
}
// DoMigrate performs the migration given the desired state we want to reach
func (m *MyMigrate) DoMigrate(desiredDBVersion semver.Version, desiredStep int) error {
migrateDirection, err := m.MigrationDirection(desiredDBVersion, desiredStep)
if err != nil {
return err
}
for migrateDirection != 0 {
err = m.Steps(int(migrateDirection))
if err != nil {
return err
}
log.Printf("Migrated %s by %d step", migrateDirection.String(), intAbs(int(migrateDirection)))
migrateDirection, err = m.MigrationDirection(desiredDBVersion, *step)
if err != nil {
return err
}
}
return nil
}
// New instantiates a new migrate object
func New(path string, dbURI string, database string) (*MyMigrate, error) {
noDbPostgres := strings.Replace(dbURI, fmt.Sprintf("/%s", database), "", 1)
err := createDatabaseIfNotExists(noDbPostgres, database)
if err != nil {
return nil, err
}
path = fmt.Sprintf("file://%v", path)
crdbURI := strings.Replace(dbURI, "postgresql", "cockroachdb", 1)
migrater, err := migrate.New(path, crdbURI)
if err != nil {
return nil, err
}
myMigrater := &MyMigrate{migrater, dbURI, database}
// handle Ctrl+c
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT)
go func() {
for range signals {
log.Println("Stopping after this running migration ...")
myMigrater.GracefulStop <- true
return
}
}()
return myMigrater, err
}
func intAbs(x int) int {
return int(math.Abs(float64(x)))
}
func createDatabaseIfNotExists(crdbURI string, database string) error {
crdb, err := cockroach.Dial(crdbURI)
if err != nil {
return fmt.Errorf("Failed to dial CRDB to check DB exists: %v", err)
}
defer func() {
crdb.Close()
}()
const checkDbQuery = `
SELECT EXISTS (
SELECT *
FROM pg_database
WHERE datname = $1
)
`
var exists bool
if err := crdb.QueryRow(checkDbQuery, database).Scan(&exists); err != nil {
return err
}
if !exists {
log.Printf("Database \"%s\" doesn't exist, attempting to create", database)
createDB := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", database)
_, err := crdb.Exec(createDB)
if err != nil {
return fmt.Errorf("Failed to Create Database: %v", err)
}
}
return nil
}
func getCurrentDBVersion(crdbURI string, database string) (*semver.Version, error) {
crdb, err := cockroach.Dial(crdbURI)
if err != nil {
return nil, fmt.Errorf("Failed to dial CRDB while getting DB version: %v", err)
}
defer func() {
crdb.Close()
}()
return crdb.GetVersion(context.Background(), database)
}
// MigrationDirection reads our custom DB version string as well as the Migration Steps from the framework
// and returns a signed integer value of the Direction and count to migrate the db
func (m *MyMigrate) MigrationDirection(desiredVersion semver.Version, desiredStep int) (Direction, error) {
if desiredStep != 0 {
currentStep, dirty, err := m.Version()
if err != migrate.ErrNilVersion && err != nil {
return 0, fmt.Errorf("Failed to get Migration Step to determine migration direction: %v", err)
}
if dirty {
log.Fatal("DB in Dirty state, Please fix before migrating")
}
return Direction(desiredStep - int(currentStep)), nil
}
currentVersion, err := getCurrentDBVersion(m.postgresURI, m.database)
if err != nil {
return 0, fmt.Errorf("Failed to get current DB version to determine migration direction: %v", err)
}
return Direction(desiredVersion.Compare(*currentVersion)), nil
}
|
[
6
] |
package service
import (
"context"
"github.com/gogf/gf/frame/g"
"github.com/qiniu/api.v7/v7/auth/qbox"
"github.com/qiniu/api.v7/v7/storage"
)
// 上传七牛后删除
func uploadFile(url, filePath string) (string, error) {
var (
accessKey = g.Cfg("private").GetString("qiniu.AccessKey") // 七牛的accessKey 去七牛后台获取
secretKey = g.Cfg("private").GetString("qiniu.SecretKey") // 七牛的secretKey 去七牛后台获取
bucket = g.Cfg("private").GetString("qiniu.Bucket") // 上传空间 去七牛后台创建
)
// 鉴权
mac := qbox.NewMac(accessKey, secretKey)
// 上传策略
putPolicy := storage.PutPolicy{
Scope: bucket,
Expires: 7200,
}
// 获取上传token
upToken := putPolicy.UploadToken(mac)
// 上传Config对象
cfg := storage.Config{}
cfg.Zone = &storage.ZoneHuabei //指定上传的区域
cfg.UseHTTPS = g.Cfg("private").GetBool("qiniu.UseHTTPS") // 是否使用https域名
cfg.UseCdnDomains = g.Cfg("private").GetBool("qiniu.UseCdnDomains") //是否使用CDN上传加速
// 需要上传的文件
localFile := url
// 七牛key
qiniuKey := filePath
// 构建表单上传的对象
formUploader := storage.NewFormUploader(&cfg)
ret := storage.PutRet{}
// 上传文件
err := formUploader.PutFile(context.Background(), &ret, upToken, qiniuKey, localFile, nil)
if err != nil {
g.Log().Println("上传文件失败,原因:", err)
return "err", err
}
g.Log().Println("上传成功,key为:", ret)
return ret.Key, nil
}
func AddUrl(url string) string {
return g.Cfg("private").GetString("qiniu.Url") + url
}
|
[
3
] |
// Copyright 2010 The postscript-go Authors. All rights reserved.
// created: 13/12/2010 by Laurent Le Goff
package postscript
import (
"log"
)
//int dict dict -> Create dictionary with capacity for int elements
func dict(interpreter *Interpreter) {
interpreter.Push(NewDictionary(interpreter.PopInt()))
}
//dict length int -> Return number of entries in dict
func lengthdict(interpreter *Interpreter) {
dictionary := interpreter.Pop().(Dictionary)
interpreter.Push(float64(len(dictionary)))
}
//dict maxlength int -> Return current capacity of dict
func maxlength(interpreter *Interpreter) {
interpreter.Pop()
interpreter.Push(float64(999999999)) // push arbitrary value
}
//dict begin – -> Push dict on dictionary stack
func begin(interpreter *Interpreter) {
interpreter.PushDictionary(interpreter.Pop().(Dictionary))
}
//– end – -> Pop current dictionary off dictionary stack
func end(interpreter *Interpreter) {
interpreter.PopDictionary()
}
//key value def – -> Associate key and value in current dictionary
func def(interpreter *Interpreter) {
value := interpreter.Pop()
name := interpreter.PopName()
if p, ok := value.(*ProcedureDefinition); ok {
value = NewProcedure(p)
}
interpreter.Define(name, value)
}
//key load value -> Search dictionary stack for key and return associated value
func load(interpreter *Interpreter) {
name := interpreter.PopName()
value, _ := interpreter.FindValueInDictionaries(name)
if value == nil {
log.Printf("Can't find value %s\n", name)
}
interpreter.Push(value)
}
//key value store – -> Replace topmost definition of key
func store(interpreter *Interpreter) {
value := interpreter.Pop()
key := interpreter.PopName()
_, dictionary := interpreter.FindValueInDictionaries(key)
if dictionary != nil {
dictionary[key] = value
}
}
//dict key get any -> Return value associated with key in dict
func getdict(interpreter *Interpreter) {
key := interpreter.PopName()
dictionary := interpreter.Pop().(Dictionary)
interpreter.Push(dictionary[key])
}
//dict key value put – -> Associate key with value in dict
func putdict(interpreter *Interpreter) {
value := interpreter.Pop()
key := interpreter.PopName()
dictionary := interpreter.Pop().(Dictionary)
dictionary[key] = value
}
//dict key undef – Remove key and its value from dict
func undef(interpreter *Interpreter) {
key := interpreter.PopName()
dictionary := interpreter.Pop().(Dictionary)
dictionary[key] = nil
}
//dict key known bool -> Test whether key is in dict
func known(interpreter *Interpreter) {
key := interpreter.PopName()
dictionary := interpreter.Pop().(Dictionary)
interpreter.Push(dictionary[key] != nil)
}
//key where (dict true) or false -> Find dictionary in which key is defined
func where(interpreter *Interpreter) {
key := interpreter.PopName()
_, dictionary := interpreter.FindValueInDictionaries(key)
if dictionary == nil {
interpreter.Push(false)
} else {
interpreter.Push(dictionary)
interpreter.Push(true)
}
}
// dict1 dict2 copy dict2 -> Copy contents of dict1 to dict2
func copydict(interpreter *Interpreter) {
dict2 := interpreter.Pop().(Dictionary)
dict1 := interpreter.Pop().(Dictionary)
for key, value := range dict1 {
dict2[key] = value
}
interpreter.Push(dict2)
}
//dict proc forall – -> Execute proc for each entry in dict
func foralldict(interpreter *Interpreter) {
proc := NewProcedure(interpreter.PopProcedureDefinition())
dict := interpreter.Pop().(Dictionary)
for key, value := range dict {
interpreter.Push(key)
interpreter.Push(value)
proc.Execute(interpreter)
}
}
//– currentdict dict -> Return current dictionary
func currentdict(interpreter *Interpreter) {
interpreter.Push(interpreter.PeekDictionary())
}
//– systemdict dict -> Return system dictionary
func systemdict(interpreter *Interpreter) {
interpreter.Push(interpreter.SystemDictionary())
}
//– userdict dict -> Return writeable dictionary in local VM
func userdict(interpreter *Interpreter) {
interpreter.Push(interpreter.UserDictionary())
}
//– globaldict dict -> Return writeable dictionary in global VM
func globaldict(interpreter *Interpreter) {
interpreter.Push(interpreter.UserDictionary())
}
//– statusdict dict -> Return product-dependent dictionary
func statusdict(interpreter *Interpreter) {
interpreter.Push(interpreter.UserDictionary())
}
//– countdictstack int -> Count elements on dictionary stack
func countdictstack(interpreter *Interpreter) {
interpreter.Push(float64(interpreter.DictionaryStackSize()))
}
//array dictstack subarray -> Copy dictionary stack into array
func dictstack(interpreter *Interpreter) {
panic("No yet implemenented")
}
//– cleardictstack – -> Pop all nonpermanent dictionaries off dictionary stack
func cleardictstack(interpreter *Interpreter) {
interpreter.ClearDictionaries()
}
func initDictionaryOperators(interpreter *Interpreter) {
interpreter.SystemDefine("dict", NewOperator(dict))
//interpreter.SystemDefine("length", NewOperator(length)) // already define in operators_conflict.go
interpreter.SystemDefine("maxlength", NewOperator(maxlength))
interpreter.SystemDefine("begin", NewOperator(begin))
interpreter.SystemDefine("end", NewOperator(end))
interpreter.SystemDefine("def", NewOperator(def))
interpreter.SystemDefine("load", NewOperator(load))
interpreter.SystemDefine("store", NewOperator(store))
//interpreter.SystemDefine("get", NewOperator(get)) // already define in operators_conflict.go
//interpreter.SystemDefine("put", NewOperator(put)) // already define in operators_conflict.go
interpreter.SystemDefine("undef", NewOperator(undef))
interpreter.SystemDefine("known", NewOperator(known))
interpreter.SystemDefine("where", NewOperator(where))
//interpreter.SystemDefine("copydict", NewOperator(copydict)) // already define in operators_conflict.go
//interpreter.SystemDefine("foralldict", NewOperator(foralldict)) // already define in operators_conflict.go
interpreter.SystemDefine("currentdict", NewOperator(currentdict))
interpreter.SystemDefine("systemdict", NewOperator(systemdict))
interpreter.SystemDefine("userdict", NewOperator(userdict))
interpreter.SystemDefine("globaldict", NewOperator(globaldict))
interpreter.SystemDefine("statusdict", NewOperator(statusdict))
interpreter.SystemDefine("countdictstack", NewOperator(countdictstack))
interpreter.SystemDefine("dictstack", NewOperator(dictstack))
interpreter.SystemDefine("cleardictstack", NewOperator(cleardictstack))
}
|
[
3
] |
package clinicaltrials
import (
"context"
"gitlab.com/weinbergerlab/immunogenicity-data-project/app/gen/models"
//_ "github.com/mattn/go-sqlite3" // Import go-sqlite3 library
_ "github.com/lib/pq"
"github.com/stretchr/testify/assert"
"testing"
)
func TestInsert(t *testing.T) {
//os.Remove("test.db") // I delete the file to avoid duplicated records.
//// SQLite is a file based database.
//
//log.Println("Creating sqlite-database.db...")
//file, err := os.Create("test.db") // Create SQLite file
//assert.Nil(t, err)
//file.Close()
//log.Println("test.db created")
ctx := context.Background()
//testID := "NCT03197376"
//testID = "NCT03547167"
//testIDs := []string{
//"NCT03950856",
//"NCT03950622",
//"NCT03835975",
//"NCT03828617",
//"NCT03760146",
//"NCT03547167",
//"NCT03480802",
//"NCT03480763",
//"NCT03313037", // This one presents an issue we need to look into (invalid array length)
//"NCT03197376",
//"NCT02787863",
//"NCT02717494",
//"NCT02573181",
//"NCT02547649",
//"NCT02308540",
//"NCT02225587",
//"NCT02097472",
//"NCT02037984",
//"NCT01646398",
//"NCT01641133",
//"NCT01545375",
//"NCT01513551",
//"NCT01215188",
//"NCT01215175",
//"NCT00962780",
//"NCT00836641",
//"NCT00689351",
//"NCT00688870",
//"NCT00680914",
//"NCT00676091",
//"NCT00574548",
//"NCT00546572",
//"NCT00508742",
//"NCT00475033",
//"NCT00474539",
//"NCT00463437",
//"NCT00457977",
//"NCT00452790",
//"NCT00444457",
//"NCT00427895",
//"NCT00384059",
//"NCT00373958",
//"NCT00370396",
//"NCT00368966",
//"NCT00366899",
//"NCT00366678",
//"NCT00366340",
//"NCT00205803", // Issue parsing date at insert
//}
driver := "postgres"
dataSource := "host=localhost port=18034 user=local dbname=local password=password sslmode=disable"
//driver = "sqlite3"
//dataSource = "file:./test.db?cache=shared&mode=memory&_fk=true"
db, err := models.Open(driver, dataSource)
assert.Nil(t, err)
assert.Nil(t, db.Schema.Create(ctx))
//rc := NewResultsContext(ctx, db)
//for _, testIdInsert := range testIDs {
// assert.Nil(t, rc.Insert(testIdInsert, false))
//}
_, err = GetTrial("NCT03197376")
assert.Nil(t, err)
//assert.Nil(t, rc.InsertAll(study, GetOutcomeOverviewList(study)), []Metadata{})
//assert.Nil(t, rc.Insert(testID, false))
}
|
[
3
] |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"context"
"time"
"sigs.k8s.io/sig-storage-local-static-provisioner/pkg/metrics"
batch_v1 "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
// APIUtil is an interface for the K8s API
type APIUtil interface {
// Create PersistentVolume object
CreatePV(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
// Delete PersistentVolume object
DeletePV(pvName string) error
// CreateJob Creates a Job execution.
CreateJob(job *batch_v1.Job) error
// DeleteJob deletes specified Job by its name and namespace.
DeleteJob(jobName string, namespace string) error
}
var _ APIUtil = &apiUtil{}
type apiUtil struct {
client kubernetes.Interface
}
// NewAPIUtil creates a new APIUtil object that represents the K8s API
func NewAPIUtil(client kubernetes.Interface) APIUtil {
return &apiUtil{client: client}
}
// CreatePV will create a PersistentVolume
func (u *apiUtil) CreatePV(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {
startTime := time.Now()
metrics.APIServerRequestsTotal.WithLabelValues(metrics.APIServerRequestCreate).Inc()
pv, err := u.client.CoreV1().PersistentVolumes().Create(context.TODO(), pv, metav1.CreateOptions{})
metrics.APIServerRequestsDurationSeconds.WithLabelValues(metrics.APIServerRequestCreate).Observe(time.Since(startTime).Seconds())
if err != nil {
metrics.APIServerRequestsFailedTotal.WithLabelValues(metrics.APIServerRequestCreate).Inc()
}
return pv, err
}
// DeletePV will delete a PersistentVolume
func (u *apiUtil) DeletePV(pvName string) error {
startTime := time.Now()
metrics.APIServerRequestsTotal.WithLabelValues(metrics.APIServerRequestDelete).Inc()
err := u.client.CoreV1().PersistentVolumes().Delete(context.TODO(), pvName, metav1.DeleteOptions{})
metrics.APIServerRequestsDurationSeconds.WithLabelValues(metrics.APIServerRequestDelete).Observe(time.Since(startTime).Seconds())
if err != nil {
metrics.APIServerRequestsFailedTotal.WithLabelValues(metrics.APIServerRequestDelete).Inc()
}
return err
}
func (u *apiUtil) CreateJob(job *batch_v1.Job) error {
_, err := u.client.BatchV1().Jobs(job.Namespace).Create(context.TODO(), job, metav1.CreateOptions{})
if err != nil {
return err
}
return nil
}
func (u *apiUtil) DeleteJob(jobName string, namespace string) error {
deleteProp := metav1.DeletePropagationForeground
if err := u.client.BatchV1().Jobs(namespace).Delete(context.TODO(), jobName, metav1.DeleteOptions{PropagationPolicy: &deleteProp}); err != nil {
return err
}
return nil
}
|
[
6
] |
package main
import "zdy_demo/rpc_server/process"
func main() {
//process.Thrift()
process.Grpc()
}
|
[
3
] |
package main
import (
"fmt"
"github.com/PlatONnetwork/PlatON-Go/common"
"github.com/PlatONnetwork/PlatON-Go/x/staking"
"math/big"
)
func main() {
subDelegateFn := func(source, sub *big.Int) (*big.Int, *big.Int) {
return new(big.Int).Sub(source, sub), common.Big0
}
refundFn := func(remain, aboutRelease, aboutLockRepo *big.Int) (*big.Int, *big.Int, *big.Int, bool, error) {
// When remain is greater than or equal to del.ReleasedTmp/del.Released
if remain.Cmp(common.Big0) > 0 {
if remain.Cmp(aboutRelease) >= 0 && aboutRelease.Cmp(common.Big0) > 0 {
remain, aboutRelease = subDelegateFn(remain, aboutRelease)
} else if remain.Cmp(aboutRelease) < 0 {
// When remain is less than or equal to del.ReleasedTmp/del.Released
aboutRelease, remain = subDelegateFn(aboutRelease, remain)
}
}
if remain.Cmp(common.Big0) > 0 {
// When remain is greater than or equal to del.LockRepoTmp/del.LockRepo
if remain.Cmp(aboutLockRepo) >= 0 && aboutLockRepo.Cmp(common.Big0) > 0 {
return remain, aboutRelease, aboutLockRepo, false, nil
}
} else if remain.Cmp(aboutLockRepo) < 0 {
// When remain is less than or equal to del.LockRepoTmp/del.LockRepo
return remain, aboutRelease, aboutLockRepo, false, nil
}
return remain, aboutRelease, aboutLockRepo, true, nil
}
del := &staking.Delegation{
ReleasedHes: common.Big2,
RestrictingPlanHes: common.Big1,
}
//remain, release, lockRepo := common.Big2, common.Big1, common.Big3
remain := common.Big3
fmt.Println(remain, del.ReleasedHes, del.RestrictingPlanHes)
// 注意 结构体的不能直接赋值?
remain, release, lock, flag, err := refundFn(remain, del.ReleasedHes, del.RestrictingPlanHes)
del.ReleasedHes, del.RestrictingPlanHes = release, lock
fmt.Println(remain, del.ReleasedHes, del.RestrictingPlanHes, flag, err)
}
|
[
3
] |
package utils
import (
"context"
"fmt"
"sync"
"sync/atomic"
)
type LoadBalance[T any] interface {
Next(ctx context.Context) (T, error)
}
var ErrNoArguments = fmt.Errorf("error no arguments provided")
type roundRobin[T any] struct {
things []T
next uint32
}
// NewRoundRobin returns Round Robin implementation(roundRobin).
func NewRoundRobin[T any](things ...T) (LoadBalance[T], any) {
if len(things) == 0 {
return nil, ErrNoArguments
}
return &roundRobin[T]{things: things, next: 0}, nil
}
// Next returns things
func (r *roundRobin[T]) Next(ctx context.Context) (T, error) {
select {
case <-ctx.Done():
return getZero[T](), ctx.Err()
default:
}
n := atomic.AddUint32(&r.next, 1)
return r.things[(int(n)-1)%len(r.things)], nil
}
// getZero returns zero value of T.
func getZero[T any]() T {
var result T
return result
}
type conn[T any] struct {
thing T
cnt int
}
type leastConnections[T any] struct {
conns []conn[T]
mu *sync.Mutex
}
func NewLeastConnection[T any](things ...T) (LoadBalance[T], error) {
if len(things) == 0 {
return nil, ErrNoArguments
}
conns := make([]conn[T], len(things))
for i := range conns {
conns[i] = conn[T]{
thing: things[i],
cnt: 0,
}
}
return &leastConnections[T]{
conns: conns,
mu: new(sync.Mutex),
}, nil
}
func (lc *leastConnections[T]) Next(ctx context.Context) (T, error) {
select {
case <-ctx.Done():
return getZero[T](), ctx.Err()
default:
}
var (
min = -1
idx int
)
lc.mu.Lock()
for i, conn := range lc.conns {
if min == -1 || conn.cnt < min {
min = conn.cnt
idx = i
}
}
lc.conns[idx].cnt++
lc.mu.Unlock()
go func() {
// wait for the context to be done
<-ctx.Done()
lc.mu.Lock()
lc.conns[idx].cnt--
lc.mu.Unlock()
}()
return lc.conns[idx].thing, nil
}
|
[
1
] |
// Package human provides functions for converting a number to human readable form
package human
import (
"fmt"
"math"
"strconv"
"strings"
)
// Bytes transforms a number into a string with 1024 as base.
// Arguments: n - number to transform, decimals - number of decimals to show,
// long - if true, show full names, otherwise show abbreviated.
func Bytes(n int64, decimals int, long bool) string {
padding := " "
levels := []string{
"B", "KB", "MB", "GB", "TB", "PB", "EB", /* "ZB", "YB" will overflow int64 */
}
if long {
levels = []string{
"bytes", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte", "exabyte",
}
}
return human(n, levels, 1024, decimals, padding)
}
// Kilos transforms a number into a string with 1000 as base
// Arguments: n - number to transform, decimals - number of decimals to show,
// long - if true, show full names, otherwise show abbreviated.
func Kilos(n int64, decimals int, long bool) string {
padding := " "
levels := []string{
"", "k", "M", "G", "T", "P", "E", /* "Z", "Y" will overflow int64 */
}
if long {
levels = []string{
"s", "kilo", "mega", "giga", "tera", "peta", "exa",
}
}
return human(n, levels, 1000, decimals, padding)
}
// human - generic number to string conversion function
func human(n int64, levels []string, base int, decimals int, padding string) string {
format := fmt.Sprintf("%%.%df%v%%v", decimals, padding)
res := strconv.FormatInt(n, 10)
for i, level := range levels {
nom := float64(n)
den := math.Pow(float64(base), float64(i))
val := nom / den
if val < float64(base) {
res = fmt.Sprintf(format, val, level)
break
}
}
return strings.TrimSpace(res)
}
|
[
6
] |
package spawn
/*
Package spawn implements methods and interfaces used in downloading and spawning the underlying thrust core binary.
*/
import (
"fmt"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
//. "github.com/miketheprogrammer/go-thrust/lib/common"
//"github.com/miketheprogrammer/go-thrust/lib/connection"
// Switch to Vendoring
//. "GoServe/external/go-thrust-master/lib/common"
//"GoServe/external/go-thrust-master/lib/connection"
. "go-thrust/lib/common"
"go-thrust/lib/connection"
)
const (
thrustVersion = "0.7.6"
)
var (
// ApplicationName only functionally applies to OSX builds, otherwise it is only cosmetic
ApplicationName = "Go Thrust"
// base directory for storing the executable
base = ""
)
/*
SetBaseDirectory sets the base directory used in the other helper methods
*/
func SetBaseDirectory(dir string) error {
if len(dir) == 0 {
usr, err := user.Current()
if err != nil {
fmt.Println(err)
}
dir = usr.HomeDir
}
dir, err := filepath.Abs(dir)
if err != nil {
fmt.Println("Could not calculate absolute path", err)
return err
}
base = dir
return nil
}
/*
The SpawnThrustCore method is a bootstrap and run method.
It will try to detect an installation of thrust, if it cannot find it
it will download the version of Thrust detailed in the "common" package.
Once downloaded, it will launch a process.
Go-Thrust and all *-Thrust packages communicate with Thrust Core via Stdin/Stdout.
using -log=debug as a command switch will give you the most information about what is going on. -log=info will give you notices that stuff is happening.
Any log level higher than that will output nothing.
*/
func Run() {
if Log == nil {
InitLogger("debug")
}
if base == "" {
SetBaseDirectory("") // Default to usr.homedir.
}
thrustExecPath := GetExecutablePath()
if len(thrustExecPath) > 0 {
if provisioner == nil {
SetProvisioner(NewThrustProvisioner())
}
if err := provisioner.Provision(); err != nil {
panic(err)
}
thrustExecPath = GetExecutablePath()
Log.Print("Attempting to start Thrust Core")
Log.Print("CMD:", thrustExecPath)
cmd := exec.Command(thrustExecPath)
cmdIn, e1 := cmd.StdinPipe()
cmdOut, e2 := cmd.StdoutPipe()
if e1 != nil {
fmt.Println(e1)
os.Exit(2) // need to improve exit codes
}
if e2 != nil {
fmt.Println(e2)
os.Exit(2)
}
if LogLevel != "none" {
cmd.Stderr = os.Stdout
}
if err := cmd.Start(); err != nil {
Log.Panic("Thrust Core not started.")
}
Log.Print("Thrust Core started.")
// Setup our Connection.
connection.Stdout = cmdOut
connection.Stdin = cmdIn
connection.ExecCommand = cmd
connection.InitializeThreads()
return
} else {
fmt.Println("===============WARNING================")
fmt.Println("Current operating system not supported", runtime.GOOS)
fmt.Println("===============END====================")
}
return
}
|
[
3
] |
package database
import (
"context"
"fmt"
"log"
"github.com/dinsharmagithub/sfhealth/proto"
)
//Insert Inserts one record in application specific table
//TODO it has to named better or under different package like sfhealth/crud
func Insert(ctx context.Context, req *proto.CreateRequest) error {
log.Printf("Inside Insert()\n")
txn, err := GetDbConn().Begin()
if err != nil {
log.Fatal(err)
}
defer txn.Rollback()
log.Printf("Transaction started \n")
fmt.Printf("Creating prepared statement\n")
stmtStr, err := txn.Prepare("INSERT INTO restaurant_scores(business_id, business_name, business_address, business_city, business_state, business_postal_code, business_latitude, business_longitude, business_location, business_phone_number, inspection_id, inspection_date, inspection_score, inspection_type, violation_id, violation_description, risk_category, neighborhoods_old, police_districts, supervisor_districts, fire_prevention_districts, zip_codes, analysis_neighborhoods) VALUES( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23 )")
//TODO clean
// stmtStr, err := txn.Prepare("INSERT INTO restaurant_scores(business_id, business_name, business_address, business_city, business_state, business_postal_code, business_latitude, business_longitude, business_location, business_phone_number, inspection_id, inspection_date, inspection_score, inspection_type, violation_id, violation_description, risk_category, neighborhoods_old, police_districts, supervisor_districts, fire_prevention_districts, zip_codes, analysis_neighborhoods) VALUES( 1, 2, 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test' )")
if err != nil {
fmt.Printf("Error in creating statement %v", err)
return err
}
defer stmtStr.Close()
log.Printf("Statement Insertd \n")
log.Printf("Executing the statement for business_id %v \n", req.GetRecord().GetBusinessId())
//Keeping long statement as punch cards time has gone
res, err := stmtStr.Exec(req.GetRecord().GetBusinessId(), req.GetRecord().GetBusinessName(), req.GetRecord().GetBusinessAddress(), req.GetRecord().GetBusinessCity(), req.GetRecord().GetBusinessState(), req.GetRecord().GetBusinessPostalCode(), req.GetRecord().GetBusinessLatitude(), req.GetRecord().GetBusinessLongitude(), req.GetRecord().GetBusinessLocation(), req.GetRecord().GetBusinessPhoneNumber(), req.GetRecord().GetInspectionId(), req.GetRecord().GetInspectionDate(), req.GetRecord().GetInspectionScore(), req.GetRecord().GetInspectionType(), req.GetRecord().GetViolationId(), req.GetRecord().GetViolationDescription(), req.GetRecord().GetRiskCategory(), req.GetRecord().GetNeighborhoodsOld(), req.GetRecord().GetPoliceDistricts(), req.GetRecord().GetSupervisorDistricts(), req.GetRecord().GetFirePreventionDistricts(), req.GetRecord().GetZipCodes(), req.GetRecord().GetAnalysisNeighborhoods())
if err != nil {
log.Printf("Error while inserting rows %v", err)
}
log.Printf("INSERT done with Result = %v\n doing commit now \n", res)
err = txn.Commit()
if err != nil {
log.Fatal(err)
}
log.Printf("Exiting Insert()\n")
return nil
}
|
[
3
] |
package util
import (
"fmt"
"github.com/weiliang-ms/easyctl/constant"
"os"
"strings"
"sync"
)
func CreateFile(filePath string, content string) {
file, err := os.Create(filePath)
defer file.Close()
if err != nil {
panic(err)
}
_, writeErr := file.WriteString(content)
if writeErr != nil {
panic(writeErr)
}
}
func OverwriteContent(filePath string, content string) {
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
defer file.Close()
if err != nil {
fmt.Println(err.Error())
}
_, writeErr := file.WriteString(content)
if writeErr != nil {
fmt.Println(err.Error())
}
}
func FormatFileName(name string) string {
array := strings.Split(name, "/")
if len(array) > 0 {
name = array[len(array)-1]
}
return name
}
func WriteFile(filePath string, b []byte, serverList []Server) {
if len(serverList) == 0 {
PrintActionBanner([]string{constant.LoopbackAddress}, fmt.Sprintf("写文件:%s", filePath))
OverwriteContent(filePath, string(b))
} else {
wg := sync.WaitGroup{}
wg.Add(len(serverList))
for _, v := range serverList {
PrintActionBanner([]string{v.Host}, fmt.Sprintf("写文件:%s:%s", v.Host, filePath))
go RemoteWriteFileParallel(filePath, b, v, &wg)
}
wg.Wait()
}
}
|
[
6
] |
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
import (
"math/big"
"github.com/ethereum/go-ethereum/common"
)
// Signs with Homestead
// obtains sender from EIP55Signer
type QuorumPrivateTxSigner struct{ HomesteadSigner }
func (s QuorumPrivateTxSigner) Sender(tx *Transaction) (common.Address, error) {
return HomesteadSigner{}.Sender(tx)
}
// SignatureValues returns signature values. This signature
// needs to be in the [R || S || V] format where V is 0 or 1.
func (qs QuorumPrivateTxSigner) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) {
r, s, _, _ := HomesteadSigner{}.SignatureValues(tx, sig)
// update v for private transaction marker: needs to be 37 (0+37) or 38 (1+37) for a private transaction.
v := new(big.Int).SetBytes([]byte{sig[64] + 37})
return r, s, v, nil
}
// Hash returns the hash to be signed by the sender.
// It does not uniquely identify the transaction.
func (s QuorumPrivateTxSigner) Hash(tx *Transaction) common.Hash {
return s.HomesteadSigner.Hash(tx)
}
func (s QuorumPrivateTxSigner) Equal(s2 Signer) bool {
_, ok := s2.(QuorumPrivateTxSigner)
return ok
}
/*
* If v is `37` or `38` that marks the transaction as private in Quorum.
* Note: this means quorum chains cannot have a public ethereum chainId == 1, as the EIP155 v
* param is `37` and `38` for the public Ethereum chain. Having a private chain with a chainId ==1
* is discouraged in the general Ethereum ecosystem.
*/
func isPrivate(v *big.Int) bool {
return v.Cmp(big.NewInt(37)) == 0 || v.Cmp(big.NewInt(38)) == 0
}
|
[
2
] |
package udwBytes
import (
"bytes"
"encoding/binary"
"io"
)
type BufReader struct {
buf []byte
pos int
}
func NewBufReader(buf []byte) *BufReader {
return &BufReader{
buf: buf,
}
}
func (r *BufReader) ResetWithBuffer(buf []byte) {
r.pos = 0
r.buf = buf
}
func (r *BufReader) Read(inBuf []byte) (n int, err error) {
remainSize := len(r.buf) - r.pos
if remainSize > len(inBuf) {
copy(inBuf, r.buf[r.pos:])
r.pos += len(inBuf)
return len(inBuf), nil
} else {
copy(inBuf, r.buf[r.pos:])
r.pos += remainSize
return remainSize, io.EOF
}
}
func (r *BufReader) ReadByte() (b byte, err error) {
if r.pos >= len(r.buf) {
return 0, io.EOF
}
b = r.buf[r.pos]
r.pos += 1
return b, nil
}
func (r *BufReader) MustReadByte() (b byte) {
b = r.buf[r.pos]
r.pos += 1
return b
}
func (r *BufReader) ReadByteOrEof() (b byte, isRead bool) {
if r.pos >= len(r.buf) {
return 0, false
}
b = r.buf[r.pos]
r.pos += 1
return b, true
}
func (r *BufReader) ReadAt(inBuf []byte, off int64) (n int, err error) {
remainSize := len(r.buf) - int(off)
if remainSize > len(inBuf) {
copy(inBuf, r.buf[r.pos:])
return len(inBuf), nil
} else {
copy(inBuf, r.buf[off:])
return remainSize, io.EOF
}
}
func (r *BufReader) IsEof() bool {
return r.pos >= len(r.buf)
}
func (r *BufReader) GetRemainSize() int {
return len(r.buf) - r.pos
}
func (r *BufReader) GetPos() int {
return r.pos
}
func (r *BufReader) SetPos(pos int) {
r.pos = pos
}
func (r *BufReader) AddPos(rel int) {
r.pos += rel
}
func (r *BufReader) GetBuf() []byte {
return r.buf
}
func (r *BufReader) ReadMaxByteNum(num int) []byte {
startPos := r.pos
if startPos >= len(r.buf) {
return nil
} else if r.pos+num < len(r.buf) {
r.pos += num
} else {
r.pos = len(r.buf)
}
return r.buf[startPos:r.pos]
}
func (r *BufReader) ReadHttpHeaderWithCallback(fn func(name []byte, value []byte)) (errMsg string) {
for {
if r.IsEof() {
return ""
}
thisLine := r.ReadToLineEnd()
thisLine = bytes.TrimSpace(thisLine)
if len(thisLine) == 0 {
return ""
}
headerName, value := SplitTwoBetweenFirst(thisLine, []byte(": "))
if len(headerName) == 0 || len(value) == 0 {
return "7yyaavsecr"
}
fn(headerName, value)
}
}
func (r *BufReader) ReadString255() (s string, errMsg string) {
if r.pos >= len(r.buf) {
return "", "emkdt38k48 unexpected EOF"
}
size := r.buf[r.pos]
r.pos += 1
if r.pos+int(size) > len(r.buf) {
return "", "7srvg667mv"
}
s = string(r.buf[r.pos : r.pos+int(size)])
r.pos += int(size)
return s, ""
}
func (r *BufReader) ReadCString() (s string) {
startPos := r.pos
for {
if r.pos >= len(r.buf) {
return string(r.buf[startPos:])
}
b := r.buf[r.pos]
r.pos++
if b == 0 {
break
}
}
return string(r.buf[startPos : r.pos-1])
}
func (r *BufReader) Close() (err error) {
return nil
}
func (r *BufReader) ReadBigEndUint16() (x uint16, isOk bool) {
buf := r.ReadMaxByteNum(2)
if len(buf) != 2 {
return 0, false
}
x = binary.BigEndian.Uint16(buf)
return x, true
}
func (r *BufReader) ReadBigEndUint32() (x uint32, isOk bool) {
buf := r.ReadMaxByteNum(4)
if len(buf) != 4 {
return 0, false
}
x = binary.BigEndian.Uint32(buf)
return x, true
}
func (r *BufReader) ReadBigEndUint64() (x uint64, isOk bool) {
buf := r.ReadMaxByteNum(8)
if len(buf) != 8 {
return 0, false
}
x = binary.BigEndian.Uint64(buf)
return x, true
}
func (r *BufReader) ReadLittleEndUint16() (x uint16, isOk bool) {
buf := r.ReadMaxByteNum(2)
if len(buf) != 2 {
return 0, false
}
x = binary.LittleEndian.Uint16(buf)
return x, true
}
func (r *BufReader) ReadLittleEndUint32() (x uint32, isOk bool) {
buf := r.ReadMaxByteNum(4)
if len(buf) != 4 {
return 0, false
}
x = binary.LittleEndian.Uint32(buf)
return x, true
}
func (r *BufReader) ReadLittleEndUint64() (x uint64, isOk bool) {
buf := r.ReadMaxByteNum(8)
if len(buf) != 8 {
return 0, false
}
x = binary.LittleEndian.Uint64(buf)
return x, true
}
func (r *BufReader) ReadStringLenUint32() (s string, isOk bool) {
sLen, ok := r.ReadLittleEndUint32()
if !ok {
return s, false
}
if r.pos+int(sLen) > len(r.buf) {
return s, false
}
s = string(r.buf[r.pos : r.pos+int(sLen)])
r.pos += int(sLen)
return s, true
}
func (r *BufReader) PeekByte() (b byte, ok bool) {
if len(r.buf) <= r.pos {
return 0, false
}
return r.buf[r.pos], true
}
func (r *BufReader) ReadByteSlice(num int) (s []byte, ok bool) {
end := r.pos + num
if num < 0 || end > len(r.buf) {
return nil, false
}
s = r.buf[r.pos:end]
r.pos = end
return s, true
}
func (r *BufReader) MustReadByteSlice(num int) (s []byte) {
end := r.pos + num
if end > len(r.buf) {
panic(`t2ga4b2n9x`)
}
s = r.buf[r.pos:end]
r.pos = end
return
}
func (r *BufReader) MustReadLittleEndUint32() (x uint32) {
buf := r.ReadMaxByteNum(4)
if len(buf) != 4 {
panic("bezxbb5n3b")
}
x = binary.LittleEndian.Uint32(buf)
return x
}
|
[
5,
6
] |
package engine
import (
"fmt"
"os"
"path"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/juju/errors"
bunyan "github.com/mumoshu/logrus-bunyan-formatter"
"github.com/spf13/viper"
"github.com/mumoshu/variant/api/flow"
"github.com/mumoshu/variant/api/step"
"github.com/mumoshu/variant/util/maputil"
"reflect"
)
type Application struct {
Name string
CommandRelativePath string
CachedFlowOutputs map[string]interface{}
ConfigFile string
Verbose bool
Output string
Env string
FlowRegistry *FlowRegistry
InputResolver InputResolver
FlowKeyCreator *FlowKeyCreator
LogToStderr bool
}
func (p Application) UpdateLoggingConfiguration() {
if p.Verbose {
log.SetLevel(log.DebugLevel)
}
if p.LogToStderr {
log.SetOutput(os.Stderr)
}
commandName := path.Base(os.Args[0])
if p.Output == "bunyan" {
log.SetFormatter(&bunyan.Formatter{Name: commandName})
} else if p.Output == "json" {
log.SetFormatter(&log.JSONFormatter{})
} else if p.Output == "text" {
log.SetFormatter(&log.TextFormatter{})
} else if p.Output == "message" {
log.SetFormatter(&MessageOnlyFormatter{})
} else {
log.Fatalf("Unexpected output format specified: %s", p.Output)
}
}
func (p Application) RunFlowForKeyString(keyStr string, args []string, provided flow.ProvidedInputs, caller ...step.Caller) (string, error) {
flowKey := p.FlowKeyCreator.CreateFlowKey(fmt.Sprintf("%s.%s", p.Name, keyStr))
return p.RunFlowForKey(flowKey, args, provided, caller...)
}
func (p Application) RunFlowForKey(flowKey step.Key, args []string, providedInputs flow.ProvidedInputs, caller ...step.Caller) (string, error) {
var ctx *log.Entry
if len(caller) == 1 {
ctx = log.WithFields(log.Fields{"flow": flowKey.ShortString(), "caller": caller[0].GetKey().ShortString()})
} else {
ctx = log.WithFields(log.Fields{"flow": flowKey.ShortString()})
}
ctx.Debugf("app started flow %s", flowKey.ShortString())
provided := p.GetValueForConfigKey(flowKey.ShortString())
if provided != nil {
p := *provided
ctx.Debugf("app skipped flow %s via provided value: %s", flowKey.ShortString(), p)
ctx.Info(p)
println(p)
return p, nil
}
flowDef, err := p.FlowRegistry.FindFlow(flowKey)
if err != nil {
return "", errors.Annotatef(err, "app failed finding flow %s", flowKey.ShortString())
}
vars := map[string](interface{}){}
vars["args"] = args
vars["env"] = p.Env
vars["cmd"] = p.CommandRelativePath
inputs, err := p.InheritedInputValuesForFlowKey(flowKey, args, providedInputs, caller...)
if err != nil {
return "", errors.Annotatef(err, "app failed running flow %s", flowKey.ShortString())
}
for k, v := range inputs {
vars[k] = v
}
flow := &BoundFlow{
Vars: vars,
Flow: *flowDef,
}
kv := maputil.Flatten(vars)
ctx.WithField("variables", kv).Debugf("app bound variables for flow %s", flowKey.ShortString())
output, error := flow.Run(&p, caller...)
ctx.Debugf("app received output from flow %s: %s", flowKey.ShortString(), output)
if error != nil {
error = errors.Annotatef(error, "app failed running flow %s", flowKey.ShortString())
}
ctx.Debugf("app finished running flow %s", flowKey.ShortString())
return output, error
}
func (p Application) InheritedInputValuesForFlowKey(flowKey step.Key, args []string, provided flow.ProvidedInputs, caller ...step.Caller) (map[string]interface{}, error) {
result := map[string]interface{}{}
// TODO make this parents-first instead of children-first?
direct, err := p.DirectInputValuesForFlowKey(flowKey, args, provided, caller...)
if err != nil {
return nil, errors.Annotatef(err, "One or more inputs for flow %s failed", flowKey.ShortString())
}
for k, v := range direct {
result[k] = v
}
parentKey, err := flowKey.Parent()
if err == nil {
inherited, err := p.InheritedInputValuesForFlowKey(parentKey, []string{}, provided, caller...)
if err != nil {
return nil, errors.Annotatef(err, "AggregateInputsForParent(%s) failed", flowKey.ShortString())
}
maputil.DeepMerge(result, inherited)
}
return result, nil
}
type AnyMap map[string]interface{}
func (p Application) GetValueForConfigKey(k string) *string {
ctx := log.WithFields(log.Fields{"key": k})
lastIndex := strings.LastIndex(k, ".")
valueFromFlag := viper.GetString(fmt.Sprintf("flags.%s", k))
if valueFromFlag != "" {
return &valueFromFlag
}
if lastIndex != -1 {
a := []rune(k)
k1 := string(a[:lastIndex])
k2 := string(a[lastIndex+1:])
ctx.Debugf("viper.Get(%v): %v", k1, viper.Get(k1))
if viper.Get(k1) != nil {
values := viper.Sub(k1)
ctx.Debugf("app fetched %s: %v", k1, values)
var provided *string
if values != nil && values.Get(k2) != nil {
str := values.GetString(k2)
provided = &str
} else {
provided = nil
}
ctx.Debugf("app fetched %s[%s]: %s", k1, k2, provided)
if provided != nil {
return provided
}
}
return nil
} else {
raw := viper.Get(k)
ctx.Debugf("app fetched raw value for key %s: %v", k, raw)
ctx.Debugf("type of value fetched: %v", reflect.TypeOf(raw))
if str, ok := raw.(string); ok {
return &str
} else if raw == nil {
return nil
} else {
panic(fmt.Sprintf("unexpected type of value fetched: %v", reflect.TypeOf(raw)))
}
}
}
func (p Application) DirectInputValuesForFlowKey(flowKey step.Key, args []string, provided flow.ProvidedInputs, caller ...step.Caller) (map[string]interface{}, error) {
var ctx *log.Entry
if len(caller) == 1 {
ctx = log.WithFields(log.Fields{"caller": caller[0].GetKey().ShortString(), "flow": flowKey.ShortString()})
} else {
ctx = log.WithFields(log.Fields{"flow": flowKey.ShortString()})
}
values := map[string]interface{}{}
var baseFlowKey string
if len(caller) > 0 {
baseFlowKey = caller[0].GetKey().ShortString()
} else {
baseFlowKey = ""
}
ctx.Debugf("app started collecting inputs")
flowDef, err := p.FlowRegistry.FindFlow(flowKey)
if err != nil {
return nil, errors.Trace(err)
}
for _, input := range flowDef.ResolvedInputs {
ctx.Debugf("app sees flow depends on input %s", input.ShortName())
var positional *string
if i := input.ArgumentIndex; i != nil && len(args) >= *i+1 {
ctx.Debugf("app found positional argument: args[%d]=%s", input.ArgumentIndex, args[*i])
positional = &args[*i]
}
var nullableValue *string
if v, err := provided.Get(input.Name); err == nil {
nullableValue = &v
}
if nullableValue == nil && baseFlowKey != "" {
nullableValue = p.GetValueForConfigKey(fmt.Sprintf("%s.%s", baseFlowKey, input.ShortName()))
}
if nullableValue == nil && strings.LastIndex(input.ShortName(), flowKey.ShortString()) == -1 {
nullableValue = p.GetValueForConfigKey(fmt.Sprintf("%s.%s", flowKey.ShortString(), input.ShortName()))
}
if nullableValue == nil {
nullableValue = p.GetValueForConfigKey(input.ShortName())
}
pathComponents := strings.Split(input.Name, ".")
if positional != nil {
maputil.SetValueAtPath(values, pathComponents, *positional)
} else if nullableValue == nil {
var output interface{}
var err error
if output, err = maputil.GetValueAtPath(p.CachedFlowOutputs, pathComponents); output == nil {
output, err = p.RunFlowForKey(p.FlowKeyCreator.CreateFlowKeyFromResolvedInput(input), []string{}, flow.NewProvidedInputs(), *flowDef)
if err != nil {
return nil, errors.Annotatef(err, "Missing value for input `%s`. Please provide a command line option or a positional argument or a flow for it`", input.ShortName())
}
maputil.SetValueAtPath(p.CachedFlowOutputs, pathComponents, output)
}
if err != nil {
return nil, errors.Trace(err)
}
maputil.SetValueAtPath(values, pathComponents, output)
} else {
maputil.SetValueAtPath(values, pathComponents, *nullableValue)
}
}
ctx.WithField("values", values).Debugf("app finished collecting inputs")
return values, nil
}
func (p *Application) Flows() map[string]*Flow {
return p.FlowRegistry.Flows()
}
|
[
5
] |
package external_service
import "github.com/pefish/go-core/driver/external-service"
type DepositAddressServiceClass struct {
baseUrl string
external_service.BaseExternalServiceClass
}
var DepositAddressService = DepositAddressServiceClass{}
func (this *DepositAddressServiceClass) Init(driver *external_service.ExternalServiceDriverClass) {
this.baseUrl = `http://baidu.com`
}
func (this *DepositAddressServiceClass) Test(series string, address string) interface{} {
path := ``
return this.PostJson(this.baseUrl + path, map[string]interface{}{
`series`: series,
`address`: address,
})
}
|
[
6
] |
package ticket
import (
"time"
"github.com/andresnatanael/go-training2/cinema"
)
const (
//RegularPrice represent the current price that will
//be used for all kind of tickets
RegularPrice = float32(100)
guestDiscount = float32(100)
retiredDiscount = float32(50)
)
//Ticket interface represent the base
//Operations for tickets
type Ticket interface {
GetMovie() cinema.Movie
GetShowTime() time.Time
GetCurrentPrice() float32
GetPaidPrice() float32
SetPaidPrice(price float32)
GetType() string
GetDiscount() float32
}
|
[
3
] |
package dao
import (
"goweb/day03/bookstore0612/model"
"goweb/day03/bookstore0612/utils"
)
//CheckUserNameAndPassword 根据用户名和密码从数据库中查询一条记录
func CheckUserNameAndPassword(username string, password string) (*model.User, error) {
//写sql语句
sqlStr := "select id,username,password,email from users where username = ? and password = ?"
//执行
row := utils.Db.QueryRow(sqlStr, username, password)
user := &model.User{}
row.Scan(&user.ID, &user.Username, &user.Password, &user.Email)
return user, nil
}
//CheckUserName 根据用户名和密码从数据库中查询一条记录
func CheckUserName(username string) (*model.User, error) {
//写sql语句
sqlStr := "select id,username,password,email from users where username = ?"
//执行
row := utils.Db.QueryRow(sqlStr, username)
user := &model.User{}
row.Scan(&user.ID, &user.Username, &user.Password, &user.Email)
return user, nil
}
//SaveUser 向数据库中插入用户信息
func SaveUser(username string, password string, email string) error {
//写sql语句
sqlStr := "insert into users(username,password,email) values(?,?,?)"
//执行
_, err := utils.Db.Exec(sqlStr, username, password, email)
if err != nil {
return err
}
return nil
}
//Updatebook 根据图书id更新图书信息
func UpdateBook(b *model.Book) error {
//写sql语句
sqlStr := "update books set title=?,author=?,price=?,sales=?,stock=? where id=?"
//执行
_, err := utils.Db.Exec(sqlStr, b.Title, b.Author, b.Price, b.Sales, b.Stock, b.ID)
if err != nil {
return err
}
return nil
}
|
[
3,
6
] |
package jira
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/mkobaly/devop/config"
)
//ApiError represents a set of error(s) that the rest api threw
type ApiError struct {
ErrorMessages []string `json:"errorMessages"`
Errors interface{} `json:"errors"`
}
func (e ApiError) String() string {
return strings.Join(e.ErrorMessages, " ")
}
type BaseFields struct {
Id string `json:"id"`
Self string `json:"self"`
}
type IssueLink struct {
BaseFields
Type map[string]string `json:"type"`
InwardIssue Issue `json:"inwardIssue"`
OutwardIssue Issue `json:"outwardIssue"`
}
type Issue struct {
BaseFields
Key string `json:"key"`
Fields IssueFields `json:fields"`
}
type IssueFields struct {
Summary string `json:"summary"`
Progress IssueFieldProgress `json:"progress"`
IssueType IssueType `json:"issuetype"`
ResolutionDate interface{} `json:"resolutiondate"`
Timespent interface{} `json:"timespent"`
Creator IssueFieldCreator `json:"creator"`
Created string `json:"created"`
Updated string `json:"updated"`
Labels []string `json:"labels"`
Assignee IssueFieldCreator `json:"assignee"`
Description interface{} `json:"description"`
IssueLinks []IssueLink `json:"issueLinks"`
Status IssueStatus `json:"status"`
}
type IssueFieldProgress struct {
Progress int `json:"progress"`
Total int `json:"total"`
}
type IssueFieldCreator struct {
Self string `json:"self"`
Name string `json:"name"`
EmailAddress string `json:"emailAddress"`
AvatarUrls map[string]string `json:"avatarUrls"`
DisplayName string `json:"displayName"`
Active bool `json:"active"`
}
type IssueType struct {
BaseFields
Description string `json:"description"`
IconUrl string `json:"iconURL"`
Name string `json:"name"`
Subtask bool `json:"subtask"`
}
type IssueStatus struct {
BaseFields
Name string `json:"name"`
}
//New will create a new instance of Jira Rest API
func New(credentials config.UserCredential) *RestAPI {
return &RestAPI{credentials: credentials}
//var api = new(RestAPI)
//api.credentials = credentials
//return api
}
// RestAPI wraps some basic rest calls to work with Jira
type RestAPI struct {
credentials config.UserCredential
}
// GetJiraRelease returns Epic information
func (api *RestAPI) GetRelease(epicID string) ([]ReleaseItem, error) {
results := []ReleaseItem{}
issue, err := api.getIssue(epicID)
if err != nil {
return results, err
}
scanner := bufio.NewScanner(strings.NewReader(issue.Fields.Description.(string)))
for scanner.Scan() {
line := strings.ToLower(scanner.Text())
if strings.Contains(line, "/app#/projects") {
parts := strings.Split(line, "/")
results = append(results, ReleaseItem{Project: parts[5], Version: parts[7]})
}
}
return results, nil
}
func (api *RestAPI) CreateEpicNew(project string, summary string, projectItems []ProjectItem) (*Issue, error) {
desc := convertToDescription(projectItems)
i := issue{summary: summary, description: desc, project: project1{key: project}, issuetype: issuetype{name: "epic"}}
b, _ := json.Marshal(i)
issue, err := api.createIssue(bytes.NewReader(b))
return issue, err
}
//CreateEpic will create a new release epic in Jira
func (api *RestAPI) CreateEpic(project string, summary string, releaseItems []ReleaseItem) (*Issue, error) {
i := issue{summary: summary, project: project1{key: project}, issuetype: issuetype{name: "epic"}}
b, _ := json.Marshal(i)
issue, err := api.createIssue(bytes.NewReader(b))
return issue, err
}
func convertToDescription(pi []ProjectItem) string {
desc := "..."
for _, r := range pi {
desc += fmt.Sprintf("%s|%s\r\n", r.Project, r.Branch)
}
return desc
}
func (api *RestAPI) DeleteIssue(issue *Issue) error {
url := fmt.Sprintf("%s/issue/%s", api.credentials.URL, issue.Key)
code, body := api.execRequest("DELETE", url, nil)
if code != http.StatusNoContent {
return handleJiraError(body)
}
return nil
}
func (api *RestAPI) createIssue(params io.Reader) (*Issue, error) {
url := fmt.Sprintf("%s/issue", api.credentials.URL)
code, body := api.execRequest("POST", url, params)
if code == http.StatusCreated {
response := make(map[string]string)
err := json.Unmarshal(body, &response)
if err != nil {
return nil, err
}
return api.getIssue(response["key"])
}
return nil, handleJiraError(body)
}
func (api *RestAPI) getIssue(issueKey string) (*Issue, error) {
url := fmt.Sprintf("%s/issue/%s", api.credentials.URL, issueKey)
code, body := api.execRequest("GET", url, nil)
if code == http.StatusOK {
var issue Issue
err := json.Unmarshal(body, &issue)
if err != nil {
return nil, err
}
return &issue, nil
}
return nil, handleJiraError(body)
}
// ReleaseItem is a line item in the Jira Release (Epic) that should be deployed
type ReleaseItem struct {
Project string
Version string
}
// ProjectItem represents a project and git branch
type ProjectItem struct {
Project string
Branch string
}
func (api *RestAPI) execRequest(requestType, requestUrl string, data io.Reader) (int, []byte) {
client := &http.Client{}
req, err := http.NewRequest(requestType, requestUrl, data)
if err != nil {
panic(err)
}
req.Header.Add("Content-Type", "application/json")
req.SetBasicAuth(api.credentials.Username, api.credentials.Password)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return resp.StatusCode, body
}
func handleJiraError(body []byte) error {
errorAnswer := ApiError{}
err := json.Unmarshal(body, &errorAnswer)
if err != nil {
return err
}
return errors.New(errorAnswer.String())
}
type project1 struct {
key string
}
type issuetype struct {
name string
}
type issue struct {
summary string
description string
project project1
issuetype issuetype
}
/*
{
"fields": {
"project":
{
"key": "TEST"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
}
*/
|
[
3,
6
] |
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"strings"
"text/tabwriter"
"github.com/TJM/go-trello"
"github.com/alexflint/go-arg"
)
var args struct {
AppKey string `arg:"required,env:TRELLO_APP_KEY" help:"Trello API App Key.\n\t\t Obtain yours at https://trello.com/app-key\n\t\t (env: TRELLO_APP_KEY)"`
Token string `arg:"required,env:TRELLO_TOKEN" help:"Trello API App Key.\n\t\t Authorize your App Key to use your account at <https://trello.com/1/connect?key=<appKey from above>&name=Go-Trello-Example-delete_boards&response_type=token&scope=read,write&expiration=1day>\n\t\t (env: TRELLO_TOKEN)"`
AnyOf bool `help:"Match AnyOf the StartsWith, Contains or EndsWith conditions. By default board name must match all of the conditions."`
StartsWith string `help:"Select boards to delete that *start with* this string"`
Contains string `help:"Select boards to delete that *contain* this string"`
EndsWith string `help:"Select boards to delete that *end with* this string"`
Delete bool `help:"Actually DELETE the boards (defaults to false so you can see what will happen)"`
Debug bool `help:"Enable debugging output"`
}
var w *tabwriter.Writer
func main() {
// Parse Command Line Args
arg.MustParse(&args)
// Tab Writer
w = new(tabwriter.Writer)
w.Init(os.Stdout, 4, 4, 2, ' ', tabwriter.TabIndent)
// New Trello Client
appKey := args.AppKey
token := args.Token
trello, err := trello.NewAuthClient(appKey, &token)
if err != nil {
log.Fatal(err)
}
// User @trello
user, err := trello.Member("me")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Trello User: %s (%s) <%s>\n", user.FullName, user.Username, user.URL)
// @trello Boards
boards, err := user.Boards()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Trello Boards: %v\n", len(user.IDBoards))
fmt.Fprintf(w, "\tAction\tBoard Name\tURL\n")
fmt.Fprintf(w, "\t------\t----------\t---\n")
for _, board := range boards {
var action string
if args.Debug {
boardJSON, err := json.MarshalIndent(board, "", " ")
if err != nil {
log.Fatalf(err.Error())
}
fmt.Printf("====================\n%s:\n%s\n\n", board.Name, string(boardJSON))
}
if args.AnyOf {
// AnyOf
if args.StartsWith != "" && strings.HasPrefix(board.Name, args.StartsWith) {
action = removeBoard(board, user)
} else if args.Contains != "" && strings.Contains(board.Name, args.Contains) {
action = removeBoard(board, user)
} else if args.EndsWith != "" && strings.HasSuffix(board.Name, args.EndsWith) {
action = removeBoard(board, user)
} else {
action = "KEEP"
}
} else {
if args.StartsWith == "" && args.Contains == "" && args.EndsWith == "" { // If no conditions are set, KEEP
action = "KEEP"
} else if (args.StartsWith == "" || strings.HasPrefix(board.Name, args.StartsWith)) &&
(args.Contains == "" || strings.Contains(board.Name, args.Contains)) &&
(args.EndsWith == "" || strings.HasSuffix(board.Name, args.EndsWith)) { // If a condition is set, and matches, DELETE
action = removeBoard(board, user)
} else { // KEEP by default
action = "KEEP"
}
}
fmt.Fprintf(w, "\t%s\t%s\t<%s>\n", action, board.Name, board.ShortURL)
}
// Output Tabwriter Table
fmt.Printf("\n")
w.Flush()
if !args.Delete {
fmt.Printf("\n\n ** Run again with --delete flag to actually delete the board(s).\n\n")
}
}
func removeBoard(board *trello.Board, user *trello.Member) (action string) {
if args.Delete {
if board.IsAdmin(user) {
fmt.Printf("DELETING: %s <%s> ...\n", board.Name, board.ShortURL)
err := board.Delete()
action = "DELETED"
if err != nil {
fmt.Printf("ERROR Deleting board: %v\n", err)
action = "ERROR DELETING"
}
} else {
fmt.Printf("LEAVING: %s <%s> ...\n", board.Name, board.ShortURL)
err := board.RemoveMember(user)
action = "LEFT"
if err != nil {
fmt.Printf("ERROR Leaving board: %v\n", err)
action = "ERROR LEAVING"
}
}
} else {
if board.IsAdmin(user) {
action = "DELETE"
} else {
action = "LEAVE"
}
}
return
}
|
[
5
] |
package binlog
import (
"os"
"sync"
"library/service"
"github.com/siddontang/go-mysql/canal"
"library/app"
)
type Binlog struct {
// github.com/siddontang/go-mysql interface
canal.DummyEventHandler
// config
Config *app.MysqlConfig
// github.com/siddontang/go-mysql mysql protocol handler
handler *canal.Canal
// context, like that use for wait coroutine exit
ctx *app.Context
// use for wait coroutine exit
wg *sync.WaitGroup
// lock
lock *sync.Mutex
statusLock *sync.Mutex
// event unique index
EventIndex int64
// registered service, key is the name of the service
services map[string]service.Service
// cache handler, use for read and write cache file
// binlog_handler.go SaveBinlogPostionCache and getBinlogPositionCache
cacheHandler *os.File
// the last read pos
lastPos uint32
// the last read binlog file
lastBinFile string
startServiceChan chan struct{}
stopServiceChan chan bool
// binlog status
status int
//pos change 回调函数
onPosChanges []PosChangeFunc
onEvent []OnEventFunc
}
type BinlogOption func(h *Binlog)
type PosChangeFunc func(r []byte)
type OnEventFunc func(table string, data []byte)
const (
//start stop
binlogIsRunning = 1 << iota
// binlog is in exit status, will exit later
binlogIsExit
cacheHandlerIsOpened
)
|
[
3
] |
package main
import (
"context"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/dyweb/gommon/log/handlers/cli"
"github.com/benchhub/benchhub/exp/qaq16/config"
"github.com/dyweb/gommon/errors"
dlog "github.com/dyweb/gommon/log"
)
var (
logReg = dlog.NewRegistry()
log = logReg.Logger()
)
func main() {
args := os.Args
// TODO: use gommon/dcli, don't want to use cobra anymore
if len(args) < 2 {
log.Fatal("must provide action e.g. qaq16 run; qaq16 rm")
return
}
var err error
action := args[1]
switch action {
case "rm", "kill":
err = RmContainers(context.Background())
case "run":
if len(args) < 3 {
log.Fatal("must provide context for run e.g. qaq16 run go")
return
}
ctx := args[2]
err = run(ctx)
default:
log.Fatalf("unknown action %s", action)
}
if err != nil {
log.Fatal(err)
}
}
func mergeEnvs(base []config.Env, ext []config.Env) []config.Env {
var merged []config.Env
merged = append(merged, base...)
merged = append(merged, ext...)
// TODO: remove dup
return merged
}
func extendContainer(containers []config.Container) ([]config.Container, error) {
abstracts := make(map[string]config.Container)
var unresolved []config.Container
var resolved []config.Container
for _, c := range containers {
switch {
case c.Abstract:
abstracts[c.Name] = c
case c.Extends == "":
resolved = append(resolved, c)
case c.Extends != "":
unresolved = append(unresolved, c)
default:
// should never happen
return nil, errors.Errorf("container must be abstract, extends or final %s", c.Name)
}
}
for _, c := range unresolved {
base, ok := abstracts[c.Extends]
if !ok {
return nil, errors.Errorf("container base not found %s wants %s", c.Name, c.Extends)
}
// simply copy everything
c.Image = base.Image
c.Resource = base.Resource
c.Envs = mergeEnvs(base.Envs, c.Envs)
resolved = append(resolved, c)
}
return resolved, nil
}
const paramPrefix = "param."
func resolveEnv(c *config.Container, params []config.Parameter) error {
pmap := make(map[string]int)
for _, p := range params {
pmap[p.Name] = p.Default
}
for i, env := range c.Envs {
if strings.HasPrefix(env.Value, paramPrefix) {
key := strings.TrimPrefix(env.Value, paramPrefix)
v, ok := pmap[key]
if !ok {
return errors.Errorf("param not found container %s requires %s", c.Name, key)
}
env.Value = strconv.Itoa(v)
c.Envs[i] = env
}
}
return nil
}
// TODO: allow dry run, print config and exit
func run(contextName string) error {
cfg, err := config.Read("qaq15.yml")
if err != nil {
return err
}
// select context
var selectedContext config.Context
for _, ctx := range cfg.Contexts {
if ctx.Name == contextName {
selectedContext = ctx
break
}
}
if selectedContext.Name == "" {
return errors.Errorf("context not found no %s", contextName)
}
containers, err := extendContainer(cfg.Containers)
if err != nil {
return err
}
for i := range containers {
if err := resolveEnv(&containers[i], cfg.Parameters); err != nil {
return err
}
}
now := time.Now()
logPrefix, err := NewLogDir(cfg.Data, now)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
wg.Add(len(containers) + 1)
merr := errors.NewMultiErrSafe()
// Run containers
for _, container := range containers {
container := container
container.Image = selectedContext.Image
go func() {
defer wg.Done()
reportError := func(err error) {
merr.Append(err)
log.Error(err)
cancel() // TODO: is cancel go routine safe?
}
// Add a mount in $logdir/$container to /qaq16
if p, err := NewMountDir(logPrefix, container.Name); err != nil {
reportError(err)
return
} else {
container.Mounts = append(container.Mounts, config.Mount{
Src: p,
Dst: "/qaq16",
})
}
execCtx := ExecContext{log: FormatLog(logPrefix, container.Name)}
if err := RunContainer(ctx, container, execCtx); err != nil {
reportError(err)
}
}()
}
// FIXME: hack to wait container ready
time.Sleep(1 * time.Second)
// Run score
go func() {
defer wg.Done()
execCtx := ExecContext{log: FormatLog(logPrefix, "score")}
if err := RunScore(ctx, cfg.Score, execCtx); err != nil {
merr.Append(err)
log.Error(err)
cancel()
}
}()
wg.Wait()
return merr.ErrorOrNil()
}
func init() {
dlog.SetHandler(cli.New(os.Stderr, false))
}
|
[
6
] |
package main
import (
"image"
"image/color"
"image/gif"
)
// a palette I stole online for the image.NewPaletted - required.
var palette = []color.Color{
color.White,
color.RGBA{250, 130, 0, 100},
color.RGBA{0, 0, 250, 100},
color.RGBA{0, 250, 0, 100},
// color.RGBA{0xff, 0x00, 0x00, 0xff},
// color.RGBA{0xff, 0x00, 0xff, 0xff},
// color.RGBA{0xff, 0xff, 0x00, 0xff},
// color.RGBA{0xff, 0xff, 0xff, 0xff},
}
// xy coordinates
type xy struct {
x, y int
}
// squareParams are the parameters for square()
type squareParams struct {
from, to xy
c color.Color
}
// square draws a square on a paletted image, taking in squareParams as a struct
func square(img *image.Paletted, p squareParams) {
for x := p.from.x; x < p.to.x; x++ {
for y := p.from.y; y < p.to.y; y++ {
img.Set(x, y, p.c)
}
}
}
// lineParams are the parameters to call line
type lineParams struct {
location xy
direction int
length int
c color.RGBA
}
// line takes an image, the start coordinates,
// the direction and distance of the line, and the color
// of the line
// func straightLine(img *image.Paletted, start xy, dir, length int, c color.Color) {
func line(img *image.Paletted, p lineParams) {
switch p.direction {
case left:
for i := p.length; i >= 0; i-- {
img.Set(p.location.x-i, p.location.y, p.c)
}
case right:
for i := 0; i <= p.length; i++ {
img.Set(p.location.x+i, p.location.y, p.c)
}
case up:
for i := p.length; i >= 0; i-- {
img.Set(p.location.x, p.location.y-i, p.c)
}
case down:
for i := 0; i <= p.length; i++ {
img.Set(p.location.x, p.location.y+i, p.c)
}
}
}
// createUlam creates an ulam gif and sends it to a writer
func createUlam(positions []position) *gif.GIF {
var (
images []*image.Paletted // images for the gif
delays []int // delays to transition to the next gif
lines []lineParams // parameters for each line creation call
squares []squareParams // parameters for each squares - defaulted to 0 for non primes
lenLine = 10 // length of each line
wh = 500 // to keep width and height equal
w, h = wh, wh // width and height
lastLoc = xy{wh / 2, wh / 2} // beginning position, also placeholder for each previous location
delayCt = 0 // delayCount for transition between images
)
// Loop over positions and create a new image, utilizing the previous straightLine calls
for i, pos := range positions {
img := image.NewPaletted(image.Rect(0, 0, w, h), palette)
lines = append(lines, lineParams{
location: lastLoc,
direction: pos.direction,
length: lenLine,
c: color.RGBA{}})
for _, p := range lines {
line(img, p)
}
for _, p := range squares {
square(img, p)
}
// Change the lastLocation based on the current direction
// to keep track of what the next location start needs to be
switch pos.direction {
case down:
lastLoc = xy{lastLoc.x, lastLoc.y + lenLine}
case up:
lastLoc = xy{lastLoc.x, lastLoc.y - lenLine}
case left:
lastLoc = xy{lastLoc.x - lenLine, lastLoc.y}
case right:
lastLoc = xy{lastLoc.x + lenLine, lastLoc.y}
}
// Create a sqare for each prime
// This is called after lastLoc updates, so it's one frame behind.
if isPrime(pos.number) {
s := 2 //size
squares = append(squares, squareParams{
from: xy{lastLoc.x - s, lastLoc.y - s},
to: xy{lastLoc.x + s, lastLoc.y + s},
c: color.RGBA{255, 150, 0, 255}})
} else {
squares = append(squares, squareParams{})
}
// Pause for effect at last iteration
if i == len(positions)-1 {
delayCt = 6000
}
delays = append(delays, delayCt)
images = append(images, img)
}
return &gif.GIF{
Image: images,
Delay: delays,
}
}
func isPrime(n int) bool {
for i := 2; i < n; i++ {
if n%i == 0 && i != n {
return false
}
}
return true
}
|
[
3
] |
package jobs
import "log"
type Cleanup struct {
//logger *utils.Log
}
func (i *Cleanup) Run() {
log.Println("Running cleanup job")
//ctx := context.Background()
}
|
[
3
] |
package models
import "gin/bubble/dao"
// model
type Todo struct {
ID int `json:"id"`
Title string `json:"title"`
Status bool `json:"status"`
//CreateTime int `json:"create_time"`
//UpdateTime int `json:"update_time"`
}
// 新增
func CreateTodo(todo *Todo) (err error) {
err = dao.DB.Create(&todo).Error
return
}
// 编辑
func UpdateTodo(todo *Todo)(err error) {
err = dao.DB.Save(todo).Error
return
}
// 查询列表
func ListTodo() (todoList []*Todo, err error) {
if err:=dao.DB.Find(&todoList).Error;err!=nil{
return nil,err
}else{
return todoList,nil
}
}
// 删除
func DelTodo(id string) (err error) {
err = dao.DB.Where("id=?", id).Delete(&Todo{}).Error
return
}
// 单个查询
func OneTodo(id string) (todo *Todo,err error) {
todo = new(Todo)
if err:= dao.DB.Where("id=?", id).First(&todo).Error;err!=nil{
return nil,err
}
return todo,nil
}
|
[
3
] |
package model
import (
"fmt"
"fund/common"
"fund/lang"
"github.com/lauthrul/goutil/log"
"github.com/lauthrul/goutil/util"
"github.com/shopspring/decimal"
"strings"
"time"
)
type SinaFund struct {
Id string `json:"id"`
FundCode string `json:"fund_code" name:"代码"`
FundName string `json:"fund_name" name:"基金"`
//CompanyId string `json:"company_id"`
//FundShortName string `json:"fund_short_name"`
//FundLegalName string `json:"fund_legal_name"`
//FundPinyin string `json:"fund_pinyin"`
//FundRiskLevel string `json:"fund_risk_level"`
//ShareType string `json:"share_type"`
//FundType string `json:"fund_type"`
//Type1Id string `json:"type1_id"`
//Type2Id string `json:"type2_id"`
//Type3Id string `json:"type3_id"`
//HelpType4Id string `json:"help_type4_id"`
//IsMoneyFund string `json:"is_money_fund"`
//HfIncomeratio string `json:"hf_incomeratio"`
//Income string `json:"income"`
//Incomeratio string `json:"incomeratio"`
//IncomeratioT001 string `json:"incomeratio_t001"`
//IncomeratioS010 string `json:"incomeratio_s010"`
Netvalue string `json:"netvalue" name:"净值"`
TotalNetvalue string `json:"total_netvalue" name:"累计净值"`
Navdate string `json:"navdate" name:"更新日期"`
//FundState string `json:"fund_state"`
//MinShare string `json:"min_share"`
DayIncratio string `json:"day_incratio" name:"日涨幅"`
MonthIncratio string `json:"month_incratio" name:"月涨幅"`
QuarterIncratio string `json:"quarter_incratio" name:"近3月涨幅"`
YearIncratio string `json:"year_incratio" name:"近1年涨幅"`
ThisYearIncratio string `json:"this_year_incratio" name:"今年以来涨幅"`
HalfYearIncratio string `json:"half_year_incratio" name:"近半年涨幅"`
ThreeYearIncratio string `json:"three_year_incratio" name:"近3年涨幅"`
//Feerate1 string `json:"feerate1"`
//SinaFeerate1 string `json:"sina_feerate1"`
//Feerate2 string `json:"feerate2"`
//SinaFeerate2 string `json:"sina_feerate2"`
//Discountrate2 string `json:"discountrate2"`
//Feerate3 string `json:"feerate3"`
//SinaFeerate3 string `json:"sina_feerate3"`
//Dayinc string `json:"dayinc"`
//SubscribeState string `json:"subscribe_state"`
//DeclareState string `json:"declare_state"`
//WithdrawState string `json:"withdraw_state"`
//ValuagrState string `json:"valuagr_state"`
//TrendState string `json:"trend_state"`
//HopedeclareState string `json:"hopedeclare_state"`
//DeclareendDay string `json:"declareend_day"`
//RedeemendDay string `json:"redeemend_day"`
//OpenDay string `json:"open_day"`
//IsForbidbuybyredeem string `json:"is_forbidbuybyredeem"`
//TransFlag string `json:"trans_flag"`
//FundsubType string `json:"fundsub_type"`
//SubscribeBeigin string `json:"subscribe_beigin"`
//SinaSubscribeBeigin string `json:"sina_subscribe_beigin"`
//HelpSinaSubscribeBeigin string `json:"help_sina_subscribe_beigin"`
//SinaSubscribeEnd string `json:"sina_subscribe_end"`
//SubscribeEnd string `json:"subscribe_end"`
//Zjzfe string `json:"zjzfe"`
FundScale string `json:"fund_scale" name:"规模"`
FundManager []struct {
Name string `json:"name"`
Url string `json:"url"`
} `json:"fund_manager"`
UTime string `json:"u_time"`
CTime string `json:"c_time" name:"成立时间"`
ToThisDayIncratio string `json:"to_this_day_incratio" name:"成立以来涨幅"`
//LDay string `json:"l_day"`
//BonusDate string `json:"bonus_date"`
//Forbidbonustype string `json:"forbidbonustype"`
//Status string `json:"status"`
//QdiiConfirmDay string `json:"qdii_confirm_day"`
//TaCode string `json:"ta_code"`
//ManageRatio string `json:"manage_ratio"`
//FarePayRate string `json:"fare_pay_rate"`
//MinValue1 string `json:"min_value1"`
//MinValue2 string `json:"min_value2"`
//OpenStatus string `json:"open_status"`
//CanBuy struct { //在售状态
// Show string `json:"show"`
// Canbuy int `json:"canbuy"`
//} `json:"can_buy"`
Type2IdDesc string `json:"type2_id_desc" name:"类型"`
//JzAndSy string `json:"jz_and_sy"`
//MinValue string `json:"min_value"` // 起购金额
}
func (f SinaFund) GetMetas() []THMeta {
return []THMeta{
{lang.Text(common.Lan, "FundCode"), true, ""},
{lang.Text(common.Lan, "FundName"), false, ""},
{lang.Text(common.Lan, "FundType"), false, ""},
{lang.Text(common.Lan, "FundScale"), true, "fund_scale"},
{lang.Text(common.Lan, "CreateDate"), false, ""},
{lang.Text(common.Lan, "ManagerName"), false, ""},
{lang.Text(common.Lan, "NetValue"), true, "netvalue"},
{lang.Text(common.Lan, "TotalNetValue"), false, ""},
{lang.Text(common.Lan, "Date"), false, ""},
{lang.Text(common.Lan, "DayRate"), true, "day_incratio"},
{lang.Text(common.Lan, "MonthRate"), true, "month_incratio"},
{lang.Text(common.Lan, "3MonthRate"), true, "quarter_incratio"},
{lang.Text(common.Lan, "6MonthRate"), true, "half_year_incratio"},
{lang.Text(common.Lan, "YearRate"), true, "year_incratio"},
{lang.Text(common.Lan, "ThisYearRate"), true, "this_year_incratio"},
{lang.Text(common.Lan, "3YearRate"), false, ""},
{lang.Text(common.Lan, "SinceCreateRate"), false, ""},
}
}
func formatIncratio(incratio string) string {
value := util.Str2Decimal(incratio)
s := value.Mul(decimal.NewFromInt(100)).StringFixed(2) + "%"
if value.IsPositive() {
return "+" + s
} else {
return s
}
}
func (f SinaFund) GetValues() []string {
var manager string
for _, m := range f.FundManager {
manager += m.Name + ", "
}
manager = strings.TrimRight(manager, ", ")
return []string{
f.FundCode, f.FundName, f.Type2IdDesc, f.FundScale, f.CTime, manager, f.Netvalue, f.TotalNetvalue, f.Navdate,
formatIncratio(f.DayIncratio),
formatIncratio(f.MonthIncratio),
formatIncratio(f.QuarterIncratio),
formatIncratio(f.HalfYearIncratio),
formatIncratio(f.YearIncratio),
formatIncratio(f.ThisYearIncratio),
formatIncratio(f.ThreeYearIncratio),
formatIncratio(f.ToThisDayIncratio),
}
}
type SinaFundRankArg struct {
Tab int `json:"tab"` // [1:在售基金 2:新发基金]
PageSize int `json:"page_size"` // 页大小
PageNo int `json:"page_no"` // 页码
FundCode string `json:"fund_code"` // 基金代码
Type string `json:"type"` // 基金类型 [x2001:混合型 x2002:股票型 x2003:债券型 x2005:货币型 x2006:QDII型]
Company string `json:"company"` // 基金公司 [80000220:南方 80000223:嘉实 80000224:国泰 80000226:博时 80000229:易方达 80053708:汇添富 80055334:华泰博瑞 80280038:前海开源 80329448:中融]
Scale string `json:"scale"` // 规模 [1:0~10亿 2:10~20亿 3:20~50亿 4:50~100亿 5:>100亿]
Status string `json:"status"` // 状态 [0:暂停 1:在售]
S string `json:"s"` // 搜索关键字
Order string `json:"order"` // 排序字段 [fund_scale day_incratio month_incratio quarter_incratio half_year_incratio year_incratio this_year_incratio min_value]
OrderType string `json:"order_type"` // 排序方式 [asc:升序 desc:降序]
Time int64 `json:"_"` // 时间戳
}
func (a *SinaFundRankArg) String() string {
return fmt.Sprintf(
"tab=%v&"+
"page_size=%v&"+
"page_no=%v&"+
"fund_code=%v&"+
"type=%v&"+
"company=%v&"+
"scale=%v&"+
"status=%v&"+
"s=%v&"+
"order=%v&"+
"order_type=%v&"+
"_=%v",
a.Tab,
a.PageSize,
a.PageNo,
a.FundCode,
a.Type,
a.Company,
a.Scale,
a.Status,
a.S,
a.Order,
a.OrderType,
a.Time,
)
}
type SinaFundResult struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Items []SinaFund `json:"items"`
PageSize int `json:"page_size"`
PageNo int `json:"page_no"`
PageTotal string `json:"page_total"`
} `json:"data"`
}
type SinaApi struct {
urlRank string
urlEstimate string
}
func NewSinaApi() *SinaApi {
return &SinaApi{
urlRank: "http://fund.sina.com.cn/fund/api/fundMarketList", // http://fund.sina.com.cn/fund/api/fundMarketList?tab=1&page_size=20&page_no=1&fund_code=&type=&company=&scale=&status=1&s=&order=&order_type=desc&_=1613637482
urlEstimate: "https://hq.sinajs.cn/list=", // https://hq.sinajs.cn/list=fu_008293,fu_000594
}
}
func (api *SinaApi) GetTHReference() []THMeta {
return SinaFund{}.GetMetas()
}
func (api *SinaApi) GetFundRank(arg FundRankArg) (FundList, error) {
var funds FundList
sinaArg := SinaFundRankArg{
Tab: 1,
PageSize: arg.PageNumber,
PageNo: arg.PageIndex,
FundCode: "",
Type: "",
Company: "",
Scale: "",
Status: "1",
S: "",
Order: arg.SortCode,
OrderType: arg.SortType,
Time: time.Now().Unix(),
}
url := api.urlRank + "?" + sinaArg.String()
resp, err := common.Client.Get(url, nil)
if err != nil {
log.Error(err)
return funds, err
}
body := string(resp.Body())
body = strings.ReplaceAll(body, `"fund_manager":"",`, `"fund_manager":[],`)
var result SinaFundResult
err = util.Json.UnmarshalFromString(body, &result)
if err != nil {
log.Error(err)
return funds, err
}
// TODO: Data porting
return funds, nil
}
func (api *SinaApi) GetFundEstimate(fundCode string) (FundEstimate, error) {
var estimate FundEstimate
return estimate, nil
}
|
[
3
] |
package lumberjack
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
"net"
"os"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/elastic/libbeat/common"
"github.com/elastic/libbeat/common/streambuf"
"github.com/elastic/libbeat/outputs"
)
func testEvent() common.MapStr {
return common.MapStr{
"timestamp": common.Time(time.Now()),
"type": "log",
"extra": 10,
"message": "message",
}
}
func testLogstashIndex(test string) string {
return fmt.Sprintf("beat-logstash-int-%v-%d", test, os.Getpid())
}
func newTestLumberjackOutput(
t *testing.T,
test string,
config *outputs.MothershipConfig,
) outputs.BulkOutputer {
if config == nil {
config = &outputs.MothershipConfig{
Enabled: true,
TLS: nil,
Hosts: []string{getLumberjackHost()},
Index: testLogstashIndex(test),
}
}
plugin := outputs.FindOutputPlugin("lumberjack")
if plugin == nil {
t.Fatalf("No lumberjack output plugin found")
}
output, err := plugin.NewOutput("test", config, 0)
if err != nil {
t.Fatalf("init lumberjack output plugin failed: %v", err)
}
return output.(outputs.BulkOutputer)
}
func sockReadMessage(buf *streambuf.Buffer, in io.Reader) (*message, error) {
for {
// try parse message from buffered data
msg, err := readMessage(buf)
if msg != nil || (err != nil && err != streambuf.ErrNoMoreBytes) {
return msg, err
}
// read next bytes from socket if incomplete message in buffer
buffer := make([]byte, 1024)
n, err := in.Read(buffer)
if err != nil {
return nil, err
}
buf.Write(buffer[:n])
}
}
func sockSendACK(out io.Writer, seq uint32) error {
buf := streambuf.New(nil)
buf.WriteByte('1')
buf.WriteByte('A')
buf.WriteNetUint32(seq)
_, err := out.Write(buf.Bytes())
return err
}
// genCertsIfMIssing generates a testing certificate for ip 127.0.0.1 for
// testing if certificate or key is missing. Generated is used for CA,
// client-auth and server-auth. Use only for testing.
func genCertsIfMIssing(
t *testing.T,
capem string,
cakey string,
) error {
_, err := os.Stat(capem)
if err == nil {
_, err = os.Stat(cakey)
if err == nil {
return nil
}
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
t.Fatalf("failed to generate serial number: %s", err)
}
caTemplate := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Country: []string{"US"},
Organization: []string{"elastic"},
OrganizationalUnit: []string{"beats"},
},
Issuer: pkix.Name{
Country: []string{"US"},
Organization: []string{"elastic"},
OrganizationalUnit: []string{"beats"},
Locality: []string{"locality"},
Province: []string{"province"},
StreetAddress: []string{"Mainstreet"},
PostalCode: []string{"12345"},
SerialNumber: "23",
CommonName: "*",
},
IPAddresses: []net.IP{
net.IP{127, 0, 0, 1},
},
SignatureAlgorithm: x509.SHA512WithRSA,
PublicKeyAlgorithm: x509.ECDSA,
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
SubjectKeyId: []byte("12345"),
BasicConstraintsValid: true,
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageKeyEncipherment |
x509.KeyUsageDigitalSignature |
x509.KeyUsageCertSign,
}
// generate keys
priv, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
t.Fatalf("failed to generate ca private key: %v", err)
}
pub := &priv.PublicKey
// generate certificate
caBytes, err := x509.CreateCertificate(
rand.Reader,
&caTemplate,
&caTemplate,
pub, priv)
if err != nil {
t.Fatalf("failed to generate ca certificate: %v", err)
}
// write key file
keyOut, err := os.OpenFile(cakey, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
t.Fatalf("failed to open key file for writing: %v", err)
}
pem.Encode(keyOut, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv)})
keyOut.Close()
// write certificate
certOut, err := os.Create(capem)
if err != nil {
t.Fatalf("failed to open cert.pem for writing: %s", err)
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: caBytes})
certOut.Close()
return nil
}
func TestLumberjackTCP(t *testing.T) {
var serverErr error
var win, data *message
// create server with randomized port
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Failed to create test server")
}
// start server
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// server read timeout
timeout := 5 * time.Second
buf := streambuf.New(nil)
client, err := listener.Accept()
if err != nil {
t.Logf("failed on accept: %v", err)
serverErr = err
return
}
if err := client.SetDeadline(time.Now().Add(timeout)); err != nil {
serverErr = err
return
}
win, err = sockReadMessage(buf, client)
if err != nil {
t.Logf("failed on read window size: %v", err)
serverErr = err
return
}
if err := client.SetDeadline(time.Now().Add(timeout)); err != nil {
serverErr = err
return
}
data, err = sockReadMessage(buf, client)
if err != nil {
t.Logf("failed on read data frame: %v", err)
serverErr = err
return
}
if err := client.SetDeadline(time.Now().Add(timeout)); err != nil {
serverErr = err
return
}
err = sockSendACK(client, 1)
if err != nil {
t.Logf("failed on read data frame: %v", err)
serverErr = err
}
}()
// create lumberjack output client
config := outputs.MothershipConfig{
TLS: nil,
Timeout: 2,
Hosts: []string{listener.Addr().String()},
}
output := newTestLumberjackOutput(t, "", &config)
// send event to server
event := testEvent()
output.PublishEvent(nil, time.Now(), event)
wg.Wait()
listener.Close()
// validate output
assert.Nil(t, serverErr)
assert.NotNil(t, win)
if data == nil {
t.Fatalf("No data received")
}
assert.Equal(t, 1, len(data.events))
data = data.events[0]
assert.Equal(t, 10.0, data.doc["extra"])
assert.Equal(t, "message", data.doc["line"])
}
func TestLumberjackTLS(t *testing.T) {
pem := "ca_test.pem"
key := "ca_test.key"
var serverErr error
var win, data *message
genCertsIfMIssing(t, pem, key)
tcpListener, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("failed to generate TCP listener")
}
// create lumberjack output client
config := outputs.MothershipConfig{
TLS: &outputs.TLSConfig{
Certificate: pem,
CertificateKey: key,
CAs: []string{pem},
},
Timeout: 5,
Hosts: []string{tcpListener.Addr().String()},
}
tlsConfig, err := outputs.LoadTLSConfig(config.TLS)
if err != nil {
tcpListener.Close()
t.Fatalf("failed to load certificates")
}
listener := tls.NewListener(tcpListener, tlsConfig)
// start server
var wg sync.WaitGroup
var wgReady sync.WaitGroup
wg.Add(1)
wgReady.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 3; i++ { // try up to 3 failed connection attempts
// server read timeout
timeout := 5 * time.Second
buf := streambuf.New(nil)
wgReady.Done()
client, err := listener.Accept()
if err != nil {
continue
}
tlsConn, ok := client.(*tls.Conn)
if !ok {
serverErr = errors.New("no tls connection")
return
}
if err := client.SetDeadline(time.Now().Add(timeout)); err != nil {
serverErr = err
return
}
err = tlsConn.Handshake()
if err != nil {
serverErr = err
return
}
if err := client.SetDeadline(time.Now().Add(timeout)); err != nil {
serverErr = err
return
}
win, err = sockReadMessage(buf, client)
if err != nil {
serverErr = err
return
}
if err := client.SetDeadline(time.Now().Add(timeout)); err != nil {
serverErr = err
return
}
data, err = sockReadMessage(buf, client)
if err != nil {
serverErr = err
return
}
serverErr = sockSendACK(client, 1)
return
}
}()
// send event to server
go func() {
wgReady.Wait()
output := newTestLumberjackOutput(t, "", &config)
event := testEvent()
output.PublishEvent(nil, time.Now(), event)
}()
wg.Wait()
listener.Close()
// validate output
assert.Nil(t, serverErr)
assert.NotNil(t, win)
assert.NotNil(t, data)
if data != nil {
assert.Equal(t, 1, len(data.events))
data = data.events[0]
assert.Equal(t, 10.0, data.doc["extra"])
assert.Equal(t, "message", data.doc["line"])
}
}
|
[
6
] |
/*
Copyright 2012 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package shlex
/*
Package shlex implements a simple lexer which splits input in to tokens using
shell-style rules for quoting and commenting.
*/
import (
"bufio"
"errors"
"fmt"
"io"
"strings"
)
/*
A TokenType is a top-level token; a word, space, comment, unknown.
*/
type TokenType int
/*
A RuneTokenType is the type of a UTF-8 character; a character, quote, space, escape.
*/
type RuneTokenType int
type lexerState int
type Token struct {
tokenType TokenType
value string
}
/*
Two tokens are equal if both their types and values are equal. A nil token can
never equal another token.
*/
func (a *Token) Equal(b *Token) bool {
if a == nil || b == nil {
return false
}
if a.tokenType != b.tokenType {
return false
}
return a.value == b.value
}
const (
RUNE_CHAR string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-,/@$*()+=><:;&^%~|!?[]{}"
RUNE_SPACE string = " \t\r\n"
RUNE_ESCAPING_QUOTE string = "\""
RUNE_NONESCAPING_QUOTE string = "'"
RUNE_ESCAPE = "\\"
RUNE_COMMENT = "#"
RUNETOKEN_UNKNOWN RuneTokenType = 0
RUNETOKEN_CHAR RuneTokenType = 1
RUNETOKEN_SPACE RuneTokenType = 2
RUNETOKEN_ESCAPING_QUOTE RuneTokenType = 3
RUNETOKEN_NONESCAPING_QUOTE RuneTokenType = 4
RUNETOKEN_ESCAPE RuneTokenType = 5
RUNETOKEN_COMMENT RuneTokenType = 6
RUNETOKEN_EOF RuneTokenType = 7
TOKEN_UNKNOWN TokenType = 0
TOKEN_WORD TokenType = 1
TOKEN_SPACE TokenType = 2
TOKEN_COMMENT TokenType = 3
STATE_START lexerState = 0
STATE_INWORD lexerState = 1
STATE_ESCAPING lexerState = 2
STATE_ESCAPING_QUOTED lexerState = 3
STATE_QUOTED_ESCAPING lexerState = 4
STATE_QUOTED lexerState = 5
STATE_COMMENT lexerState = 6
INITIAL_TOKEN_CAPACITY int = 100
)
/*
A type for classifying characters. This allows for different sorts of
classifiers - those accepting extended non-ascii chars, or strict posix
compatibility, for example.
*/
type TokenClassifier struct {
typeMap map[int32]RuneTokenType
}
func addRuneClass(typeMap *map[int32]RuneTokenType, runes string, tokenType RuneTokenType) {
for _, rune := range runes {
(*typeMap)[int32(rune)] = tokenType
}
}
/*
Create a new classifier for basic ASCII characters.
*/
func NewDefaultClassifier() *TokenClassifier {
typeMap := map[int32]RuneTokenType{}
addRuneClass(&typeMap, RUNE_CHAR, RUNETOKEN_CHAR)
addRuneClass(&typeMap, RUNE_SPACE, RUNETOKEN_SPACE)
addRuneClass(&typeMap, RUNE_ESCAPING_QUOTE, RUNETOKEN_ESCAPING_QUOTE)
addRuneClass(&typeMap, RUNE_NONESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE)
addRuneClass(&typeMap, RUNE_ESCAPE, RUNETOKEN_ESCAPE)
addRuneClass(&typeMap, RUNE_COMMENT, RUNETOKEN_COMMENT)
return &TokenClassifier{
typeMap: typeMap}
}
func (classifier *TokenClassifier) ClassifyRune(rune int32) RuneTokenType {
return classifier.typeMap[rune]
}
/*
A type for turning an input stream in to a sequence of strings. Whitespace and
comments are skipped.
*/
type Lexer struct {
tokenizer *Tokenizer
}
/*
Create a new lexer.
*/
func NewLexer(r io.Reader) (*Lexer, error) {
tokenizer, err := NewTokenizer(r)
if err != nil {
return nil, err
}
lexer := &Lexer{tokenizer: tokenizer}
return lexer, nil
}
/*
Return the next word, and an error value. If there are no more words, the error
will be io.EOF.
*/
func (l *Lexer) NextWord() (string, error) {
var token *Token
var err error
for {
token, err = l.tokenizer.NextToken()
if err != nil {
return "", err
}
switch token.tokenType {
case TOKEN_WORD:
{
return token.value, nil
}
case TOKEN_COMMENT:
{
// skip comments
}
default:
{
panic(fmt.Sprintf("Unknown token type: %v", token.tokenType))
}
}
}
return "", io.EOF
}
/*
A type for turning an input stream in to a sequence of typed tokens.
*/
type Tokenizer struct {
input *bufio.Reader
classifier *TokenClassifier
}
/*
Create a new tokenizer.
*/
func NewTokenizer(r io.Reader) (*Tokenizer, error) {
input := bufio.NewReader(r)
classifier := NewDefaultClassifier()
tokenizer := &Tokenizer{
input: input,
classifier: classifier}
return tokenizer, nil
}
/*
Scan the stream for the next token.
This uses an internal state machine. It will panic if it encounters a character
which it does not know how to handle.
*/
func (t *Tokenizer) scanStream() (*Token, error) {
state := STATE_START
var tokenType TokenType
value := make([]int32, 0, INITIAL_TOKEN_CAPACITY)
var (
nextRune int32
nextRuneType RuneTokenType
err error
)
SCAN:
for {
nextRune, _, err = t.input.ReadRune()
nextRuneType = t.classifier.ClassifyRune(nextRune)
if err != nil {
if err == io.EOF {
nextRuneType = RUNETOKEN_EOF
err = nil
} else {
return nil, err
}
}
switch state {
case STATE_START: // no runes read yet
{
switch nextRuneType {
case RUNETOKEN_EOF:
{
return nil, io.EOF
}
case RUNETOKEN_CHAR:
{
tokenType = TOKEN_WORD
value = append(value, nextRune)
state = STATE_INWORD
}
case RUNETOKEN_SPACE:
{
}
case RUNETOKEN_ESCAPING_QUOTE:
{
tokenType = TOKEN_WORD
state = STATE_QUOTED_ESCAPING
}
case RUNETOKEN_NONESCAPING_QUOTE:
{
tokenType = TOKEN_WORD
state = STATE_QUOTED
}
case RUNETOKEN_ESCAPE:
{
tokenType = TOKEN_WORD
state = STATE_ESCAPING
}
case RUNETOKEN_COMMENT:
{
tokenType = TOKEN_COMMENT
state = STATE_COMMENT
}
default:
{
return nil, errors.New(fmt.Sprintf("Unknown rune: %v", nextRune))
}
}
}
case STATE_INWORD: // in a regular word
{
switch nextRuneType {
case RUNETOKEN_EOF:
{
break SCAN
}
case RUNETOKEN_CHAR, RUNETOKEN_COMMENT:
{
value = append(value, nextRune)
}
case RUNETOKEN_SPACE:
{
t.input.UnreadRune()
break SCAN
}
case RUNETOKEN_ESCAPING_QUOTE:
{
state = STATE_QUOTED_ESCAPING
}
case RUNETOKEN_NONESCAPING_QUOTE:
{
state = STATE_QUOTED
}
case RUNETOKEN_ESCAPE:
{
state = STATE_ESCAPING
}
default:
{
return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune))
}
}
}
case STATE_ESCAPING: // the next rune after an escape character
{
switch nextRuneType {
case RUNETOKEN_EOF:
{
err = errors.New("EOF found after escape character")
break SCAN
}
case RUNETOKEN_CHAR, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT:
{
state = STATE_INWORD
value = append(value, nextRune)
}
default:
{
return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune))
}
}
}
case STATE_ESCAPING_QUOTED: // the next rune after an escape character, in double quotes
{
switch nextRuneType {
case RUNETOKEN_EOF:
{
err = errors.New("EOF found after escape character")
break SCAN
}
case RUNETOKEN_CHAR, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT:
{
state = STATE_QUOTED_ESCAPING
value = append(value, nextRune)
}
default:
{
return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune))
}
}
}
case STATE_QUOTED_ESCAPING: // in escaping double quotes
{
switch nextRuneType {
case RUNETOKEN_EOF:
{
err = errors.New("EOF found when expecting closing quote.")
break SCAN
}
case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_SPACE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_COMMENT:
{
value = append(value, nextRune)
}
case RUNETOKEN_ESCAPING_QUOTE:
{
state = STATE_INWORD
}
case RUNETOKEN_ESCAPE:
{
state = STATE_ESCAPING_QUOTED
}
default:
{
return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune))
}
}
}
case STATE_QUOTED: // in non-escaping single quotes
{
switch nextRuneType {
case RUNETOKEN_EOF:
{
err = errors.New("EOF found when expecting closing quote.")
break SCAN
}
case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT:
{
value = append(value, nextRune)
}
case RUNETOKEN_NONESCAPING_QUOTE:
{
state = STATE_INWORD
}
default:
{
return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune))
}
}
}
case STATE_COMMENT:
{
switch nextRuneType {
case RUNETOKEN_EOF:
{
break SCAN
}
case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT, RUNETOKEN_NONESCAPING_QUOTE:
{
value = append(value, nextRune)
}
case RUNETOKEN_SPACE:
{
if nextRune == '\n' {
state = STATE_START
break SCAN
} else {
value = append(value, nextRune)
}
}
default:
{
return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune))
}
}
}
default:
{
panic(fmt.Sprintf("Unexpected state: %v", state))
}
}
}
token := &Token{
tokenType: tokenType,
value: string(value)}
return token, err
}
/*
Return the next token in the stream, and an error value. If there are no more
tokens available, the error value will be io.EOF.
*/
func (t *Tokenizer) NextToken() (*Token, error) {
return t.scanStream()
}
/*
Split a string in to a slice of strings, based upon shell-style rules for
quoting, escaping, and spaces.
*/
func Split(s string) ([]string, error) {
l, err := NewLexer(strings.NewReader(s))
if err != nil {
return nil, err
}
subStrings := []string{}
for {
word, err := l.NextWord()
if err != nil {
if err == io.EOF {
return subStrings, nil
}
return subStrings, err
}
subStrings = append(subStrings, word)
}
return subStrings, nil
}
|
[
1
] |
package handlers
import (
"crypto/md5"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/jitsucom/jitsu/server/appconfig"
"github.com/jitsucom/jitsu/server/appstatus"
"github.com/jitsucom/jitsu/server/caching"
"github.com/jitsucom/jitsu/server/events"
"github.com/jitsucom/jitsu/server/geo"
"github.com/jitsucom/jitsu/server/logging"
"github.com/jitsucom/jitsu/server/middleware"
"github.com/jitsucom/jitsu/server/multiplexing"
"github.com/jitsucom/jitsu/server/timestamp"
"github.com/jitsucom/jitsu/server/wal"
"net/http"
"strconv"
"strings"
"time"
)
const (
defaultLimit = 100
noDestinationsErrTemplate = "No destination is configured for token [%q] (or only staged ones)"
)
//EventResponse is a dto for sending operation status and delete_cookie flag
type EventResponse struct {
Status string `json:"status"`
DeleteCookie bool `json:"delete_cookie,omitempty"`
}
//CachedEvent is a dto for events cache
type CachedEvent struct {
Original json.RawMessage `json:"original,omitempty"`
Success json.RawMessage `json:"success,omitempty"`
Error string `json:"error,omitempty"`
}
//CachedEventsResponse dto for events cache response
type CachedEventsResponse struct {
TotalEvents int `json:"total_events"`
ResponseEvents int `json:"response_events"`
Events []CachedEvent `json:"events"`
}
//EventHandler accepts all events
type EventHandler struct {
writeAheadLogService *wal.Service
multiplexingService *multiplexing.Service
eventsCache *caching.EventsCache
parser events.Parser
processor events.Processor
}
//NewEventHandler returns configured EventHandler
func NewEventHandler(writeAheadLogService *wal.Service, multiplexingService *multiplexing.Service,
eventsCache *caching.EventsCache, parser events.Parser, processor events.Processor) (eventHandler *EventHandler) {
return &EventHandler{
writeAheadLogService: writeAheadLogService,
multiplexingService: multiplexingService,
eventsCache: eventsCache,
parser: parser,
processor: processor,
}
}
//PostHandler accepts all events according to token
func (eh *EventHandler) PostHandler(c *gin.Context) {
eventsArray, err := eh.parser.ParseEventsBody(c)
if err != nil {
msg := fmt.Sprintf("Error parsing events body: %v", err)
c.JSON(http.StatusBadRequest, middleware.ErrResponse(msg, nil))
return
}
iface, ok := c.Get(middleware.TokenName)
if !ok {
logging.SystemError("Token wasn't found in the context")
return
}
token := iface.(string)
reqContext := getRequestContext(c)
//put all events to write-ahead-log if idle
if appstatus.Instance.Idle.Load() {
eh.writeAheadLogService.Consume(eventsArray, reqContext, token, eh.processor.Type())
c.JSON(http.StatusOK, middleware.OKResponse())
return
}
err = eh.multiplexingService.AcceptRequest(eh.processor, reqContext, token, eventsArray)
if err != nil {
code := http.StatusBadRequest
if err == multiplexing.ErrNoDestinations {
code = http.StatusUnprocessableEntity
err = fmt.Errorf(noDestinationsErrTemplate, token)
}
reqBody, _ := json.Marshal(eventsArray)
logging.Warnf("%v. Event: %s", err, string(reqBody))
c.JSON(code, middleware.ErrResponse(err.Error(), nil))
return
}
c.JSON(http.StatusOK, EventResponse{Status: "ok", DeleteCookie: !reqContext.CookiesLawCompliant})
}
//GetHandler returns cached events by destination_ids
func (eh *EventHandler) GetHandler(c *gin.Context) {
var err error
destinationIDs, ok := c.GetQuery("destination_ids")
if !ok {
c.JSON(http.StatusBadRequest, middleware.ErrResponse("destination_ids is required parameter", nil))
return
}
if destinationIDs == "" {
c.JSON(http.StatusOK, CachedEventsResponse{Events: []CachedEvent{}})
return
}
start := time.Time{}
startStr := c.Query("start")
if startStr != "" {
start, err = time.Parse(time.RFC3339Nano, startStr)
if err != nil {
logging.Errorf("Error parsing start query param [%s] in events cache handler: %v", startStr, err)
c.JSON(http.StatusBadRequest, middleware.ErrResponse("Error parsing start query parameter. Accepted datetime format: "+timestamp.Layout, err))
return
}
}
end := time.Now().UTC()
endStr := c.Query("end")
if endStr != "" {
end, err = time.Parse(time.RFC3339Nano, endStr)
if err != nil {
logging.Errorf("Error parsing end query param [%s] in events cache handler: %v", endStr, err)
c.JSON(http.StatusBadRequest, middleware.ErrResponse("Error parsing end query parameter. Accepted datetime format: "+timestamp.Layout, err))
return
}
}
limitStr := c.Query("limit")
var limit int
if limitStr == "" {
limit = defaultLimit
} else {
limit, err = strconv.Atoi(limitStr)
if err != nil {
logging.Errorf("Error parsing limit [%s] to int in events cache handler: %v", limitStr, err)
c.JSON(http.StatusBadRequest, middleware.ErrResponse("limit must be int", nil))
return
}
}
response := CachedEventsResponse{Events: []CachedEvent{}}
for _, destinationID := range strings.Split(destinationIDs, ",") {
eventsArray := eh.eventsCache.GetN(destinationID, start, end, limit)
for _, event := range eventsArray {
response.Events = append(response.Events, CachedEvent{
Original: []byte(event.Original),
Success: []byte(event.Success),
Error: event.Error,
})
}
response.ResponseEvents += len(eventsArray)
response.TotalEvents += eh.eventsCache.GetTotal(destinationID)
}
c.JSON(http.StatusOK, response)
}
//extractIP returns client IP address parsed from HTTP request (headers, remoteAddr)
func extractIP(c *gin.Context) string {
ip := c.Request.Header.Get("X-Real-IP")
if ip == "" {
ip = c.Request.Header.Get("X-Forwarded-For")
}
if ip == "" {
remoteAddr := c.Request.RemoteAddr
if remoteAddr != "" {
addrPort := strings.Split(remoteAddr, ":")
ip = addrPort[0]
}
}
//Case when Nginx concatenate remote_addr to client addr
if strings.Contains(ip, ",") {
addresses := strings.Split(ip, ",")
return strings.TrimSpace(addresses[0])
}
return ip
}
func getRequestContext(c *gin.Context) *events.RequestContext {
clientIP := extractIP(c)
var compliant *bool
cookiesLawCompliant := true
//cookies
cookiePolicy := c.Query(middleware.CookiePolicyParameter)
if cookiePolicy != "" {
switch cookiePolicy {
case middleware.ComplyValue:
value := complyWithCookieLaws(clientIP)
compliant = &value
cookiesLawCompliant = value
case middleware.KeepValue:
cookiesLawCompliant = true
case middleware.StrictValue:
cookiesLawCompliant = false
default:
logging.SystemErrorf("Unknown value %q for %q query parameter", middleware.CookiePolicyParameter, cookiePolicy)
}
}
hashedAnonymousID := fmt.Sprintf("%x", md5.Sum([]byte(clientIP + c.Request.UserAgent())))
var jitsuAnonymousID string
if !cookiesLawCompliant {
//cookie less
jitsuAnonymousID = hashedAnonymousID
}
//ip address
ipPolicy := c.Query(middleware.IPPolicyParameter)
if ipPolicy != "" {
switch ipPolicy {
case middleware.ComplyValue:
if compliant == nil {
value := complyWithCookieLaws(clientIP)
compliant = &value
}
if !*compliant {
clientIP = getThreeOctets(clientIP)
}
case middleware.KeepValue:
case middleware.StrictValue:
clientIP = getThreeOctets(clientIP)
default:
logging.SystemErrorf("Unknown value %q for %q query parameter", middleware.IPPolicyParameter, ipPolicy)
}
}
return &events.RequestContext{
UserAgent: c.Request.UserAgent(),
ClientIP: clientIP,
Referer: c.Request.Referer(),
JitsuAnonymousID: jitsuAnonymousID,
HashedAnonymousID: hashedAnonymousID,
CookiesLawCompliant: cookiesLawCompliant,
}
}
func getThreeOctets(ip string) string {
ipParts := strings.Split(ip, ".")
ipParts[len(ipParts)-1] = "1"
return strings.Join(ipParts, ".")
}
//complyWithCookieLaws returns true if geo data has been detected and ip isn't from EU or UK
func complyWithCookieLaws(ip string) bool {
ipThreeOctets := getThreeOctets(ip)
if appconfig.Instance.GeoResolver.Type() != geo.MaxmindType {
return false
}
data, err := appconfig.Instance.GeoResolver.Resolve(ipThreeOctets)
if err != nil {
logging.SystemErrorf("Error resolving IP %q into geo data: %v", ipThreeOctets, err)
return false
}
if _, ok := geo.EUCountries[data.Country]; ok || data.Country == geo.UKCountry {
return false
}
return true
}
|
[
3
] |
package main
import(
"fmt"
)
//uncomment statement(baris) dengan comment menggunakan // (double slash) untuk melakukan percobaan
func main() {
/*PERCOBAAN 1
ini akan mencetak sebuah variable baru bernama "m" dengan tipe data "int" dengan nilai 123
*/
// m:=123
// fmt.Println(m)
/* HASIL :
$ go run test.go
123
*/
/*PERCOBAAN 2
namun jika kita mencoba untuk memasukkan nilai baru kepada variable yang di deklarasikan menggunakan Short Assignment Statement terhadap variable Short Assignment Statement yang sudah kita buat sebelumnya (m), maka akan menghasilkan error
*/
// m:=123
// m:=456
// fmt.Println(m)
/* HASIL :
$ go run test.go
# command-line-arguments
.\test.go:20:3: no new variables on left side of :=
*/
/*PERCOBAAN 3
sekarang bagaimana jika kita mendapatkan dua atau lebih value dari function, dan kita ingin menggunakan variable yang sudah ada, untuk menampuk salah satu nilainya. Mana yang harus kita gunakan? := atau =?
jawabannya adalah := silahkan lihat contoh dibawah
*/
i, k := 3, 4
fmt.Println(i, " ", k)
j, k := 1, 2
fmt.Println(i, " ", k)
fmt.Println(j, " ", k)
/* HASIL
$ go run test.go
3 4
3 2
1 2
Penjelasan
karena vaiable J di baru saja deklarasikan pada saat statement kedua, maka kita boleh menggunakan := kepada j untuk melakukan inisialisasi, meskipun k sudah di definisikan pada statement sebelumnya
*/
}
|
[
3
] |
package calFanShu
import (
"majiang-new/card/cardType"
"majiang-new/common"
"reflect"
)
/*说明:
九莲宝灯:由一种花色序数牌按①①①②③④⑤⑥⑦⑧⑨⑨⑨组成的特定牌型,见同花色任何1张序数牌即成和牌。
不计清一色、门前清、幺九刻,自摸计不求人。因听牌时听同花色所有9种牌而得名。
如不是听九种牌的情况但和牌后牌型符合九莲宝灯牌型的,一般不算九莲宝灯,但有的场合也算(如QQ麻将)。
*/
const (
_HUPAI4_ID = 4
_HUPAI4_NAME = "九莲宝灯"
_HUPAI4_FANSHU = 88
_HUPAI4_KIND = cardType.HUMETHOD_NORMAL
)
var _HUPAI4_CHECKID_ = []int{22, 62, 72, 76} //
func init() {
fanShuMgr.registerHander(&huPai4{
id: _HUPAI4_ID,
name: _HUPAI4_NAME,
fanShu: _HUPAI4_FANSHU,
setChcFanShuID: _HUPAI4_CHECKID_,
huKind: _HUPAI4_KIND,
})
}
type huPai4 struct {
id int
name string
fanShu int
setChcFanShuID []int
huKind int
}
func (h *huPai4) GetID() int {
return h.id
}
func (h *huPai4) Name() string {
return h.name
}
func (h *huPai4) GetFanShu() int {
return h.fanShu
}
func (h *huPai4) Satisfy(method *cardType.HuMethod, satisfyedID []int, slBanID []int) (bool, int, []int, []int) {
if method.GetHuPaiKind() != h.huKind {
return false, 0, satisfyedID, slBanID
}
if common.InIntSlace(satisfyedID, h.GetID()) {
return false, 0, satisfyedID, slBanID
}
//不能计算的直接退出
if common.InIntSlace(slBanID, h.GetID()) {
return false, 0, satisfyedID, slBanID
}
if !h.CheckSatisfySelf(method) {
slBanID = append(slBanID, h.GetID())
return false, 0, satisfyedID, slBanID
}
//满足后把自己自己要ban的id加入进去
for _, id := range h.setChcFanShuID {
if !common.InIntSlace(slBanID, id) {
slBanID = append(slBanID, id)
}
}
fanShu := h.GetFanShu()
satisfyedID = append(satisfyedID, h.GetID())
//再把其他的所有的id全部遍历,有就加上去
otherChkHander := fanShuMgr.getHanderExcept(append(satisfyedID, slBanID...))
for _, hander := range otherChkHander {
ok, tmpFanShu, tmpSatisfyID, slTmpBanID := hander.Satisfy(method, satisfyedID, slBanID)
slBanID = slTmpBanID
if ok {
fanShu += tmpFanShu
satisfyedID = tmpSatisfyID
}
}
return true, fanShu, satisfyedID, slBanID
}
func (h *huPai4) CheckSatisfySelf(method *cardType.HuMethod) bool {
allCard := method.GetHandCard()
allKind := allCard.GetAllKind()
//花色第一个都是1
if allKind[0]%10 != 1 {
return false
}
var slNeedKind []uint8
for i := uint8(1); i < 10; i++ {
if i == 1 || i == 9 {
slNeedKind = append(slNeedKind, []uint8{i, i, i}...)
continue
}
slNeedKind = append(slNeedKind, i)
}
var slChk []uint8
for _, card := range allCard {
if cardType.IsFengCard(card) {
return false
}
slChk = append(slChk, card%10)
}
return reflect.DeepEqual(slChk, slNeedKind)
}
|
[
3,
6
] |
package json_structs
//type Rooms struct {
// Link string `json:"link"`
// Name string `json:"name"`
// Desc string `json:"desc"`
//}
type Users struct {
Username string `json:"username"`
}
type Payment struct {
Type string `json:"type"` // UserPayments || EventPayment
HisPend string `json:"HisPend"` // History || Pending
Data PaymentData `json:"data"`
}
type PaymentData struct {
ID string `json:"id"`
paymentNum int
Title string `json:"title"`
Value float64 `json:"ammount"`
Created string `json:"created"`
Accepted []string `json:"accepted"`
Waiting []string `json:"waiting"`
AllUsersAccepted bool `json:"all_users_accepted"`
FromUsername string `json:"from_username"`
ToUsername string `json:"to_username"`
Ammounts map[string]float64 `json:"ammounts"`
}
const (
USER_PAYMENT = "UserPayment"
EVENT_PAYMENT = "EventPayment"
HISTORY = "History"
PENDING = "Pending"
)
|
[
3
] |
// 反转链表 II
// medium
/*
* 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
*
* 说明:
* 1 ≤ m ≤ n ≤ 链表长度。
*
* 示例:
*
* 输入: 1->2->3->4->5->NULL, m = 2, n = 4
* 输出: 1->4->3->2->5->NULL
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* ---------------------------------------------------------
* 题解:
* 和整个链表翻转没区别,记好 p、q、t 仨指针的转移过程就好。
* 因为是部分翻转,所以需要一个头指针记录下起点,剩下的就是链表翻转了。注意判好起点终点完事。
*
*/
package main
func main() {
}
type ListNode struct {
Val int
Next *ListNode
}
func reverseBetween(head *ListNode, left int, right int) *ListNode {
if right-left == 0 {
return head
}
hair := &ListNode{0, head}
hair2 := hair
cnt := 1
var p, q, t *ListNode
for cnt < left {
hair2 = head
head = head.Next
cnt++
}
p = head
q = p.Next
if q != nil {
t = q.Next
}
head.Next = nil
for cnt < right {
q.Next = p
p = q
q = t
if t != nil {
t = t.Next
}
cnt++
}
hair2.Next = p
head.Next = q
return hair.Next
}
|
[
6
] |
package reservoir
import (
"fmt"
"math"
"strconv"
"sync/atomic"
"time"
"github.com/DataDog/datadog-trace-agent/model"
"github.com/DataDog/datadog-trace-agent/sampler"
"github.com/DataDog/datadog-trace-agent/statsd"
)
type Sampler struct {
stratReservoir *StratifiedReservoir
flusher *Flusher
minFPS float64
first time.Time
}
func NewSampler(minFPS float64, maxFPS float64) *Sampler {
flusher := NewFlusher(maxFPS-minFPS, 30*time.Second, int(math.Round(minFPS)))
stratReservoir := NewStratifiedReservoir()
return &Sampler{
minFPS: minFPS,
stratReservoir: stratReservoir,
flusher: flusher,
}
}
func (s *Sampler) Start(decisionCb func(t *model.ProcessedTrace, sampled bool)) {
s.flusher.Start(s.stratReservoir, func(t *model.ProcessedTrace) { decisionCb(t, true) })
s.stratReservoir.Init(s.flusher, func(t *model.ProcessedTrace) { decisionCb(t, false) })
go s.reportStats()
}
func (s *Sampler) Sample(t *model.ProcessedTrace) {
s.stratReservoir.Add(sig(t), t)
newTraceTime := time.Unix(0, t.Root.Start+t.Root.Duration)
if s.first.IsZero() {
s.first = newTraceTime
}
fmt.Println("%%% " + strconv.FormatInt(newTraceTime.Sub(s.first).Nanoseconds(), 10) + " " + t.Root.Resource[3:])
oldestTraceInSampler := s.stratReservoir.GetLatestTime()
isReset := newTraceTime.Sub(oldestTraceInSampler) < 0
isEnoughTimePassed := newTraceTime.Sub(oldestTraceInSampler) >= time.Duration(1./s.minFPS)*time.Second
if isReset || isEnoughTimePassed {
s.flusher.TicketFlush()
}
}
func (s *Sampler) Stop() {
s.flusher.Stop()
}
func sig(t *model.ProcessedTrace) sampler.Signature {
return sampler.ComputeSignatureWithRootAndEnv(t.Trace, t.Root, t.Env)
}
func (s *Sampler) reportStats() {
flushTicker := time.NewTicker(15 * time.Second)
defer flushTicker.Stop()
for range flushTicker.C {
s.stratReservoir.RLock()
signatureCard := len(s.stratReservoir.reservoirs)
s.stratReservoir.RUnlock()
reservoirSize := atomic.LoadUint64(&s.stratReservoir.size)
statsd.Client.Count("datadog.trace_agent.reservoir.memory_size", int64(reservoirSize), nil, 1)
statsd.Client.Count("datadog.trace_agent.reservoir.signature_cardinality", int64(signatureCard), nil, 1)
if s.stratReservoir.isFull() {
statsd.Client.Count("datadog.trace_agent.reservoir.full", int64(1), nil, 1)
}
}
}
|
[
6
] |
package goroutine_channel
/*
多线程运行速度明显比单线程快,测试对比结果:
=== RUN TestSerial
sum = 7999999998000000000, spend time: 1.7382813s --- PASS: TestSerial (1.74s)
=== RUN TestParallel
sum = 7999999998000000000, spend time: 1.1835937s--- PASS: TestParallel (1.18s)
PASS
ok _/D_/Do/GitCode/GoLearn/goroutine-channel 2.979s
*/
import (
"fmt"
"time"
)
// 单线程
func serial() {
sum, count, start := 0, 0, time.Now()
for count < 4e9 {
sum += count
count += 1
}
end := time.Now()
fmt.Printf("sum = %d, spend time: %s ", sum, end.Sub(start))
}
//多线程性能明显提升
func parallel() {
sum, count, start, ch := 0, 0, time.Now(), make(chan int, 4)
for count < 4 {
go func(count int) {
value := 0
for i := count * 1e9; i < (count+1)*1e9; i++ {
value += i
}
ch <- value
}(count)
count++
}
for count > 0 {
sum += <-ch
count--
}
end := time.Now()
fmt.Printf("sum = %d, spend time: %s", sum, end.Sub(start))
}
/********************** channel阻塞情况,及其解决方法 *********************/
// 阻塞死锁的情况
// 这里的运行结果会报错:fatal error: all goroutines are asleep - deadlock!
func dealLock() {
ch := make(chan int)
ch <- 1
val := <-ch
fmt.Println(val)
}
// 这里的运行结果为:1 不会报错,通过初试化channel时,让channel容量大于0,是异步非阻塞,解决了死锁问题
func chWithCap() {
ch := make(chan int, 1)
ch <- 1
val := <-ch
fmt.Println(val)
}
/*
首先,管道的容量依然为0;但是,通过go关键字来创建一个协程,这这个单独的协程中就可以做好准备,
向管道中写入这个值,并且也不会阻塞主线程;在主线程中,消费者做好准备从管道中读取值;
在某个时刻,生产者和消费者都准备好了,进行通信,这就不会导致死锁了。
*/
func chWithRoutine() {
ch := make(chan int)
go func() {
ch <- 1
}()
val := <-ch
fmt.Println(val)
}
/********************** channel方向,close, for *********************/
/*
1、sender函数中,持续地往管道中写入int类型的消息,并且在i为5的时候调用close手动关闭了管道,并且跳出了循环。
这里需要注意的是,不能再向已经关闭的管道中写入值,因此如果没有上面的break,会触发panic
2、receiver函数中,使用for-range的形式从管道中读取值,在管道被关闭之后,会自动的结束循环
3、同时,我们还注意到,sender函数的形参类型是 chan<- int,receiver函数的形参类型是 <-chan int,
这代表着管道是单向的,分别只能向管道中写入消息、读取消息
*/
func sendToCh(ch chan<- int) {
for i := 0; i < 10; i++ {
ch <- i
if i == 5 {
close(ch)
break
}
}
}
func receiveCh(ch <-chan int) {
for val := range ch {
fmt.Println(val)
}
}
func chMain() {
ch := make(chan int)
go sendToCh(ch)
receiveCh(ch)
}
|
[
3
] |
package ssh
import (
"bytes"
"fmt"
"github.com/pkg/errors"
"github.com/viant/toolbox/cred"
"github.com/viant/toolbox/storage"
"golang.org/x/crypto/ssh"
"io"
"net"
"os"
"path"
"strings"
"sync"
"time"
)
type (
//Service represents ssh service
Service interface {
//Service returns a service wrapper
Client() *ssh.Client
//OpenMultiCommandSession opens multi command session
OpenMultiCommandSession(config *SessionConfig) (MultiCommandSession, error)
//Run runs supplied command
Run(command string) error
//Upload uploads provided content to specified destination
//Deprecated: please consider using https://github.com/viant/afs/tree/master/scp
Upload(destination string, mode os.FileMode, content []byte) error
//Download downloads content from specified source.
//Deprecated: please consider using https://github.com/viant/afs/tree/master/scp
Download(source string) ([]byte, error)
//OpenTunnel opens a tunnel between local to remote for network traffic.
OpenTunnel(localAddress, remoteAddress string) error
NewSession() (*ssh.Session, error)
Close() error
}
)
//service represnt SSH service
type service struct {
host string
client *ssh.Client
forwarding []*Tunnel
replayCommands *ReplayCommands
recordSession bool
config *ssh.ClientConfig
}
//Service returns undelying ssh Service
func (c *service) Client() *ssh.Client {
return c.client
}
//Service returns undelying ssh Service
func (c *service) NewSession() (*ssh.Session, error) {
return c.client.NewSession()
}
//MultiCommandSession create a new MultiCommandSession
func (c *service) OpenMultiCommandSession(config *SessionConfig) (MultiCommandSession, error) {
return newMultiCommandSession(c, config, c.replayCommands, c.recordSession)
}
func (c *service) Run(command string) error {
session, err := c.client.NewSession()
if err != nil {
panic("failed to create session: " + err.Error())
}
defer session.Close()
return session.Run(command)
}
func (c *service) transferData(payload []byte, createFileCmd string, writer io.Writer, errors chan error, waitGroup *sync.WaitGroup) {
const endSequence = "\x00"
defer waitGroup.Done()
_, err := fmt.Fprint(writer, createFileCmd)
if err != nil {
errors <- err
return
}
_, err = io.Copy(writer, bytes.NewReader(payload))
if err != nil {
errors <- err
return
}
if _, err = fmt.Fprint(writer, endSequence); err != nil {
errors <- err
return
}
}
type Errors chan error
func (e Errors) GetError() error {
select {
case err := <-e:
return err
case <-time.After(time.Millisecond):
}
return nil
}
const operationSuccessful = 0
func checkOutput(reader io.Reader, errorChannel Errors) {
writer := new(bytes.Buffer)
io.Copy(writer, reader)
if writer.Len() > 1 {
data := writer.Bytes()
if data[1] == operationSuccessful {
return
} else if len(data) > 2 {
errorChannel <- errors.New(string(data[2:]))
}
}
}
//Upload uploads passed in content into remote destination
func (c *service) Upload(destination string, mode os.FileMode, content []byte) (err error) {
err = c.upload(destination, mode, content)
if err != nil {
if strings.Contains(err.Error(), "No such file or directory") {
dir, _ := path.Split(destination)
c.Run("mkdir -p " + dir)
return c.upload(destination, mode, content)
} else if strings.Contains(err.Error(), "handshake") || strings.Contains(err.Error(), "connection") {
time.Sleep(500 * time.Millisecond)
fmt.Printf("got error %v\n", err)
c.Reconnect()
return c.upload(destination, mode, content)
}
}
return err
}
func (c *service) getSession() (*ssh.Session, error) {
return c.client.NewSession()
}
//Upload uploads passed in content into remote destination
func (c *service) upload(destination string, mode os.FileMode, content []byte) (err error) {
dir, file := path.Split(destination)
if mode == 0 {
mode = 0644
}
waitGroup := &sync.WaitGroup{}
waitGroup.Add(1)
if strings.HasPrefix(file, "/") {
file = string(file[1:])
}
session, err := c.getSession()
if err != nil {
return err
}
writer, err := session.StdinPipe()
if err != nil {
return errors.Wrap(err, "failed to acquire stdin")
}
defer writer.Close()
var transferError Errors = make(chan error, 1)
defer close(transferError)
var sessionError Errors = make(chan error, 1)
defer close(sessionError)
output, err := session.StdoutPipe()
if err != nil {
return errors.Wrap(err, "failed to acquire stdout")
}
go checkOutput(output, sessionError)
if mode >= 01000 {
mode = storage.DefaultFileMode
}
fileMode := string(fmt.Sprintf("C%04o", mode)[:5])
createFileCmd := fmt.Sprintf("%v %d %s\n", fileMode, len(content), file)
go c.transferData(content, createFileCmd, writer, transferError, waitGroup)
scpCommand := "scp -qtr " + dir
err = session.Start(scpCommand)
if err != nil {
return err
}
waitGroup.Wait()
writerErr := writer.Close()
if err := sessionError.GetError(); err != nil {
return err
}
if err := transferError.GetError(); err != nil {
return err
}
if err = session.Wait(); err != nil {
if err := sessionError.GetError(); err != nil {
return err
}
return err
}
return writerErr
}
//Download download passed source file from remote host.
func (c *service) Download(source string) ([]byte, error) {
session, err := c.client.NewSession()
if err != nil {
return nil, err
}
defer session.Close()
return session.Output(fmt.Sprintf("cat %s", source))
}
//Host returns client host
func (c *service) Host() string {
return c.host
}
//Close closes service
func (c *service) Close() error {
if len(c.forwarding) > 0 {
for _, forwarding := range c.forwarding {
_ = forwarding.Close()
}
}
return c.client.Close()
}
//Reconnect client
func (c *service) Reconnect() error {
return c.connect()
}
//OpenTunnel tunnels data between localAddress and remoteAddress on ssh connection
func (c *service) OpenTunnel(localAddress, remoteAddress string) error {
local, err := net.Listen("tcp", localAddress)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to listen on local: %v", localAddress))
}
var forwarding = NewForwarding(c.client, remoteAddress, local)
if len(c.forwarding) == 0 {
c.forwarding = make([]*Tunnel, 0)
}
c.forwarding = append(c.forwarding, forwarding)
go forwarding.Handle()
return nil
}
func (c *service) connect() (err error) {
if c.client, err = ssh.Dial("tcp", c.host, c.config); err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to dial: %v", c.host))
}
return nil
}
//NewService create a new ssh service, it takes host port and authentication config
func NewService(host string, port int, authConfig *cred.Config) (Service, error) {
if authConfig == nil {
authConfig = &cred.Config{}
}
clientConfig, err := authConfig.ClientConfig()
if err != nil {
return nil, err
}
var result = &service{
host: fmt.Sprintf("%s:%d", host, port),
config: clientConfig,
}
return result, result.connect()
}
|
[
3
] |
package SortSource
/*
@author katholikos [email protected]
@version 10/05/2020 16:39
@since Go1.13.5
*/
func merge(leftArr []int, rightArr []int) []int {
leftIndex:=0 //左边索引
rightIndex:=0 //右边索引
var lastArr []int //最终的数组
for leftIndex<len(leftArr) && rightIndex<len(rightArr){
if leftArr[leftIndex] <rightArr[rightIndex]{
lastArr=append(lastArr,leftArr[leftIndex] )
leftIndex++
}else if leftArr[leftIndex] >rightArr[rightIndex]{
lastArr=append(lastArr,rightArr[rightIndex] )
rightIndex++
} else{
lastArr=append(lastArr,rightArr[rightIndex] )
lastArr=append(lastArr,leftArr[leftIndex])
leftIndex++
rightIndex++
}
}
for leftIndex< len(leftArr){ //把没有结束的归并过来
lastArr=append(lastArr,leftArr[leftIndex] )
leftIndex++
}
for rightIndex<len(rightArr){ //把没有结束的归并过来
lastArr=append(lastArr,rightArr[rightIndex] )
rightIndex++
}
return lastArr
}
func MergeSort(arr []int) []int {
length := len(arr)
if length <= 1 {
return arr
}else if length>1 &&length <5{
return InsertSort(arr)
} else {
mid := length / 2
leftArr:=MergeSort(arr[:mid])
rightArr:=MergeSort(arr[mid:])
return merge(leftArr,rightArr)
}
}
|
[
3,
5,
6
] |
package reversindex
type Files struct {
Name string
Quantity int
}
type Allfiles []Files
func sort1(m map[string]Allfiles, str string) map[string]Allfiles {
for i := range m[str] {
for j := i; j > 0 && m[str][j-1].Quantity < m[str][j].Quantity; j-- {
m[str][j-1], m[str][j] = m[str][j], m[str][j-1]
}
}
return m
}
func ReversIndex(str []string, filesname string, m map[string]Allfiles) map[string]Allfiles {
var data1 Files
data1.Name = filesname
data1.Quantity = 1
for i := range str {
k := 0
if m[str[i]] != nil {
for j := range m[str[i]] {
if m[str[i]][j].Name == filesname {
m[str[i]][j].Quantity++
k++
}
}
if k == 0 {
m[str[i]] = append(m[str[i]], data1)
}
} else {
m[str[i]] = append(m[str[i]], data1)
}
k = 0
m = sort1(m, str[i])
}
return m
}
func Search(words []string, m map[string]Allfiles, m1 Allfiles) Allfiles {
var m11 Files
for i := range words {
l := 0
for j := range m[words[i]] {
for k := range m1 {
if m[words[i]][j].Name == m1[k].Name {
m1[k].Quantity = m1[k].Quantity + m[words[i]][j].Quantity
l++
}
}
if l == 0 {
m11.Name = m[words[i]][j].Name
m11.Quantity = m[words[i]][j].Quantity
m1 = append(m1, m11)
}
l = 0
}
}
return m1
}
|
[
0
] |
package commands
import (
"bytes"
"log"
"time"
"github.com/astroband/astrologer/config"
"github.com/astroband/astrologer/db"
"github.com/astroband/astrologer/es"
)
const ingestRetries = 25
// IngestCommand represents the CLI command which starts the Astrologer ingestion daemon
type IngestCommand struct {
ES es.Adapter
DB db.Adapter
}
// Execute starts ingestion
func (cmd *IngestCommand) Execute() {
current := cmd.getStartLedger()
log.Println("Starting ingest from", current.LedgerSeq)
for {
var b bytes.Buffer
var seq = current.LedgerSeq
txs := cmd.DB.TxHistoryRowForSeq(seq)
fees := cmd.DB.TxFeeHistoryRowsForRows(txs)
err := es.SerializeLedger(*current, txs, fees, &b)
if err != nil {
log.Fatalf("Failed to ingest ledger %d: %v\n", seq, err)
}
//es.NewBulkMaker(*current, txs, fees, &b).Make()
cmd.ES.IndexWithRetries(&b, ingestRetries)
log.Println("Ledger", seq, "ingested.")
current = cmd.DB.LedgerHeaderNext(seq)
for {
if current != nil {
break
}
time.Sleep(1 * time.Second)
current = cmd.DB.LedgerHeaderNext(seq)
}
}
}
func (cmd *IngestCommand) getStartLedger() (h *db.LedgerHeaderRow) {
if *config.StartIngest == 0 {
h = cmd.DB.LedgerHeaderLastRow()
} else {
if *config.StartIngest > 0 {
h = cmd.DB.LedgerHeaderNext(*config.StartIngest)
} else {
last := cmd.DB.LedgerHeaderLastRow()
if last == nil {
log.Fatal("Nothing to ingest")
}
h = cmd.DB.LedgerHeaderNext(last.LedgerSeq + *config.StartIngest)
}
}
if h == nil {
log.Fatal("Nothing to ingest")
}
return h
}
|
[
3
] |
package config
import (
"context"
"log"
"os"
"time"
"app/pkg/controllers"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func getEnvValue(key string) string {
// load .env file
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
return os.Getenv(key)
}
func Connect() {
// Database Config
// Get .Env
dbUser := getEnvValue("DB_USER")
dbPw := getEnvValue("DB_PW")
dbUrl := getEnvValue("DB_URL")
dbName := getEnvValue("DB_NAME")
clientOptions := options.Client().ApplyURI("mongodb+srv://" + dbUser + ":" + dbPw + "@" + dbUrl)
client, err := mongo.NewClient(clientOptions)
//Set up a context required by mongo.Connect
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
//To close the connection at the end
defer cancel()
err = client.Ping(context.Background(), readpref.Primary())
if err != nil {
log.Fatal("Couldn't connect to the database", err)
} else {
log.Println("Connected!")
}
db := client.Database(dbName)
controllers.MessageCollection(db)
return
}
|
[
3
] |
package manager
import (
"github.com/astaxie/beego"
"github.com/cesanta/docker_auth/auth_server/authn"
"github.com/cesanta/docker_auth/auth_server/authz"
"github.com/cesanta/docker_auth/auth_server/server/config"
"github.com/cesanta/docker_auth/auth_server/server/manager/models"
_ "github.com/cesanta/docker_auth/auth_server/server/manager/routers"
)
// 模板工具函数
func add(src int, added int) int {
return src + added
}
//
type MServer struct {
}
// 初始化配置,以及新建服务器
func NewMServer(config *config.Config, authenticators []authn.Authenticator, authorizers []authz.Authorizer) *MServer {
models.InitAuthConfigManager(config, authenticators, authorizers)
return &MServer{}
}
// 代理函数,实际调用beego的运行方法
func (ms *MServer) RunManagerServer() {
beego.SetStaticPath("/img", "img")
beego.SetStaticPath("/css", "css")
beego.SetStaticPath("/js", "js")
beego.AddFuncMap("add", add)
beego.Run()
}
|
[
6
] |
package model
import (
"github.com/jinzhu/gorm"
)
type Item struct {
*Model
// 物品名称
Name string `json:"name"`
// 状态
State string `json:"state"`
Category string `json:"category"`
//类目
CategoryId uint32 `json:"category_id"`
HomeId uint32 `json:"home_id"`
//计量单位
Unit string `json:"unit"`
//消耗速度
ConsumptionSpeed float64 `json:"consumption_speed"`
}
func (model Item) TableName() string {
return "item"
}
func (t Item) Count(db *gorm.DB) (int, error) {
var count int
if t.Name != "" {
db = db.Where("name like '%?%'", t.Name)
}
if t.HomeId != 0 {
db = db.Where("home_id=?", t.HomeId)
}
if t.CategoryId != 0 {
db = db.Where("category_id=?", t.CategoryId)
}
if t.State != "" {
db = db.Where("state = ?", t.State)
}
if err := db.Model(&t).Where("is_del = ?", 0).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func (t Item) List(db *gorm.DB, pageOffset, pageSize int) ([]*Item, error) {
var tags []*Item
var err error
if pageOffset >= 0 && pageSize > 0 {
db = db.Offset(pageOffset).Limit(pageSize)
}
if t.Name != "" {
db = db.Where("name like '%?%'", t.Name)
}
if t.HomeId != 0 {
db = db.Where("home_id=?", t.HomeId)
}
if t.CategoryId != 0 {
db = db.Where("category_id=?", t.CategoryId)
}
if t.State != "" {
db = db.Where("state = ?", t.State)
}
if err = db.Where("is_del = ?", 0).Find(&tags).Error; err != nil {
return nil, err
}
return tags, nil
}
func (t Item) Create(db *gorm.DB) error {
return db.Create(&t).Error
}
func (t Item) Update(db *gorm.DB, values interface{}) error {
return db.Model(&t).Where("id = ? and is_del=?", t.Id, 0).Updates(values).Error
}
func (t Item) Delete(db *gorm.DB) error {
return db.Where("id=? and is_del = ?", t.Id, 0).Delete(&t).Error
}
|
[
3
] |
package driver
//import . "time"
import . "math"
import . "fmt"
//
// Matrices of buttons, lights and sensor to loop through easier
//
var Button_matrix = [N_floors][N_buttons]int{
{BUTTON_UP1,BUTTON_DOWN1,BUTTON_COMMAND1},
{BUTTON_UP2,BUTTON_DOWN2,BUTTON_COMMAND2},
{BUTTON_UP3,BUTTON_DOWN3,BUTTON_COMMAND3},
{BUTTON_UP4,BUTTON_DOWN4,BUTTON_COMMAND4},
}
var Light_matrix = [N_floors][N_buttons]int{
{LIGHT_UP1,LIGHT_DOWN1,LIGHT_COMMAND1},
{LIGHT_UP2,LIGHT_DOWN2,LIGHT_COMMAND2},
{LIGHT_UP3,LIGHT_DOWN3,LIGHT_COMMAND3},
{LIGHT_UP4,LIGHT_DOWN4,LIGHT_COMMAND4},
}
var button=[N_floors][N_buttons]int{
{0,0,0},
{0,0,0},
{0,0,0},
{0,0,0},
}
var Sensors = [N_floors]int{SENSOR_FLOOR1,SENSOR_FLOOR2,SENSOR_FLOOR3,SENSOR_FLOOR4}
//
// Functions
//
func Elev_init() (err, floor int){ // returns a status int and a floor int
if (int(Io_init()) != 1) {
return 1, -1
}
// turn off all lights
for i := 0; i < N_floors; i++ {
if i != 0 {
Button_light(i, Button_down, 0)
}
if i != (N_floors - 1) {
Button_light(i, Button_up, 0)
}
Button_light(i, Button_command, 0)
}
Stop_light(0)
Door_light(0)
// find current floor
floor = 0
for i := 0; i < N_floors; i++{
if(Io_read_bit(Sensors[i]) == 1) {
floor = i
}
}
Printf("Init floor : %d\n", floor)
Floor_ind(floor)
Motor(0)
return
}
func Floor_ind(floor int){
if (floor & 0x02 == 0x02) {
Io_set_bit(LIGHT_FLOOR_IND1)
} else{
Io_clear_bit(LIGHT_FLOOR_IND1)
}
if (floor & 0x01 == 0x01) {
Io_set_bit(LIGHT_FLOOR_IND2)
} else{
Io_clear_bit(LIGHT_FLOOR_IND2)
}
}
func Poll_buttons() Event_t{
for i := 0; i < N_floors; i++ {
for j := 0; j < N_buttons; j++{
if (Io_read_bit(Button_matrix[i][j]) == 1 && button[i][j] == 0){
button[i][j] = 1
return Event_t{i,j} // returns on which floor (i) the button (j) has been pressed
}else if (Io_read_bit(Button_matrix[i][j]) == 0){
button[i][j] = 0
}
}
}
return Event_t{-1,-1}
}
func Button_light(floor, button, value int){
if value == 1 {
Io_set_bit(Light_matrix[floor][button])
}else {
Io_clear_bit(Light_matrix[floor][button])
}
}
func Get_floor() int {
for i := 0; i < N_floors; i++ {
if Io_read_bit(Sensors[i]) == 1 {
return i
}
}
return -1
}
func Stop_light(i int){
if (i == 1) {
Io_set_bit(LIGHT_STOP)
}else{
Io_clear_bit(LIGHT_STOP)
}
}
func Door_light(i int){
if (i == 1) {
Io_set_bit(LIGHT_DOOR_OPEN)
}else{
Io_clear_bit(LIGHT_DOOR_OPEN)
}
}
var prev_speed int
func Motor(speed int){
if ( speed > 0 ){
Io_clear_bit(MOTORDIR)
Io_write_analog(MOTOR, int(2048 + 4*Abs(float64(speed))))
}else if (speed < 0){
Io_set_bit(MOTORDIR)
Io_write_analog(MOTOR, int(2048 + 4*Abs(float64(speed))))
}else{
if (prev_speed < 0){
Io_clear_bit(MOTORDIR)
}else if(prev_speed > 0){
Io_set_bit(MOTORDIR)
}
Io_write_analog(MOTOR, 0)
}
prev_speed = speed
}
|
[
3,
5
] |
/**
* Created by shiyi on 2017/11/22.
* Email: [email protected]
*/
package models
import (
"fmt"
"testing"
)
func TestProblemCreate(t *testing.T) {
InitAllInTest()
problem := &Problem{Title: "sadas", Description: "1111", TimeLimit: 1000, MemoryLimit: 128000}
if _, err := problem.Create(problem); err != nil {
t.Error("Create() failed. Error:", err)
}
}
func TestProblemRemove(t *testing.T) {
InitAllInTest()
var problem Problem
if err := problem.Remove(6); err != nil {
t.Error("Remove() failed. Error:", err)
}
}
func TestProblemUpdate(t *testing.T) {
InitAllInTest()
problem := &Problem{Title: "sadas", Description: "asdasdasd"}
if err := problem.Update(problem); err != nil {
t.Error("Update() failed. Error:", err)
}
}
func TestProblemGetById(t *testing.T) {
InitAllInTest()
problem := &Problem{Title: "sadas", Description: "fffff"}
Problem{}.Create(problem)
getProblem, err := Problem{}.GetById(problem.Id)
if err != nil {
t.Error("GetById() failed:", err.Error())
}
if *getProblem != *problem {
t.Error("GetById() failed:", "%v != %v", problem, getProblem)
}
}
func TestProblemQueryByTitle(t *testing.T) {
InitAllInTest()
problem1 := &Problem{Title: "测试"}
problem2 := &Problem{Title: "测试"}
Problem{}.Create(problem1)
Problem{}.Create(problem2)
//problemList, _ := Problem{}.QueryBySearch("测试", &Problem{UserId: 0}, 2, 0)
//
//for _, v := range problemList {
// fmt.Println(v.Id)
//}
//if err != nil {
// t.Error("QueryByTitile() failed:", err)
//}
//if len(problemList) != 2 {
// t.Error("QueryByTitile() failed:", "count is wrong!")
//}
}
func TestProblemQueryByUserId(t *testing.T) {
InitAllInTest()
problem := &Problem{UserId: 20}
problem.Create(problem)
problem1 := &Problem{UserId: 20}
problem.Create(problem1)
//getProblem, err := problem.QueryByProblem(&Problem{UserId: 20}, 2, 0)
//if err != nil {
// t.Error("QueryByUserId() failed:", err)
//}
//if len(getProblem) != 2 {
// t.Error("QueryByUserId() failed:", "count is wrong!")
//}
}
func TestProblem_Count(t *testing.T) {
InitAllInTest()
sum, _ := Problem{}.CountBySearch("测试", &Problem{UserId: 0})
fmt.Println(sum)
}
|
[
3
] |
package web
import (
"NovelWeb/net"
"NovelWeb/orm"
"NovelWeb/util"
"fmt"
"github.com/PuerkitoBio/goquery"
"log"
"strings"
"time"
)
type Biquge struct {
Url string
}
func NewBiquge() Biquge {
return Biquge{
Url: "http://www.xbiquge.la",
}
}
// 网站小说下载
func (bi Biquge) Pull() {
api := fmt.Sprintf("%s%s", bi.Url, "/xiaoshuodaquan/")
doc := net.GoQuery(api, false)
doc.Find("div#main").Find("li").Each(func(i int, sec *goquery.Selection) {
a := sec.Find("a").First()
href := a.AttrOr("href", "")
bi.BookAll(href)
})
}
/////////////////////////////////////////////////// 功能 /////////////////////////////////////////////////////
// 小说信息及列表
func (bi Biquge) BookAll(url string) {
book, chapters := bi.book(url)
log.Print(book)
xorm := orm.XOrm{}
// 书本信息
identify := util.MD5(book.Domain + book.Name)
if xorm.BookExist(identify) {
log.Print("[小说 Book 已存在]", book.Name)
} else {
filePath := "covers/" + identify + ".jpg"
util.FileDownload(filePath, book.Cover)
var fileResult net.UpFileResult
net.UploadFile(filePath, &fileResult)
if fileResult.Code == 2000 { // 封面上传成功
book.Cover = fileResult.Data.URL
transBookName := net.Translate(book.Name)
transBookDesc := net.Translate(book.Describe)
transBookAuthor := net.Translate(book.Author)
transBookType := net.Translate(book.Type)
// 翻译失败
if transBookName == "" || transBookDesc == "" || transBookAuthor == "" {
log.Print("[小说 Book 翻译失败]", book, transBookName, transBookDesc, transBookAuthor)
if transBookName == "" {
log.Print("[书名为空]", book.Name, "==", transBookName)
} else if transBookDesc == "" {
log.Print("[简介为空]", book.Describe, "==", transBookDesc)
} else if transBookAuthor == "" {
log.Print("[作者为空]", book.Author, "==", transBookAuthor)
}
} else {
book.Identifier = identify
book.Name = transBookName
book.Describe = transBookDesc
book.Author = transBookAuthor
book.Type = transBookType
book.Index = strings.Replace(transBookName, " ", "-", -1)
book.Translate = "2"
book.Domain = url
book.Source = "crawler"
book.Language = "zh"
book.Source_ctr = 3
book.Score = 3.0
book.Keywords = `wuxia,topNovel,novel, light novel, web novel, chinese novel, korean novel, japanese novel, read light novel, read web novel, read koren novel, read chinese novel, read english novel, read novel for free, novel chapter,free,free novel`
log.Print("[小说]", book)
xorm.Insert(book)
}
} else {
log.Print("[封面]上传失败", book.Name)
}
}
// 章节
for index, simpleChapter := range chapters {
index++
if xorm.ChapterExist(identify, util.IntToString(index)) {
log.Print("[章节已存在]", book.Name, simpleChapter.Title)
} else {
chapter := bi.chapter(simpleChapter.Domain)
transTitle := net.Translate(chapter.Title)
transContent := net.Translate(chapter.Content)
// 章节翻译失败
if transTitle == "" || transContent == "" {
log.Print("[小说章节信息翻译失败]", simpleChapter, simpleChapter.Domain, transTitle, transContent)
if transTitle == "" {
log.Print("[章节标题为空]", chapter.Title, "==", transTitle)
} else if transContent == "" {
log.Print("[章节内容为空]", chapter.Content, "==", transContent)
}
} else {
chapter.Idx = index
chapter.Identifier = identify
chapter.Idx_name = fmt.Sprintf("Chapter %d", index)
chapter.Title = transTitle
chapter.Content = transContent
chapter.Domain = simpleChapter.Domain
chapter.LastUpdate = time.Now().Unix()
chapter.Index = strings.Replace(transTitle, " ", "-", -1)
chapter.Source = "crawler"
chapter.Keywords = `wuxia,topNovel,novel, light novel, web novel, chinese novel, korean novel, japanese novel, read light novel, read web novel, read koren novel, read chinese novel, read english novel, read novel for free, novel chapter,free,free novel`
chapter.Translate = "2"
transBookName := net.Translate(book.Name)
chapter.BookIndex = strings.Replace(transBookName, " ", "-", -1)
log.Print("[章节]", book.Name, chapter)
xorm.Insert(chapter)
}
}
}
}
// 小说
func (bi Biquge) book(url string) (orm.Book, []orm.Chapter) {
doc := net.GoQuery(url, false)
var book orm.Book
var chapters []orm.Chapter
book.Domain = url
doc.Find("div.con_top").Find("a").Each(func(i int, sec *goquery.Selection) {
if i == 2 {
book.Type = sec.Text()
}
})
cover := doc.Find("div#sidebar").Find("img").AttrOr("src", "")
book.Cover = cover
maininfo := doc.Find("div#maininfo")
info := maininfo.Find("div#info")
name := info.Find("h1").Text()
book.Name = name
info.Find("p").Each(func(i int, sec *goquery.Selection) {
if i == 0 {
author := strings.Split(sec.Text(), ":")[1]
book.Author = author
} else if i == 2 {
update := strings.Split(sec.Text(), ":")[1]
book.Last_update = update
}
})
maininfo.Find("div#intro").Find("p").Each(func(i int, sec *goquery.Selection) {
if i == 1 {
introTxt := sec.Text()
book.Describe = introTxt
}
})
doc.Find("div#list").Find("dd").Each(func(i int, sec *goquery.Selection) {
a := sec.Find("a")
href := bi.Url + a.AttrOr("href", "")
chapter := orm.Chapter{Domain: href}
chapters = append(chapters, chapter)
})
return book, chapters
}
// 章节
func (bi Biquge) chapter(url string) orm.Chapter {
var chapter orm.Chapter
doc := net.GoQuery(url, false)
content := doc.Find("div.content_read")
h1 := content.Find("div.bookname").Find("h1").Text()
_, title := util.TitleSepatate(h1)
chapter.Title = title
conTxt := content.Find("div#content").Text()
chapter.Content = conTxt
return chapter
}
|
[
5
] |
package main
import (
"flag"
"fmt"
)
func main() {
wordPtr := flag.String("word", "diego", "a string")
numPtr := flag.Int("number", 21, "an int")
boolPtr := flag.Bool("Fork", true, "a bool")
var svar string
flag.StringVar(&svar,"svar", "diegolovemetal", "a string var")
//解析
flag.Parse()
fmt.Println("word:", *wordPtr)
fmt.Println("numb:", *numPtr)
fmt.Println("fork:", *boolPtr)
fmt.Println("svar:", svar)
fmt.Println("tail:", flag.Args())
}
|
[
3
] |
package part4
// GenerateData creates slice of elements for benchmarking.
func GenerateData[N Number](len int, dtype DataType) []Element[N] {
res := make([]Element[N], len)
t := int64(0)
for i := 0; i < len; i++ {
switch dtype {
case Int32:
res[i] = Element[N]{
Timestamp: t,
Value: N(int32(i)),
}
case Float32:
res[i] = Element[N]{
Timestamp: t,
Value: N(float32(i)),
}
case Float64:
res[i] = Element[N]{
Timestamp: t,
Value: N(float64(i)),
}
}
t += 3
}
return res
}
var testDataInt32 = GenerateData[int32](6000000, Int32)
var testDataFloat32 = GenerateData[float32](6000000, Float32)
var testDataFloat64 = GenerateData[float64](6000000, Float64)
|
[
1
] |
package service
import (
"net/http"
"github.com/Sirupsen/logrus"
"github.com/reechou/duobb/models"
"github.com/reechou/duobb_proto"
)
type SpPlanService struct{}
func (self *SpPlanService) CreateSpPlan(r *http.Request, req *duobb_proto.CreateSpPlanReq, rsp *duobb_proto.Response) error {
logrus.Debugf("CreateSpPlan req: %v", req)
count, err := models.GetSpPlanCountFromUser(req.User)
if err != nil {
logrus.Errorf("get duobb sp plan count error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
if count >= SP_PLAN_MAX_COUNT {
rsp.Code = duobb_proto.DUOBB_CREATE_PLAN_OVER_LIMIT_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_CREATE_PLAN_OVER_LIMIT
return nil
}
plan := &models.SpPlan{
Name: req.Name,
CreateUser: req.User,
Password: req.Password,
Remark: req.Remark,
}
err = models.CreateSpPlan(plan)
if err != nil {
logrus.Errorf("create duobb sp plan error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
rsp.Data = plan
return nil
}
func (self *SpPlanService) DeleteSpPlan(r *http.Request, req *duobb_proto.DeleteSpPlanReq, rsp *duobb_proto.Response) error {
logrus.Debugf("CreateSpPlan req: %v", req)
plan := &models.SpPlan{
Id: req.PlanId,
CreateUser: req.User,
}
err := models.DeleteSpPlan(plan)
if err != nil {
logrus.Errorf("delete duobb sp plan error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
return nil
}
func (self *SpPlanService) GetSpPlanListFromUser(r *http.Request, req *duobb_proto.GetSpPlanListFromUserReq, rsp *duobb_proto.Response) error {
logrus.Debugf("GetSpPlanListFromUser req: %v", req)
list, err := models.GetSpPlanListFromUser(req.User, req.Offset, req.Num)
if err != nil {
logrus.Errorf("get duobb sp plan list from user error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
rsp.Data = list
return nil
}
func (self *SpPlanService) GetSpPlanListPublic(r *http.Request, req *duobb_proto.GetSpPlanListPublicReq, rsp *duobb_proto.Response) error {
logrus.Debugf("GetSpPlanListPublic req: %v", req)
list, err := models.GetSpPlanListPublic(req.QueryPriceStart, req.QueryPriceEnd, req.QueryCommissionStart, req.QueryCommissionEnd, req.QueryNumStart, req.QueryNumEnd, req.Offset, req.Num)
if err != nil {
logrus.Errorf("get duobb sp plan list public error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
rsp.Data = list
return nil
}
func (self *SpPlanService) GetSpPlanInfoFromUser(r *http.Request, req *duobb_proto.GetSpPlanInfoFromUserReq, rsp *duobb_proto.Response) error {
logrus.Debugf("GetSpPlanInfoFromUser req: %v", req)
plan := &models.SpPlan{
Id: req.PlanId,
CreateUser: req.User,
}
err := models.GetSpPlanInfoFromUser(plan)
if err != nil {
logrus.Errorf("get duobb sp plan info from user error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
rsp.Data = plan
//logrus.Debug(plan)
return nil
}
func (self *SpPlanService) GetSpPlanInfoFromPassword(r *http.Request, req *duobb_proto.GetSpPlanFromPasswordReq, rsp *duobb_proto.Response) error {
logrus.Debugf("GetSpPlanInfoFromPassword req: %v", req)
plan := &models.SpPlan{
Id: req.PlanId,
Password: req.Password,
}
err := models.GetSpPlanInfoFromPassword(plan)
if err != nil {
logrus.Errorf("get duobb sp plan info from password error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
rsp.Data = plan
return nil
}
func (self *SpPlanService) UpdateSpPlanInfo(r *http.Request, req *duobb_proto.UpdateSpPlanInfoReq, rsp *duobb_proto.Response) error {
logrus.Debugf("UpdateSpPlanInfo req: %v", req)
plan := &models.SpPlan{
Id: req.PlanId,
CreateUser: req.User,
Name: req.Name,
Password: req.Password,
Remark: req.Remark,
}
err := models.UpdateSpPlanInfo(plan)
if err != nil {
logrus.Errorf("update duobb sp plan info error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
return nil
}
func (self *SpPlanService) UpdateSpPlanItems(r *http.Request, req *duobb_proto.UpdateSpPlanItemsReq, rsp *duobb_proto.Response) error {
logrus.Debugf("UpdateSpPlanItems req planid[%d] itemsnum: %d", req.PlanId, req.ItemsNum)
plan := &models.SpPlan{
Id: req.PlanId,
CreateUser: req.User,
ItemsNum: req.ItemsNum,
ItemsAvgPrice: req.ItemsAvgPrice,
AvgCommission: req.AvgCommission,
ItemsList: req.ItemsList,
}
err := models.UpdateSpPlanItems(plan)
if err != nil {
logrus.Errorf("update duobb sp plan items error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
return nil
}
func (self *SpPlanService) UpdateSpPlanPassword(r *http.Request, req *duobb_proto.UpdateSpPlanPasswordReq, rsp *duobb_proto.Response) error {
logrus.Debugf("UpdateSpPlanPassword req: %v", req)
plan := &models.SpPlan{
Id: req.PlanId,
CreateUser: req.User,
Password: req.Password,
}
err := models.UpdateSpPlanPassword(plan)
if err != nil {
logrus.Errorf("update duobb sp plan password error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
return nil
}
func (self *SpPlanService) UpdateSpPlanRemark(r *http.Request, req *duobb_proto.UpdateSpPlanRemarkReq, rsp *duobb_proto.Response) error {
logrus.Debugf("UpdateSpPlanRemark req: %v", req)
plan := &models.SpPlan{
Id: req.PlanId,
CreateUser: req.User,
Remark: req.Remark,
}
err := models.UpdateSpPlanRemark(plan)
if err != nil {
logrus.Errorf("update duobb sp plan remark error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
return nil
}
func (self *SpPlanService) SyncSpPlanSource(r *http.Request, req *duobb_proto.SyncSpPlanSourceReq, rsp *duobb_proto.Response) error {
logrus.Debugf("SyncSpPlanSource req: %v", req)
plan := &models.SpPlan{
Id: req.SourceFromId,
Password: req.SourceIdPassword,
}
err := models.GetSpPlanInfoFromPassword(plan)
if err != nil {
logrus.Errorf("get duobb sp plan from password error: %v", err)
rsp.Code = duobb_proto.DUOBB_GET_PLAN_FROM_PW_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_PLAN_FROM_PW_ERROR
return err
}
plan = &models.SpPlan{
Id: req.PlanId,
CreateUser: req.User,
SourceFromId: req.SourceFromId,
}
err = models.UpdateSpPlanSourceFrom(plan)
if err != nil {
logrus.Errorf("update duobb sp plan source error: %v", err)
rsp.Code = duobb_proto.DUOBB_DB_ERROR
rsp.Msg = duobb_proto.MSG_DUOBB_DB_ERROR
return err
}
rsp.Code = duobb_proto.DUOBB_RSP_SUCCESS
return nil
}
|
[
3
] |
package repo
import (
"context"
"fmt"
svcerr "github.com/Sainarasimhan/go-error/err"
log "github.com/Sainarasimhan/sample/pkg/log"
"github.com/lib/pq"
"go.opentelemetry.io/otel/api/trace"
)
type commonMiddlware struct {
Repository
log.Logger
ot trace.Tracer
}
//MiddleWare - returns new implementation covering existing one
type MiddleWare func(Repository) Repository
//CommonMiddleware - Does below functionalities
// - convert any DB error to standard error
// - Sets up Opentelemetry tracer for DB calls
func CommonMiddleware(lg log.Logger, ot trace.Tracer) MiddleWare {
return func(next Repository) Repository {
lg.Debugw(context.Background(), "Middleware", "Wrapped Repo with ErrorMiddelware")
return &commonMiddlware{Repository: next, Logger: lg, ot: ot}
}
}
func (cm *commonMiddlware) Insert(ctx context.Context, req Request) (Response, error) {
if sp := cm.traceDB(ctx); sp != nil {
defer sp.End()
}
resp, err := cm.Repository.Insert(ctx, req)
if err != nil {
return resp, cm.mapPostgresError(fmt.Sprintf("Insert with req %v", req), err)
}
return resp, err
}
func (cm *commonMiddlware) List(ctx context.Context, req Request) ([]Details, error) {
if sp := cm.traceDB(ctx); sp != nil {
defer sp.End()
}
dts, err := cm.Repository.List(ctx, req)
if err != nil {
return dts, cm.mapPostgresError(fmt.Sprintf("List with req %v", req), err)
}
if len(dts) == 0 {
return dts, svcerr.NotFound(fmt.Sprintf("Entries not Found for ID %d", req.ID))
}
return dts, err
}
//Not Used atm
/*func (e *errorMiddleware) Delete(ctx context.Context, req Request) error {
err := e.Repository.Delete(ctx, req)
if err != nil {
return e.mapPostgresError(fmt.Sprintf("Delete with req %v", req), err)
}
return err
}*/
func (cm *commonMiddlware) mapPostgresError(msg string, err error) (serr error) {
if perr, ok := err.(*pq.Error); ok {
cm.Debug(context.Background(), perr.Error(), fmt.Sprintf("Detailed error %#v", perr))
detail := svcerr.DebugInfo{
Detail: msg + "Detail:" + perr.Message,
}
switch perr.Code.Class() {
case "2":
return svcerr.NotFound(perr.Error(), &detail)
case "23", "42":
return svcerr.InvalidArgs(perr.Error(), &detail)
case "53", "54":
return svcerr.ResourceExhausted(perr.Error(), &detail)
default:
return svcerr.InternalErr(perr.Error(), &detail)
}
}
return err
}
/*Func to start tracer for DB2 call*/
func (cm *commonMiddlware) traceDB(ctx context.Context) trace.Span {
if cm.ot == nil {
return nil
}
if span := trace.SpanFromContext(ctx); span != nil {
_, sp := cm.ot.Start(ctx, "Postgres Database Call")
return sp
}
_, sp := cm.ot.Start(ctx, "Asynchronous Postgres Database Call")
return sp
}
|
[
3
] |
package utils
import (
"reflect"
)
type Slice struct {
I interface{}
}
// convert slice to map
func (s Slice) SliceToMap(is ...interface{}) M {
m := M{}
var inter []interface{}
var interNum int
switch si := s.I.(type) {
case []string:
if len(is) > 0 {
var ok bool
inter, ok = is[0].([]interface{})
if !ok {
return m
}
}
interNum = len(inter)
for key, value := range si {
if key <= interNum {
v := reflect.ValueOf(inter[key])
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
m[value] = v.Interface()
} else {
m[value] = nil
}
}
}
return m
}
|
[
7
] |
package mongo
import (
"context"
"github.com/pejovski/wish-list/model"
"time"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
repo "github.com/pejovski/wish-list/repository"
)
const (
database = "wish"
collection = "items"
)
type repository struct {
collection *mongo.Collection
}
func NewRepository(c *mongo.Client) repo.Repository {
return repository{collection: c.Database(database).Collection(collection)}
}
// get product with full data
func (r repository) Product(productId string) (*model.Product, error) {
filter := bson.M{
"product_id": productId,
"price": bson.M{
"$exists": true,
},
}
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
result := r.collection.FindOne(ctx, filter)
if result.Err() != nil {
if result.Err() == mongo.ErrNoDocuments {
logrus.Infof("No document for product %s", productId)
return nil, nil
}
logrus.Errorf("FindOne failed for product %s Error: %s", productId, result.Err())
return nil, result.Err()
}
var product *model.Product
err := result.Decode(&product)
if err != nil {
logrus.Errorf("FindOne failed for product %s. Error: %s", productId, err)
return nil, err
}
// ToDo - check why productId was not set
product.ProductId = productId
return product, nil
}
func (r repository) UpdateProduct(product *model.Product) error {
filter := bson.M{
"product_id": bson.M{
"$eq": product.ProductId,
},
}
update := bson.M{"$set": bson.M{
"name": product.Name,
"brand": product.Brand,
"price": product.Price,
"image": product.Image,
}}
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
_, err := r.collection.UpdateMany(
ctx,
filter,
update,
)
if err != nil {
logrus.Errorf("UpdateMany failed for product %s; Error: %s", product.ProductId, err)
return err
}
return nil
}
func (r repository) DeactivateProduct(productId string) error {
// ToDo
return nil
}
func (r repository) DeleteProduct(productId string) error {
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
_, err := r.collection.DeleteMany(ctx, bson.M{"product_id": productId})
if err != nil {
logrus.Errorf("DeleteMany failed for product %s; Error: %s", productId, err)
return err
}
return nil
}
func (r repository) UpdateProductPrice(productId string, price float32) error {
filter := bson.M{
"product_id": bson.M{
"$eq": productId,
},
}
update := bson.M{"$set": bson.M{
"price": price,
}}
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
_, err := r.collection.UpdateMany(
ctx,
filter,
update,
)
if err != nil {
logrus.Errorf("UpdateMany failed for product %s; Error: %s", productId, err)
return err
}
return nil
}
func (r repository) Item(userId string, productId string) (*model.Item, error) {
filter := bson.M{"user_id": userId, "product_id": productId}
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
result := r.collection.FindOne(ctx, filter)
if result.Err() != nil {
if result.Err() == mongo.ErrNoDocuments {
logrus.Infof("No document for product %s, user %s", productId, userId)
return nil, nil
}
logrus.Errorf("FindOne failed for product %s, user %s Error: %s", productId, userId, result.Err())
return nil, result.Err()
}
var item *model.Item
err := result.Decode(&item)
if err != nil {
logrus.Errorf("FindOne failed for product %s, user %s Error: %s", productId, userId, err)
return nil, err
}
return item, nil
}
func (r repository) CreateItem(userId string, productId string) error {
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
_, err := r.collection.InsertOne(ctx, bson.M{"user_id": userId, "product_id": productId, "active": true})
if err != nil {
logrus.Errorf("InsertOne failed for product %s, user %s Error: %s", productId, userId, err)
return err
}
return nil
}
func (r repository) DeleteItem(userId string, productId string) error {
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
_, err := r.collection.DeleteOne(ctx, bson.M{"user_id": userId, "product_id": productId})
if err != nil {
logrus.Errorf("DeleteOne failed for product %s, user %s Error: %s", productId, userId, err)
return err
}
return nil
}
func (r repository) UpdateItem(userId string, product *model.Product) error {
filter := bson.M{
"product_id": bson.M{
"$eq": product.ProductId,
},
"user_id": bson.M{
"$eq": userId,
},
}
update := bson.M{"$set": bson.M{
"name": product.Name,
"brand": product.Brand,
"price": product.Price,
"image": product.Image,
}}
ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
_, err := r.collection.UpdateOne(
ctx,
filter,
update,
)
if err != nil {
logrus.Errorf("UpdateMany failed for product %s; Error: %s", product.ProductId, err)
return err
}
return nil
}
func (r repository) List(userId string) (model.List, error) {
list := model.List{}
filter := bson.M{"user_id": userId}
ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)
cur, err := r.collection.Find(ctx, filter)
if err != nil {
logrus.Errorf("Find all failed for user %s Error: %s", userId, err)
return nil, err
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var item *Item
err := cur.Decode(&item)
if err != nil {
logrus.Errorf("Find all decode failed for user %s Error: %s", userId, err)
return nil, err
}
// ToDo create filter and move this out
if item.Name == "" {
continue
}
list = append(list, mapItemToDomainItem(item))
}
if err := cur.Err(); err != nil {
logrus.Errorf("Find all failed for user %s Error: %s", userId, err)
return nil, err
}
return list, nil
}
|
[
6
] |
package impl
import (
"bufio"
"fmt"
"os"
"runtime"
"strings"
"testing"
"unicode"
"github.com/yorikya/go-logger/encoders"
"github.com/yorikya/go-logger/flags"
"github.com/yorikya/go-logger/level"
)
type stdoutCapture struct {
//out comunication out chan
out chan string
//readPipe read from file
readPipe,
//writePipe write to file
writePipe,
//origStdout holds original stdout file
origStdout *os.File
}
func ScanCRLF(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
func newStdoutCapture() *stdoutCapture {
readFile, writeFile, err := os.Pipe()
if err != nil {
println("**** error: ", err.Error())
return nil
}
c := &stdoutCapture{
out: make(chan string),
readPipe: readFile,
writePipe: writeFile,
origStdout: os.Stdout,
}
os.Stdout = writeFile
go func() {
scanner := bufio.NewScanner(readFile)
scanner.Split(ScanCRLF)
for scanner.Scan() {
msg := scanner.Text()
c.out <- msg
}
}()
return c
}
func (c *stdoutCapture) getString() string {
return <-c.out
}
func (c *stdoutCapture) close() {
c.writePipe.Close()
os.Stdout = c.origStdout
}
func replaceDigit(source []rune, rep rune) string {
var res []rune
for _, r := range source {
if unicode.IsDigit(r) {
res = append(res, rep)
continue
}
res = append(res, r)
}
return string(res)
}
func replaceDigitWithD(source []rune) string {
return replaceDigit(source, 'D')
}
func wrapElement(s string) string {
return "[" + s + "]"
}
func assertEqual(t *testing.T, expect, current interface{}) {
if expect != current {
_, file, no, _ := runtime.Caller(2)
t.Errorf("test failed expect: <%v>, current: <%v>\nCaller: %s, Line: %d", expect, current, file, no)
}
}
func assertTrue(t *testing.T, current interface{}) {
assertEqual(t, true, current)
}
func cutFirstElement(s string) string {
start := strings.IndexRune(s, '[')
end := strings.IndexRune(s, ']') + 1
return string([]rune(s)[start:end])
}
func testOutput(t *testing.T, msg, out string, lvl level.Level, logger *BasicLogger) {
var seek, timstampLen int
outRune := []rune(out)
//Test timestamp
if flags.ContainFlag(logger.getFlags(), flags.Ftimestamp) {
timeFmt := wrapElement(logger.getAppenders().GetAppender(0).GetEncoder().GetTimeFormat())
timstampLen = len(timeFmt)
assertEqual(t,
replaceDigitWithD([]rune(timeFmt)),
replaceDigitWithD(outRune[seek:timstampLen]))
seek += timstampLen
}
//Test log level
if logger.getAppenders().GetAppender(0).GetEncoder().GetWithLevel() {
levelFmt := wrapElement(lvl.String())
levelLen := len(levelFmt)
assertEqual(t, levelFmt, string(outRune[seek:seek+levelLen]))
seek += levelLen
}
//Test caller
if flags.ContainFlag(logger.getFlags(), flags.Fcaller) {
caller := cutFirstElement(string(outRune[seek:]))
callerLen := len(caller)
assertTrue(t, strings.Contains(caller, ".go"))
if !flags.ContainFlag(logger.getFlags(), flags.FshortFile) {
assertTrue(t, strings.Contains(caller, "/"))
}
seek += callerLen
}
//Test logger name
if flags.ContainFlag(logger.getFlags(), flags.FLoggername) {
name := wrapElement(logger.getName())
nameLen := len(name)
assertEqual(t, name, string(outRune[seek:seek+nameLen]))
seek += nameLen
}
//Test message
assertEqual(t, msg, string(outRune[seek:]))
}
func TestDebug(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Debug message"
l := NewConsoleLogger("Test", level.DebugLevel, flags)
l.Debug(msg)
c.close()
testOutput(t, msg, c.getString(), level.DebugLevel, l)
}
func TestDebugf(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Debug %s with %d substitutions"
firstArg := "mesage"
secondArg := 2
l := NewConsoleLogger("Test", level.DebugLevel, flags)
l.Debugf(msg, firstArg, secondArg)
c.close()
testOutput(t, fmt.Sprintf(msg, firstArg, secondArg), c.getString(), level.DebugLevel, l)
}
func TestDebugln(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Debug message with new line"
l := NewConsoleLogger("Test", level.DebugLevel, flags)
l.Debugln(msg)
c.close()
testOutput(t, msg+encoders.NewLine, c.getString(), level.DebugLevel, l)
}
func TestInfo(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Info message"
l := NewConsoleLogger("Test", level.InfoLevel, flags)
l.Info(msg)
c.close()
testOutput(t, msg, c.getString(), level.InfoLevel, l)
}
func TestInfof(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Info %s with %d substitutions"
firstArg := "mesage"
secondArg := 2
l := NewConsoleLogger("Test", level.InfoLevel, flags)
l.Infof(msg, firstArg, secondArg)
c.close()
testOutput(t, fmt.Sprintf(msg, firstArg, secondArg), c.getString(), level.InfoLevel, l)
}
func TestInfoln(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Info message with new line"
l := NewConsoleLogger("Test", level.InfoLevel, flags)
l.Infoln(msg)
c.close()
testOutput(t, msg+encoders.NewLine, c.getString(), level.InfoLevel, l)
}
func TestWarn(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Warn message"
l := NewConsoleLogger("Test", level.WarnLevel, flags)
l.Warn(msg)
c.close()
testOutput(t, msg, c.getString(), level.WarnLevel, l)
}
func TestWarnf(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Warn %s with %d substitutions"
firstArg := "mesage"
secondArg := 2
l := NewConsoleLogger("Test", level.WarnLevel, flags)
l.Warnf(msg, firstArg, secondArg)
c.close()
testOutput(t, fmt.Sprintf(msg, firstArg, secondArg), c.getString(), level.WarnLevel, l)
}
func TestWarnln(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Warn message with new line"
l := NewConsoleLogger("Test", level.WarnLevel, flags)
l.Warnln(msg)
c.close()
testOutput(t, msg+encoders.NewLine, c.getString(), level.WarnLevel, l)
}
func TestError(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Error message"
l := NewConsoleLogger("Test", level.ErrorLevel, flags)
l.Error(msg)
c.close()
testOutput(t, msg, c.getString(), level.ErrorLevel, l)
}
func TestErrorf(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Error %s with %d substitutions"
firstArg := "mesage"
secondArg := 2
l := NewConsoleLogger("Test", level.ErrorLevel, flags)
l.Errorf(msg, firstArg, secondArg)
c.close()
testOutput(t, fmt.Sprintf(msg, firstArg, secondArg), c.getString(), level.ErrorLevel, l)
}
func TestErrorln(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Error message with new line"
l := NewConsoleLogger("Test", level.ErrorLevel, flags)
l.Errorln(msg)
c.close()
testOutput(t, msg+encoders.NewLine, c.getString(), level.ErrorLevel, l)
}
func TestPanic(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Panic message"
l := NewConsoleLogger("Test", level.PanicLevel, flags)
defer func() {
if r := recover(); r != nil {
c.close()
testOutput(t, msg, c.getString(), level.PanicLevel, l)
return
}
t.Error("not panic mode")
}()
l.Panic(msg)
// TODO: add recovery code
}
func TestPanicf(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Panic %s with %d substitutions"
firstArg := "mesage"
secondArg := 2
l := NewConsoleLogger("Test", level.PanicLevel, flags)
defer func() {
if r := recover(); r != nil {
c.close()
testOutput(t, fmt.Sprintf(msg, firstArg, secondArg), c.getString(), level.PanicLevel, l)
return
}
t.Error("not panic mode")
}()
l.Panicf(msg, firstArg, secondArg)
}
func TestPanicln(t *testing.T) {
c := newStdoutCapture()
flags := FBasicLoggerFlags
msg := "test Panic message with new line"
l := NewConsoleLogger("Test", level.PanicLevel, flags)
defer func() {
if r := recover(); r != nil {
c.close()
testOutput(t, msg+encoders.NewLine, c.getString(), level.PanicLevel, l)
return
}
t.Error("not panic mode")
}()
l.Panicln(msg)
}
|
[
3
] |
package main
import (
"fmt"
"strings"
"os"
"io/ioutil"
"strconv"
"log"
"regexp"
)
var counter = 0
func SplitAny(s string, seps string) []string {
splitter := func(r rune) bool {
return strings.ContainsRune(seps, r)
}
return strings.FieldsFunc(s, splitter)
}
func lab3(filetemp os.FileInfo, pwd string) {
var countWords = 0
var bufSize int = 1000
var words []string
var IsLetter = regexp.MustCompile(`^[A-Za-z]+$`).MatchString
var IsPunctuation = regexp.MustCompile(`^[.,:;?!-]+$`).MatchString
var IsSymbol = regexp.MustCompile(`^[' \t\n\r]+$`).MatchString
file, err := os.Open(pwd + SplitAny(os.Args[1], ".")[0] + "/" + filetemp.Name())
if err != nil {
log.Fatal(err)
}
defer file.Close()
var str string = filetemp.Name()
res, er := os.Create(pwd + SplitAny(os.Args[2], ".")[0] + "/" + SplitAny(str, ".")[0] + ".res")
if er != nil{
fmt.Println("Unable to create file:", err)
os.Exit(1)
}
defer res.Close()
data := make([]byte, bufSize)
dataPrev := make([]byte, bufSize)
for {
n, err := file.Read(data)
if err != nil {
break
}
var prev = string(dataPrev[n - 1])
var next = string(data[0])
for a := 0; a < n; a++ {
if (!IsLetter(string(data[a])) && (!IsSymbol(string(data[a]))) && (string(data[a]) != "-")) {
data[a] = []byte(" ")[0]
}
}
words = SplitAny(string(data[:n]), " \t\n\r")
countWords += len(words)
for i := 0; i < (n - 2); i++ {
if (IsSymbol(string(data[i])) && IsPunctuation(string(data[i+1])) && IsSymbol(string(data[i+2]))) {
countWords--
}
}
if n == bufSize {
if countWords != 0 {
if (!IsSymbol(prev)) && (!IsSymbol(next)) {
countWords--
}
}
}
dataPrev = data
}
res.WriteString(strconv.Itoa(countWords))
counter++
}
func main() {
var countFiles = 0
files, err := ioutil.ReadDir(os.Args[1])
if err != nil {
log.Fatal(err)
}
pwd, err := os.Getwd()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if _, error := os.Stat(pwd + SplitAny(os.Args[2], ".")[0]); error != nil {
os.Mkdir(pwd + SplitAny(os.Args[2], ".")[0], 0700)
}
for _, filetemp := range files {
go lab3(filetemp, pwd)
countFiles++
}
for counter != countFiles {}
fmt.Println("Total number of processed files:", countFiles)
}
|
[
6
] |
package lib
import (
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"strings"
)
//Uninstall : Install the provided version in the argument
func Uninstall(url string) string {
/* get current user */
usr, errCurr := user.Current()
if errCurr != nil {
log.Fatal(errCurr)
}
slice := strings.Split(url, "/")
app := slice[1]
installPath = fmt.Sprintf(installPath, app)
bin := fmt.Sprintf(binLocation, app)
installVersion = fmt.Sprintf(installVersion, app)
installFile = fmt.Sprintf(installFile, app)
/* set installation location */
installLocation = usr.HomeDir + installPath
/* set default binary path for app */
installedBinPath = bin
/* find app binary location if app is already installed*/
cmd := NewCommand(app)
next := cmd.Find()
/* overrride installation default binary path if app is already installed */
/* find the last bin path */
for path := next(); len(path) > 0; path = next() {
installedBinPath = path
}
/* check if selected version already downloaded */
//fileExist := CheckFileExist(installLocation + installVersion + appversion)
filesExist := GetListOfFile(installLocation)
/* if selected version already exist, */
if len(filesExist) > 0 {
symlinkExist := CheckSymlink(installedBinPath)
if symlinkExist {
RemoveSymlink(installedBinPath)
}
return installLocation
}
return installLocation
}
//RemoveContents remove all files in directory
func RemoveContents(dir string) error {
fmt.Println("Attempting to remove installed files...")
d, err := os.Open(dir)
if err != nil {
fmt.Printf("Cannot find directory %s\n", dir)
return err
}
defer d.Close()
names, err := d.Readdirnames(-1)
if err != nil {
fmt.Printf("Cannot remove directory %s\n", dir)
return err
}
for _, name := range names {
err = os.RemoveAll(filepath.Join(dir, name))
if err != nil {
fmt.Printf("Cannot remove directory %s\n", dir)
return err
}
}
return nil
}
|
[
3
] |
package controllers
import (
"fish/configs"
"fish/enums"
"fish/models"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/cache"
"github.com/astaxie/beego/utils/captcha"
"github.com/nfnt/resize"
"github.com/skip2/go-qrcode"
"html/template"
"image"
"image/draw"
"image/png"
"math/rand"
"os"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
var cpt *captcha.Captcha
type baseController struct {
beego.Controller
}
func init() {
store := cache.NewMemoryCache()
cpt = captcha.NewWithFilter("/captcha/", store)
cpt.ChallengeNums = 4
cpt.StdHeight = 40
cpt.StdWidth = 100
beego.AddFuncMap("year", time.Now().Year)
beego.AddFuncMap("v", verifyPower)
}
func (c *baseController) Prepare() {
c.Data["rand"] = rand.Int()
c.Data["site"] = configs.Site
}
func (c *baseController) jsonData(code enums.ReturnCode, params ...interface{}) models.Result {
var data interface{}
var total int
if len(params) > 0 {
data = params[0]
if len(params) > 1 {
if reflect.TypeOf(params[1]) == reflect.TypeOf(int(1)) {
total = params[1].(int)
} else if reflect.TypeOf(params[1]) == reflect.TypeOf(int64(1)) {
total = int(params[1].(int64))
}
}
}
return models.Result{
State: int(code),
Msg: code.String(),
Data: data,
Total: total,
}
}
func verifyPower(admin models.AdminAccount, code int) bool {
for _, per := range strings.Split(admin.Permissions, ",") {
iPer, _ := strconv.Atoi(per)
//999是所有权限,0是不需要权限
if iPer == 999 || code == 0 {
return true
} else {
if iPer == code {
return true
}
}
}
return false
}
func createPostForm(c *baseController, items []map[string]interface{}) {
htmlFormatter := "<div class=\"form-group input-group\"><span class=\"input-group-addon\">%s</span>%s</div>"
inputFormatter := "<input class=\"form-control\" type=\"%s\" name=\"%s\" value=\"%s\" placeholder=\"%s\" %s %s/>"
sliderFormatter := "<input class=\"form-control\" type=\"slider\" id=\"%s\" name=\"%s\" data-slider-min=\"%s\" data-slider-max=\"%s\" data-slider-step=\"%s\" data-slider-value=\"%s\" data-slider-can-min=\"%s\"/><span class=\"input-group-addon\" style=\"width: 65px\"><span id=\"%s_val\">%s</span></span>"
selectFormatter := "<select class=\"form-control\" id=\"%s\" name=\"%s\">%s</select>"
optionFormatter := "<option value=\"%d\"%s>%s</option>"
checkboxFormatter := "<div class=\"col-sm-6 col-md-4 col-lg-4\"><label class=\"checkbox-inline\"><input type=\"checkbox\" name=\"%s\" value=\"%d\"%s>%s</label></div>"
radioFormatter := "<input class=\"form-control\" type=\"radio\" name=\"%s\" value=\"%s\"%s>%s"
var html template.HTML
for _, v := range items {
if v["id"] == "title" {
c.Data["title"] = v["value"]
} else if v["id"] == "url" {
c.Data["url"] = v["value"]
} else {
switch v["type"] {
case "text", "number", "password":
var required, readonly string
if v["required"] == "true" {
required = "required"
}
if v["readonly"] == "true" {
readonly = "readonly"
}
input := template.HTML(fmt.Sprintf(inputFormatter, v["type"], v["id"], v["value"], v["name"], required, readonly))
html += template.HTML(fmt.Sprintf(htmlFormatter, v["name"], input))
break
case "hidden":
html += template.HTML(fmt.Sprintf("<input type=\"hidden\" name=\"%s\" value=\"%s\">", v["id"], v["value"]))
case "content":
html += template.HTML(v["value"].(string))
break
case "slider":
c.Data["hasSlider"] = true
input := template.HTML(fmt.Sprintf(sliderFormatter, v["id"], v["id"], v["min"], v["max"], v["step"], v["value"], v["can-min"], v["id"], v["value"]))
html += template.HTML(fmt.Sprintf(htmlFormatter, v["name"], input))
break
case "select":
optionHtml := ""
options := v["value"].([]map[string]int)
for _, op := range options {
for key, value := range op {
if value == v["selected"] {
optionHtml += fmt.Sprintf(optionFormatter, value, "selected", key)
} else {
optionHtml += fmt.Sprintf(optionFormatter, value, "", key)
}
}
}
input := template.HTML(fmt.Sprintf(selectFormatter, v["id"], v["id"], optionHtml))
html += template.HTML(fmt.Sprintf(htmlFormatter, v["name"], input))
break
case "checkbox":
checkboxHtml := ""
checkbox_items := v["value"].(map[string]map[string]int)
var ind = 0
var groups []string
for group := range checkbox_items {
groups = append(groups, group)
}
sort.Strings(groups)
for _, group := range groups {
cls := "form-control-group"
groupHtml := "<div class=\"" + cls + "\">"
groupHtml += "<p>" + group + "</p>"
itemsHtml := ""
var items []string
for item := range checkbox_items[group] {
items = append(items, item)
}
sort.Strings(items)
for _, item := range items {
checkboxItem := ""
checkeds := strings.Split(v["checked"].(string), ",")
//fmt.Printf(fmt.Sprintf("%d,", value))
item_checked := false
for _, checked := range checkeds {
if checked == fmt.Sprintf("%d", checkbox_items[group][item]) {
item_checked = true
}
}
if item_checked {
checkboxItem = fmt.Sprintf(checkboxFormatter, v["id"], checkbox_items[group][item], "checked", item)
} else {
checkboxItem = fmt.Sprintf(checkboxFormatter, v["id"], checkbox_items[group][item], "", item)
}
groupHtml += checkboxItem
}
groupHtml += itemsHtml
groupHtml += "</div>"
checkboxHtml += groupHtml
ind++
}
tmpHtml := fmt.Sprintf(htmlFormatter, v["name"], checkboxHtml)
frist := strings.Index(tmpHtml, "form-control-group")
tmpHtml = tmpHtml[:frist] + "form-control-group form-control-group-top" + tmpHtml[frist+18:]
last := strings.LastIndex(tmpHtml, "form-control-group")
tmpHtml = tmpHtml[:last] + "form-control-group form-control-group-bottom" + tmpHtml[last+18:]
html += template.HTML(tmpHtml)
break
case "radio":
radios := ""
input := template.HTML(fmt.Sprintf(radioFormatter, v["id"], v["id"], radios))
html += template.HTML(fmt.Sprintf(htmlFormatter, v["name"], input))
break
}
}
}
c.Data["form"] = html
return
}
func getDownUrl() string {
index := rand.Intn(len(configs.DownUrls))
return configs.DownUrls[index]
}
func createQr(bgPath, info string) (newImg draw.Image, err error) {
bgFile, err := os.Open(bgPath)
defer bgFile.Close()
if err != nil {
return
}
logoFile, err := os.Open("static/img/logo.png")
defer logoFile.Close()
if err != nil {
return
}
bgImg, err := png.Decode(bgFile)
if err != nil {
return
}
logoImg, err := png.Decode(logoFile)
if err != nil {
return
}
qrCode, _ := qrcode.New(info, qrcode.Highest)
qrImg := qrCode.Image(235)
logoImgSize := qrImg.Bounds().Max.X / 4
logoImg = resize.Thumbnail(uint(logoImgSize), uint(logoImgSize), logoImg, resize.Lanczos3)
newImg = image.NewRGBA64(bgImg.Bounds())
global_offset_Y := 657
qrImg_offset := image.Pt(bgImg.Bounds().Max.X/2-qrImg.Bounds().Max.X/2, global_offset_Y-qrImg.Bounds().Max.Y/2)
logoImg_offset := qrImg_offset.Add(image.Pt(qrImg.Bounds().Max.X/2-logoImg.Bounds().Max.X/2, qrImg.Bounds().Max.Y/2-logoImg.Bounds().Max.Y/2))
draw.Draw(newImg, bgImg.Bounds(), bgImg, bgImg.Bounds().Min, draw.Over)
draw.Draw(newImg, qrImg.Bounds().Add(qrImg_offset), qrImg, qrImg.Bounds().Min, draw.Src)
draw.Draw(newImg, qrImg.Bounds().Add(logoImg_offset), logoImg, logoImg.Bounds().Min, draw.Src)
return
}
|
[
3,
4,
5
] |
package main
import (
"fmt"
"github.com/wllenyj/wtime"
"math"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
w := wtime.NewWheel(500 * time.Millisecond)
f := func(d int) {
dura := time.Duration(d) * 500 * time.Millisecond
//fmt.Printf("start dura: %s\n", dura)
ticker := w.NewTicker(dura)
var cnt uint
for {
cnt++
start := time.Now()
select {
case t := <-ticker.C:
end := time.Now()
//if math.Abs(float64(end.Sub(start)-dura)) > float64(5000*time.Microsecond) {
if math.Abs(float64(end.Sub(start)-dura)) > float64(500*time.Millisecond) && cnt > 1 {
fmt.Printf("[%s] %d execout %s %s - %s sub:%s\n", dura, cnt, t, end, start, end.Sub(start)-dura)
}
}
}
}
for i := 0; i < 1000000; i++ {
n := rand.Int31n(30)
for ; n == 0; {
n = rand.Int31n(30)
}
n += 20
go f(int(n))
}
c := make(chan os.Signal, 1)
signal.Notify(c,
syscall.SIGINT,
)
for {
s := <-c
switch s {
case syscall.SIGINT:
goto END_FOR
}
}
END_FOR:
w.Stop()
fmt.Println("quit")
}
|
[
3,
7
] |
package models
import (
"context"
"errors"
)
// Remind type
type Remind struct {
RemindID int
Content string
UserID string
}
// InsertRemind handle request to add a new remind to the db
func InsertRemind(userID string, content string) (Remind, error) {
insertSQLStatement := `
INSERT INTO reminds (content, user_id)
VALUES ($1, $2)
RETURNING remind_id;`
var remind Remind
row := db.QueryRow(insertSQLStatement, content, userID)
err := row.Scan(&remind.RemindID)
if err != nil {
return remind, err
}
remind.Content = content
remind.UserID = userID
return remind, nil
}
// GetUserLastRemind handle request to get the last reminder from the user
func GetUserLastRemind(userID string) (Remind, error) {
selectSQL := `
SELECT remind_id, content
FROM reminds
WHERE user_id=$1
ORDER BY remind_id DESC
LIMIT 1;`
var remind Remind
row := db.QueryRow(selectSQL, userID)
err := row.Scan(&remind.RemindID, &remind.Content)
if err != nil {
if remind.Content == "" {
return remind, errors.New("No remind found for this user")
}
return remind, err
}
remind.UserID = userID
return remind, nil
}
// GetUserReminds handle request to get reminds from the db
func GetUserReminds(ctx context.Context, userID string) ([]Remind, error) {
selectSQL := `
SELECT remind_id, content
FROM reminds
WHERE user_id=$1
ORDER BY remind_id ASC;`
var reminds []Remind
rows, err := db.QueryContext(ctx, selectSQL, userID)
if err != nil {
return reminds, err
}
for rows.Next() {
var remind Remind
if remindErr := rows.Scan(&remind.RemindID, &remind.Content); remindErr != nil {
return reminds, remindErr
}
remind.UserID = userID
reminds = append(reminds, remind)
}
if len(reminds) == 0 {
return reminds, errors.New("no reminds found for this user")
}
return reminds, nil
}
// DeleteRemind handle request to delete a remind from the db
func DeleteRemind(ctx context.Context, remindID string, userID string) error {
deleteSQL := `
DELETE
FROM reminds
WHERE remind_id = $1
AND user_id = $2;`
_, err := db.QueryContext(ctx, deleteSQL, remindID, userID)
if err != nil {
return err
}
return nil
}
|
[
6
] |
package repo
import (
"strconv"
"time"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"intelliq/app/common"
db "intelliq/app/config"
"intelliq/app/enums"
"intelliq/app/model"
)
type userRepository struct {
coll *mgo.Collection
}
//NewUserRepository repo struct
func NewUserRepository() *userRepository {
coll := db.GetCollection(db.COLL_USER)
if coll == nil {
return nil
}
return &userRepository{
coll,
}
}
func (repo *userRepository) Save(user *model.User) error {
defer db.CloseSession(repo.coll)
err := repo.coll.Insert(user)
return err
}
func (repo *userRepository) Update(user *model.User) error {
defer db.CloseSession(repo.coll)
selector := bson.M{"_id": user.UserID}
updator := bson.M{"$set": bson.M{"name": user.FullName, "gender": user.Gender,
"email": user.Email, "dob": user.DOB, "school": user.School,
"roles": user.Roles, "lastModifiedDate": user.LastModifiedDate}}
err := repo.coll.Update(selector, updator)
return err
}
func (repo *userRepository) UpdateRoles(user *model.User) error {
defer db.CloseSession(repo.coll)
selector := bson.M{"_id": user.UserID}
updator := bson.M{"$set": bson.M{"roles": user.Roles, "lastModifiedDate": user.LastModifiedDate}}
err := repo.coll.Update(selector, updator)
return err
}
func (repo *userRepository) UpdateMobilePwd(selectorField string,
updatorField string, selectorVal interface{}, updatorVal string) error {
defer db.CloseSession(repo.coll)
selector := bson.M{selectorField: selectorVal}
updator := bson.M{"$set": bson.M{updatorField: updatorVal, "lastModifiedDate": time.Now().UTC()}}
err := repo.coll.Update(selector, updator)
return err
}
func (repo *userRepository) FindAllSchoolAdmins(groupID bson.ObjectId) (model.Users, error) {
defer db.CloseSession(repo.coll)
var users model.Users
filter := bson.M{
"school.group._id": groupID,
"roles.roleType": enums.Role.SCHOOL,
}
cols := bson.M{"password": 0, "prevSchools": 0, "days": 0, "lastModifiedDate": 0}
err := repo.coll.Find(filter).Select(cols).All(&users)
if err != nil {
return nil, err
}
return users, nil
}
func (repo *userRepository) FindAllSchoolTeachers(schoolID bson.ObjectId,
roleType interface{}) (model.Users, error) {
defer db.CloseSession(repo.coll)
var users model.Users
var filter interface{}
if roleType == nil {
filter = bson.M{"school._id": schoolID}
} else {
filter = bson.M{"school._id": schoolID, "roles.roleType": roleType}
}
cols := bson.M{"password": 0, "prevSchools": 0, "days": 0, "lastModifiedDate": 0, "school": 0}
err := repo.coll.Find(filter).Select(cols).All(&users)
if err != nil {
return nil, err
}
return users, nil
}
func (repo *userRepository) FindAllteachersUnderReviewer(schoolID bson.ObjectId,
reviewerID bson.ObjectId) (model.Users, error) {
defer db.CloseSession(repo.coll)
var users model.Users
filter := bson.M{
"school._id": schoolID,
"roles.roleType": enums.Role.TEACHER,
"roles.std.subjects.reviewer._id": reviewerID,
}
cols := bson.M{"password": 0, "prevSchools": 0, "days": 0, "lastModifiedDate": 0, "school": 0}
err := repo.coll.Find(filter).Select(cols).All(&users)
if err != nil {
return nil, err
}
return users, nil
}
func (repo *userRepository) TransferRole(roleType enums.UserRole,
fromUserID bson.ObjectId, toUserID bson.ObjectId) (string, []string, error) {
defer db.CloseSession(repo.coll)
var users model.Users
fromUserFilter := bson.M{
"_id": fromUserID,
"roles.roleType": roleType,
}
toUserFilter := bson.M{
"_id": toUserID,
"roles.roleType": bson.M{"$ne": roleType},
}
orFilter := bson.M{"$or": []bson.M{
fromUserFilter,
toUserFilter,
},
}
cols := bson.M{"_id": 1, "roles": 1, "mobile": 1}
err := repo.coll.Find(orFilter).Select(cols).All(&users)
if err != nil {
return "", nil, err
}
count := len(users)
if count < 2 {
return common.MSG_INSUFFICIENT_USER_COUNT + strconv.Itoa(count), nil, nil
}
bulk := repo.coll.Bulk()
for _, user := range users {
if user.UserID == fromUserID { // remove the current role from role array
for index, role := range user.Roles {
if role.RoleType == roleType {
user.Roles = append(user.Roles[:index], //appends records before this point
user.Roles[index+1:]...) // appends records after this point
break
}
}
} else { //add new role to role array
user.Roles = append(user.Roles, model.Role{
RoleType: roleType,
})
}
user.LastModifiedDate = time.Now().UTC()
selector := bson.M{"_id": user.UserID}
updator := bson.M{"$set": bson.M{"roles": user.Roles,
"lastModifiedDate": user.LastModifiedDate}}
bulk.Update(selector, updator)
}
_, errs := bulk.Run()
if errs != nil {
return "", nil, errs
}
mobiles := []string{users[0].Mobile, users[1].Mobile}
return "", mobiles, nil
}
func (repo *userRepository) RemoveSchoolTeacher(schoolID bson.ObjectId,
userID bson.ObjectId) error {
defer db.CloseSession(repo.coll)
var user model.User
filter := bson.M{"_id": userID, "school._id": schoolID}
cols := bson.M{"_id": 1, "roles": 1, "school": 1, "prevSchools": 1}
err := repo.coll.Find(filter).Select(cols).One(&user)
if err != nil {
return err
}
user.School.PrevUserRoles = user.Roles
user.PrevSchools = append(user.PrevSchools, user.School)
user.School = model.School{}
user.Roles = nil
user.LastModifiedDate = time.Now().UTC()
selector := bson.M{"_id": user.UserID}
updator := bson.M{"$set": bson.M{"school": user.School, "prevSchools": user.PrevSchools,
"roles": user.Roles, "lastModifiedDate": user.LastModifiedDate}}
errs := repo.coll.Update(selector, updator)
if errs != nil {
return err
}
return nil
}
func (repo *userRepository) BulkSave(users []interface{}) error {
defer db.CloseSession(repo.coll)
bulk := repo.coll.Bulk()
bulk.Insert(users...)
_, err := bulk.Run()
if err != nil {
return err
}
return nil
}
func (repo *userRepository) BulkUpdate(users model.Users) error {
defer db.CloseSession(repo.coll)
bulk := repo.coll.Bulk()
for _, user := range users {
selector := bson.M{"_id": user.UserID}
// updator := bson.M{"$set": bson.M{"roles": user.Roles, "lastModifiedDate": time.Now().UTC()}}
bulk.Update(selector, user)
}
_, err := bulk.Run()
if err != nil {
return err
}
return nil
}
func (repo *userRepository) FindOne(key string, val interface{}) (*model.User, error) {
defer db.CloseSession(repo.coll)
var user model.User
filter := bson.M{
key: val,
}
err := repo.coll.Find(filter).One(&user)
if err != nil {
return nil, err
}
return &user, nil
}
func (repo *userRepository) FindOneFromSchool(key string, val interface{},
schoolID bson.ObjectId) (*model.User, error) {
defer db.CloseSession(repo.coll)
var user model.User
filter := bson.M{
key: val,
"school._id": schoolID,
}
err := repo.coll.Find(filter).One(&user)
if err != nil {
return nil, err
}
return &user, nil
}
func (repo *userRepository) UpdateSchedule(user *model.User) error {
defer db.CloseSession(repo.coll)
selector := bson.M{"_id": user.UserID}
updator := bson.M{"$set": bson.M{"days": user.Days}}
err := repo.coll.Update(selector, updator)
return err
}
|
[
3,
6
] |
package dbdb
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"sync/atomic"
)
type StoreStat struct {
Name string
Id, Docs uint64
Size float64
}
type StoreStatSorted []*StoreStat
func (sss StoreStatSorted) Len() int {
return len(sss)
}
func (sss StoreStatSorted) Less(i, j int) bool {
return sss[i].Name < sss[j].Name
}
func (sss StoreStatSorted) Swap(i, j int) {
sss[i], sss[j] = sss[j], sss[i]
}
type Store struct {
Name string
StoreId uint64
Docs *DocMap
}
func NewStore(Name string) *Store {
return &Store{
Name: Name,
Docs: NewDocMap(),
}
}
func (st *Store) Load(ids []int) {
var docid uint64
for _, id := range ids {
docid = uint64(id)
file := fmt.Sprintf("db/%s/%d.json", st.Name, docid)
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatalf("Store.Load() -> invalid file (%v), possible corruption?\n", file)
}
var doc Doc
if err := json.Unmarshal(data, &doc); err != nil {
log.Fatalf("Store.Load() -> error unmarshaling data from file (%v), possible corruption?\n", file)
}
st.Docs.Set(docid, &doc)
}
st.StoreId = docid
}
// size on disk, not document count
func (st *Store) Size() float64 {
var size int64
for i := 1; uint64(i) < st.StoreId; i++ {
if info, err := os.Lstat(fmt.Sprintf("db/%s/%d.json", st.Name, i)); err == nil {
size += info.Size()
}
}
return toFixed(float64(size)/float64(1<<10), 2)
}
func (st *Store) Add(val interface{}) uint64 {
StoreId := atomic.AddUint64(&st.StoreId, uint64(1))
doc := NewDoc(StoreId, val)
st.Docs.Set(StoreId, doc)
func() {
WriteDoc(fmt.Sprintf("db/%s/%d.json", st.Name, StoreId), doc)
}()
return StoreId
}
func (st *Store) Set(id uint64, val interface{}) {
if doc, ok := st.Docs.Get(id); ok {
doc.Update(val)
st.Docs.Set(id, doc)
func() {
WriteDoc(fmt.Sprintf("db/%s/%d.json", st.Name, id), doc)
}()
}
}
func (st *Store) Has(id uint64) bool {
_, ok := st.Docs.Get(id)
return ok
}
func (st *Store) Get(id uint64) *Doc {
if doc, ok := st.Docs.Get(id); ok {
return doc
}
return nil
}
func (st *Store) GetAll(id ...uint64) DocSorted {
if len(id) == 0 {
return st.Docs.GetAll()
}
var docs DocSorted
for _, docid := range id {
if doc, ok := st.Docs.Get(docid); ok {
docs = append(docs, doc)
}
}
sort.Sort(docs)
return docs
}
func (st *Store) Del(id uint64) {
st.Docs.Del(id)
func() {
DeleteDoc(fmt.Sprintf("db/%s/%d.json", st.Name, id))
}()
}
func (st *Store) Query(comps ...QueryComp) DocSorted {
return st.Docs.Query(comps...)
}
|
[
2
] |
package main
import "fmt"
func main() {
arr:=[]int{2,1,3,7,8,5,-1,20,9,0}
arr=mapFunc(f10,arr)
fmt.Println(arr)
}
/*
str:="abcdefg"
s:=str[len(str)/2:] + str[:len(str)/2] //defgabc
fmt.Println(str[0])
*/
//函数练习
//1.编写一个函数,要求其接受两个参数,原始字符串 str 和分割索引 i,然后返回两个分割后的字符串
func split( str string, i int )(string,string) {
return str[:i],str[i:]
}
//2.编写一个函数反转字符串
func reverse(str string)string{
rs:="";
var i int =len(str)-1;
for ; i>=0;i-- {
rs=rs+string(str[i])
}
return string(rs)
}
//3.编写一个程序,要求能够遍历一个数组的字符,并将当前字符和前一个字符不相同的字符拷贝至另一个数组
func findDiffstr(strarr []byte) ([]byte) {
var before byte=0;
var newarr []byte;
for _,v:=range strarr{
if(v!=before && before!=0){
newarr=append(newarr,v)
}
before=v;
}
return newarr
}
//4.编写一个程序,使用冒泡排序的方法排序一个包含整数的切片
func sort_budding(arr []int)([]int) {
len:=len(arr)
for i:=0;i<len-1 ;i++ {
for j:=i+1;j<len ; j++ {
if(arr[j]<arr[i]){
tmp:=arr[i]
arr[i]=arr[j]
arr[j]=tmp
}
}
}
return arr
}
/*
5 编写一个函数 mapFunc 要求接受以下 2 个参数:
一个将整数乘以 10 的函数
一个整数列表
最后返回保存运行结果的整数列表
*/
func f10(num int)int {
return num*10
}
func mapFunc(f func(int)int,arr []int )([]int) {
for i,v:=range arr{
arr[i]=f(v)
}
return arr
}
|
[
0,
3
] |
package xprop
import (
"fmt"
"github.com/robotn/xgb"
"github.com/robotn/xgb/xproto"
"github.com/robotn/xgbutil"
)
// GetProperty abstracts the messiness of calling xgb.GetProperty.
func GetProperty(xu *xgbutil.XUtil, win xproto.Window, atom string) (
*xproto.GetPropertyReply, error) {
atomId, err := Atm(xu, atom)
if err != nil {
return nil, err
}
reply, err := xproto.GetProperty(xu.Conn(), false, win, atomId,
xproto.GetPropertyTypeAny, 0, (1<<32)-1).Reply()
if err != nil {
return nil, fmt.Errorf("GetProperty: Error retrieving property '%s' "+
"on window %x: %s", atom, win, err)
}
if reply.Format == 0 {
return nil, fmt.Errorf("GetProperty: No such property '%s' on "+
"window %x.", atom, win)
}
return reply, nil
}
// ChangeProperty abstracts the semi-nastiness of xgb.ChangeProperty.
func ChangeProp(xu *xgbutil.XUtil, win xproto.Window, format byte, prop string,
typ string, data []byte) error {
propAtom, err := Atm(xu, prop)
if err != nil {
return err
}
typAtom, err := Atm(xu, typ)
if err != nil {
return err
}
return xproto.ChangePropertyChecked(xu.Conn(), xproto.PropModeReplace, win,
propAtom, typAtom, format,
uint32(len(data)/(int(format)/8)), data).Check()
}
// ChangeProperty32 makes changing 32 bit formatted properties easier
// by constructing the raw X data for you.
func ChangeProp32(xu *xgbutil.XUtil, win xproto.Window, prop string, typ string,
data ...uint) error {
buf := make([]byte, len(data)*4)
for i, datum := range data {
xgb.Put32(buf[(i*4):], uint32(datum))
}
return ChangeProp(xu, win, 32, prop, typ, buf)
}
// WindowToUint is a covenience function for converting []xproto.Window
// to []uint.
func WindowToInt(ids []xproto.Window) []uint {
ids32 := make([]uint, len(ids))
for i, v := range ids {
ids32[i] = uint(v)
}
return ids32
}
// AtomToInt is a covenience function for converting []xproto.Atom
// to []uint.
func AtomToUint(ids []xproto.Atom) []uint {
ids32 := make([]uint, len(ids))
for i, v := range ids {
ids32[i] = uint(v)
}
return ids32
}
// StrToAtoms is a convenience function for converting
// []string to []uint32 atoms.
// NOTE: If an atom name in the list doesn't exist, it will be created.
func StrToAtoms(xu *xgbutil.XUtil, atomNames []string) ([]uint, error) {
var err error
atoms := make([]uint, len(atomNames))
for i, atomName := range atomNames {
a, err := Atom(xu, atomName, false)
if err != nil {
return nil, err
}
atoms[i] = uint(a)
}
return atoms, err
}
// PropValAtom transforms a GetPropertyReply struct into an ATOM name.
// The property reply must be in 32 bit format.
func PropValAtom(xu *xgbutil.XUtil, reply *xproto.GetPropertyReply,
err error) (string, error) {
if err != nil {
return "", err
}
if reply.Format != 32 {
return "", fmt.Errorf("PropValAtom: Expected format 32 but got %d",
reply.Format)
}
return AtomName(xu, xproto.Atom(xgb.Get32(reply.Value)))
}
// PropValAtoms is the same as PropValAtom, except that it returns a slice
// of atom names. Also must be 32 bit format.
// This is a method of an XUtil struct, unlike the other 'PropVal...' functions.
func PropValAtoms(xu *xgbutil.XUtil, reply *xproto.GetPropertyReply,
err error) ([]string, error) {
if err != nil {
return nil, err
}
if reply.Format != 32 {
return nil, fmt.Errorf("PropValAtoms: Expected format 32 but got %d",
reply.Format)
}
ids := make([]string, reply.ValueLen)
vals := reply.Value
for i := 0; len(vals) >= 4; i++ {
ids[i], err = AtomName(xu, xproto.Atom(xgb.Get32(vals)))
if err != nil {
return nil, err
}
vals = vals[4:]
}
return ids, nil
}
// PropValWindow transforms a GetPropertyReply struct into an X resource
// window identifier.
// The property reply must be in 32 bit format.
func PropValWindow(reply *xproto.GetPropertyReply,
err error) (xproto.Window, error) {
if err != nil {
return 0, err
}
if reply.Format != 32 {
return 0, fmt.Errorf("PropValId: Expected format 32 but got %d",
reply.Format)
}
return xproto.Window(xgb.Get32(reply.Value)), nil
}
// PropValWindows is the same as PropValWindow, except that it returns a slice
// of identifiers. Also must be 32 bit format.
func PropValWindows(reply *xproto.GetPropertyReply,
err error) ([]xproto.Window, error) {
if err != nil {
return nil, err
}
if reply.Format != 32 {
return nil, fmt.Errorf("PropValIds: Expected format 32 but got %d",
reply.Format)
}
ids := make([]xproto.Window, reply.ValueLen)
vals := reply.Value
for i := 0; len(vals) >= 4; i++ {
ids[i] = xproto.Window(xgb.Get32(vals))
vals = vals[4:]
}
return ids, nil
}
// PropValNum transforms a GetPropertyReply struct into an unsigned
// integer. Useful when the property value is a single integer.
func PropValNum(reply *xproto.GetPropertyReply, err error) (uint, error) {
if err != nil {
return 0, err
}
if reply.Format != 32 {
return 0, fmt.Errorf("PropValNum: Expected format 32 but got %d",
reply.Format)
}
return uint(xgb.Get32(reply.Value)), nil
}
// PropValNums is the same as PropValNum, except that it returns a slice
// of integers. Also must be 32 bit format.
func PropValNums(reply *xproto.GetPropertyReply, err error) ([]uint, error) {
if err != nil {
return nil, err
}
if reply.Format != 32 {
return nil, fmt.Errorf("PropValIds: Expected format 32 but got %d",
reply.Format)
}
nums := make([]uint, reply.ValueLen)
vals := reply.Value
for i := 0; len(vals) >= 4; i++ {
nums[i] = uint(xgb.Get32(vals))
vals = vals[4:]
}
return nums, nil
}
// PropValNum64 transforms a GetPropertyReply struct into a 64 bit
// integer. Useful when the property value is a single integer.
func PropValNum64(reply *xproto.GetPropertyReply, err error) (int64, error) {
if err != nil {
return 0, err
}
if reply.Format != 32 {
return 0, fmt.Errorf("PropValNum: Expected format 32 but got %d",
reply.Format)
}
return int64(xgb.Get32(reply.Value)), nil
}
// PropValStr transforms a GetPropertyReply struct into a string.
// Useful when the property value is a null terminated string represented
// by integers. Also must be 8 bit format.
func PropValStr(reply *xproto.GetPropertyReply, err error) (string, error) {
if err != nil {
return "", err
}
if reply.Format != 8 {
return "", fmt.Errorf("PropValStr: Expected format 8 but got %d",
reply.Format)
}
return string(reply.Value), nil
}
// PropValStrs is the same as PropValStr, except that it returns a slice
// of strings. The raw byte string is a sequence of null terminated strings,
// which is translated into a slice of strings.
func PropValStrs(reply *xproto.GetPropertyReply, err error) ([]string, error) {
if err != nil {
return nil, err
}
if reply.Format != 8 {
return nil, fmt.Errorf("PropValStrs: Expected format 8 but got %d",
reply.Format)
}
var strs []string
sstart := 0
for i, c := range reply.Value {
if c == 0 {
strs = append(strs, string(reply.Value[sstart:i]))
sstart = i + 1
}
}
if sstart < int(reply.ValueLen) {
strs = append(strs, string(reply.Value[sstart:]))
}
return strs, nil
}
|
[
6
] |
package main
import "fmt"
func main() {
var l = []int{7, 1, 5, 3, 6, 4}
fmt.Println(maxProfit2(l))
}
//贪心算法
func maxProfit2(prices []int) int {
// 设置当前收益为0
var max = 0
//假设从第二天开始买入,
for i := 1; i <= len(prices); i++ {
//当天价格高于前一天,就卖掉
if prices[i] > prices[i-1] {
max += prices[i] - prices[i-1]
}
}
return max
}
|
[
1,
3
] |
package btreeinstance
import (
"github.com/google/btree"
"strconv"
)
type Uint64 uint64
// Less returns true if uint64(a) < uint64(b).
func (a Uint64) Less(b btree.Item) bool {
return a < b.(Uint64)
}
type String string
// Less returns true if int(a) < int(b).
func (a String) Less(b btree.Item) bool {
return a < b.(String)
}
type DentryKV struct {
K string
V []byte
}
func (a DentryKV) Less(b btree.Item) bool {
return a.K < b.(DentryKV).K
}
type InodeKV struct {
K uint64
V []byte
}
func (a InodeKV) Less(b btree.Item) bool {
return a.K < b.(InodeKV).K
}
type BGKV struct {
K uint64
V []byte
}
func (a BGKV) Less(b btree.Item) bool {
return a.K < b.(BGKV).K
}
// -------- Cluster btrees ---------------
//for datanode
type DataNodeKV struct {
K string
V []byte
}
func (a DataNodeKV) Less(b btree.Item) bool {
return a.K < b.(DataNodeKV).K
}
//for datanodebgp
type DataNodeBGPKV struct {
K string
V []byte
}
func (a DataNodeBGPKV) Less(b btree.Item) bool {
return a.K < b.(DataNodeBGPKV).K
}
//for meatanode
type MetaNodeKV struct {
K uint64
V []byte
}
func (a MetaNodeKV) Less(b btree.Item) bool {
return a.K < b.(MetaNodeKV).K
}
//for volume blockgroup
type BlockGroupKV struct {
K uint64
V []byte
}
func (a BlockGroupKV) Less(b btree.Item) bool {
return a.K < b.(BlockGroupKV).K
}
//for MetaNode RaftGroup
type MNRGKV struct {
K uint64
V []byte
}
func (a MNRGKV) Less(b btree.Item) bool {
return a.K < b.(MNRGKV).K
}
//for volume info
type VOLKV struct {
K string
V []byte
}
func (a VOLKV) Less(b btree.Item) bool {
return a.K < b.(VOLKV).K
}
//to implement kv interface for snapshot
func (a DataNodeKV) Key() string {
return a.K
}
func (a DataNodeKV) Value() []byte {
return a.V
}
func (a DataNodeBGPKV) Key() string {
return a.Key()
}
func (a DataNodeBGPKV) Value() []byte {
return a.V
}
func (a MetaNodeKV) Key() string {
return strconv.FormatUint(a.K, 10)
}
func (a MetaNodeKV) Value() []byte {
return a.V
}
func (a BlockGroupKV) Key() string {
return strconv.FormatUint(a.K, 10)
}
func (a BlockGroupKV) Value() []byte {
return a.V
}
func (a MNRGKV) Key() string {
return strconv.FormatUint(a.K, 10)
}
func (a MNRGKV) Value() []byte {
return a.V
}
func (a VOLKV) Key() string {
return a.K
}
func (a VOLKV) Value() []byte {
return a.V
}
|
[
3
] |
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"log"
"net"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/ajstarks/openvg"
touchscreen "github.com/electrocatstudios/FTXXXX_Touchscreen_Driver"
"github.com/electrocatstudios/PiMenu/screenservice"
"google.golang.org/grpc"
)
var cur_screen = "main"
var imageCache PMImageCache
var interruptScreen InterruptScreen
func GetImageWithOpacity(img image.Image, opacity uint8) image.Image {
m := image.NewRGBA(img.Bounds())
mask := image.NewUniform(color.Alpha{opacity})
draw.DrawMask(m, m.Bounds(), img, image.Point{0, 0}, mask, image.Point{0, 0}, draw.Over)
return m
}
func DrawLine(s ScreenDetails, dl DisplayLine, offset openvg.VGfloat, opacity *uint8) {
if dl.Type == "null" || dl.Type == "" {
// Nothing to do here - just leave blank
return
} else if dl.Type == "text" {
if dl.Color != "" {
openvg.FillColor(dl.Color)
} else {
openvg.FillColor("rgb(255,255,255)")
}
openvg.TextMid(s.W2, offset, dl.Value, "sans", 30)
} else if dl.Type == "data" {
if dl.Value == "IMAGESERVER" {
interruptScreen.Lock.Lock()
if interruptScreen.IncomingImage != nil {
img := (*interruptScreen.IncomingImage)
left := openvg.VGfloat(0)
top := openvg.VGfloat(0)
openvg.Img(left, top, img)
} else {
openvg.TextMid(s.W2, 200, "No Image available", "sans", 30)
}
interruptScreen.Lock.Unlock()
} else {
if dl.Color != "" {
openvg.FillColor(dl.Color)
} else {
openvg.FillColor("rgb(255,255,255)")
}
dataString := GetDataString(dl.Value)
openvg.TextMid(s.W2, offset, dataString, "sans", 30)
}
} else if dl.Type == "image" {
img, err := GetImageFromString(dl.Value)
if err != nil {
fmt.Println(err)
return
}
force_height := s.Height
if img.Height != 0 {
force_height = img.Height
}
image_file, err := imageCache.GetImage(img.Filename, 0, force_height)
if err != nil {
fmt.Println(err)
return
}
left := openvg.VGfloat(0)
top := openvg.VGfloat(img.Y)
if img.X != 0 {
// We aren't centering this one - use given x val
left = openvg.VGfloat(img.X)
} else {
// Center the image
image_width := openvg.VGfloat(image_file.Bounds().Max.X)
left = openvg.VGfloat(s.W2 - (image_width / 2))
}
if opacity != nil && *opacity >= uint8(5) {
img_op := GetImageWithOpacity(image_file, *opacity)
openvg.Img(left, top, img_op)
} else if opacity != nil && *opacity < uint8(5) {
// Don't draw if less than 5 opacity - should be nearly invisible
} else {
openvg.Img(left, top, image_file)
}
} else if dl.Type == "gif" {
img, err := GetImageFromString(dl.Value)
if err != nil {
fmt.Println(err)
return
}
frame, err := imageCache.GetGifFrame(img.Filename, s)
// Center the gif
left := s.W2 - openvg.VGfloat((frame.Bounds().Max.X / 2))
top := openvg.VGfloat((s.Height / 2) - (frame.Bounds().Max.Y / 2))
if img.X != 0 {
left = openvg.VGfloat(img.X)
}
if img.Y != 0 {
top = openvg.VGfloat(img.Y)
}
openvg.Img(left, top, frame)
}
}
func RunCommand(cmd string, wait bool) error {
cmd_items := strings.Split(cmd, " ")
cmd_exec := exec.Command(cmd_items[0], strings.Join(cmd_items[1:], " "))
err := cmd_exec.Start()
if err != nil {
fmt.Printf("Failed to start command : %s\n", err)
return err
}
if wait {
err = cmd_exec.Wait()
if err != nil {
fmt.Printf("Failed to execute command: %s\n", err)
}
}
return err
}
func HandleTouches(t *touchscreen.TouchScreen, input Screen, defaultScreen string) (string, *uint8) {
numTouches, err := t.GetTouchesCount()
if err != nil {
fmt.Println(err)
return defaultScreen, nil
}
if numTouches < 1 {
if input.Timeout.Length == 0 {
// We don't have a time out so just return
return defaultScreen, nil
}
// See if we have timed out since last touch
curTime := time.Now()
diff := curTime.Sub(t.LastScreenChange).Seconds()
remain := float64(input.Timeout.Length) - diff
if int(remain) < 0 {
t.LastScreenChange = time.Now()
// We have timed out so return to previous screen
ret_op := uint8(0)
return input.Timeout.ReturnScreen, &ret_op
}
if remain < float64(input.Timeout.ShowCountDown) && input.Timeout.ShowCountDown != 0 {
seconds_remain := strconv.FormatInt(int64(remain), 10)
seconds_remain += "s"
openvg.FillColor("rgb(255,255,255)")
openvg.Text(10, 420, seconds_remain, "sans", 30)
}
// Apply opacity if appropriate
if input.Background.FadeOut && remain < 0 {
// Opacity should be zero while we load the new screen
opacity := uint8(0)
return defaultScreen, &opacity
} else if remain < 1 && input.Background.FadeOut {
opacity := uint8(255 * remain)
return defaultScreen, &opacity
} else if diff < 1 && input.Background.FadeIn {
opacity := uint8(255 * diff)
return defaultScreen, &opacity
} else {
return defaultScreen, nil
}
}
t.LastScreenChange = time.Now()
touch, _ := t.GetTouches()
for i := 0; i < len(input.Touches); i++ {
hitBox := input.Touches[i]
if touch.X > hitBox.X && touch.X < hitBox.X+hitBox.Width {
if touch.Y > hitBox.Y && touch.Y < hitBox.Y+hitBox.Height {
if hitBox.Command.Type == "menu" {
return hitBox.Command.Value, nil
} else if hitBox.Command.Type == "command" {
err := RunCommand(hitBox.Command.Value, false)
if err != nil {
return defaultScreen, nil
}
if hitBox.Command.ReturnScreen != "" {
return hitBox.Command.ReturnScreen, nil
} else {
return defaultScreen, nil
}
}
}
}
}
return defaultScreen, nil
}
/*return new screen based on touches if appropriate*/
func DrawScreen(t *touchscreen.TouchScreen, name string, input Screen, s ScreenDetails) string {
openvg.Start(s.Width, s.Height) // Start the picture
if input.Background.Color != "" {
openvg.BackgroundColor(input.Background.Color)
} else {
openvg.BackgroundColor("black")
}
ret, opacity := HandleTouches(t, input, name)
// Default fill color
openvg.FillColor("rgb(255,255,255)") // White text
DrawLine(s, input.Line1, 400, opacity)
DrawLine(s, input.Line2, 320, opacity)
DrawLine(s, input.Line3, 240, opacity)
DrawLine(s, input.Line4, 160, opacity)
DrawLine(s, input.Line5, 80, opacity)
openvg.End()
return ret
}
func monitorService(s *screenservice.Server) {
// Listen for incoming screens on the buffer
for {
if s.NumScreens() != 0 {
screen := s.GetScreen()
newScreen := GetScreenFromScreenRequest(screen)
interruptScreen.Lock.Lock()
if len(interruptScreen.Screens) == 0 {
interruptScreen.LastShown = time.Now()
}
interruptScreen.Screens = append(interruptScreen.Screens, newScreen)
interruptScreen.Lock.Unlock()
}
if s.HasImage() {
img := s.GetImage()
interruptScreen.Lock.Lock()
interruptScreen.IncomingImage = img
interruptScreen.Lock.Unlock()
s.RemoveImage()
}
time.Sleep(100 * time.Millisecond)
}
}
func runInterruptServer() {
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", 7777))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := screenservice.Server{}
grpcServer := grpc.NewServer()
go monitorService(&s)
screenservice.RegisterScreenServerServer(grpcServer, &s)
// start the server
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %s", err)
}
}
func CheckFolders() bool {
// Check if screens and images folders exist - offer to download default screens
folder := "screens"
if _, err := os.Stat(folder); os.IsNotExist(err) {
return false
}
folder = "images"
if _, err := os.Stat(folder); os.IsNotExist(err) {
return false
}
return true
}
func main() {
fmt.Println("Starting Screen App")
var screenDetails ScreenDetails
screenDetails.Width, screenDetails.Height = openvg.Init()
screenDetails.W2 = openvg.VGfloat(screenDetails.Width / 2) // this is to center lines of text
t := touchscreen.TouchScreen{}
t.Init(touchscreen.FT62XX)
t.Debug = true
bFoldersExist := CheckFolders()
if !bFoldersExist {
// Note this is a blocking call - nothing else will be available
RunFirstTimeScreen(screenDetails, &t)
return
}
go runInterruptServer()
var prevscreen string
var screen Screen
var err error
for {
bFoundInterrupt := false
interruptScreen.Lock.Lock()
if len(interruptScreen.Screens) > 0 {
bFoundInterrupt = true
DrawScreen(&t, "interrupt", interruptScreen.Screens[0], screenDetails)
curTime := time.Now()
diff := curTime.Sub(interruptScreen.LastShown).Seconds()
if int(diff) > interruptScreen.Screens[0].Timeout.Length {
interruptScreen.Screens = interruptScreen.Screens[1:]
interruptScreen.LastShown = time.Now()
}
}
interruptScreen.Lock.Unlock()
if bFoundInterrupt {
continue
}
if cur_screen != prevscreen {
screen, err = GetScreenByName(cur_screen)
if err != nil {
panic(err)
}
prevscreen = cur_screen
}
cur_screen = DrawScreen(&t, cur_screen, screen, screenDetails)
time.Sleep(5 * time.Millisecond)
}
}
|
[
5
] |
package controllers
import (
"encoding/json"
"fmt"
"github.com/swfsql/estagio/models"
)
// ERRS
var (
st_err_jsoninvalido string = "err_jsoninvalido"
st_err_rajaexistente string = "err_rajaexistente"
st_err_cursonaoexistente string = "err_cursonaoexistente"
)
type AdminController struct {
AuthAdminController
}
func (this *AdminController) Nucleo() {
sess := this.StartSession()
conta := sess.Get("conta").(models.Conta)
fmt.Println("ENTROU NA PAGINA DO Admin")
this.Data["Usuario"] = conta.Pessoa
this.Data["CursosSiglas"], _ = models.GetCursosSiglas()
fmt.Println(conta.Pessoa.Privilegio)
fmt.Println(conta.Pessoa.Nome)
this.TplName = "admin.html"
this.All()
this.Render()
}
func (this *AdminController) AdiquirirDados() {
alunos, _ := models.GetAlunos()
professores, _ := models.GetProfessores()
dado := struct {
Alunos []*models.Aluno
Professores []*models.Professor
}{alunos, professores}
this.Data["json"] = dado
this.ServeJSON()
}
func (this *AdminController) CadastroDiscente() {
dado := struct {
Ra uint64
Nome string
Email string
Curso string
Telefone string
Periodo uint64
CargaHoraria uint64
}{}
wjson := struct {
St string
}{""}
err := json.Unmarshal(this.Ctx.Input.RequestBody, &dado)
if err != nil {
fmt.Println(err)
//this.Ctx.Output.SetStatus(400)
//this.Ctx.Output.Body([]byte("JSON invalido"))
wjson.St = st_err_jsoninvalido
this.Data["json"] = wjson
this.ServeJSON()
return
}
fmt.Println(dado)
_, err_noRow := models.GetAlunoByRa(dado.Ra)
if err_noRow == nil {
fmt.Println(st_err_rajaexistente)
wjson.St = st_err_rajaexistente
this.Data["json"] = wjson
this.ServeJSON()
return
}
var curso models.Curso
curso, err_noRow = models.GetCursoBySigla(dado.Curso)
if err_noRow != nil {
fmt.Println(st_err_cursonaoexistente)
wjson.St = st_err_cursonaoexistente
this.Data["json"] = wjson
this.ServeJSON()
return
}
pessoa := &models.Pessoa{Conta: nil, Nome: dado.Nome, Telefone: dado.Telefone, Email: dado.Email, Privilegio: 2}
conta := &models.Conta{Pessoa: pessoa, Usuario: dado.Email, Senha: dado.Nome + "_"}
pessoa.Conta = conta
aluno := &models.Aluno{Conta: conta, Ra: dado.Ra, Curso: &curso, Periodo: dado.Periodo, CargaHoraria: dado.CargaHoraria}
models.CadastroAluno(aluno)
fmt.Println(st_ok)
wjson.St = st_ok
this.Data["json"] = wjson
this.ServeJSON()
return
}
|
[
3
] |
/*
I try to change this problem to a BFS problem, where nodes in level i are all
the nodes that can be reached in i-1th jump.
for example. {2 3 1 1 4}, is
2
3 1
1 4
*/
package main
import "fmt"
func max(x int, y int) int {
if x > y {
return x
} else {
return y
}
}
func jump(nums []int) int {
if len(nums) <= 1 {
return 0
}
bound := nums[0] // current level bound
farest := nums[0] // farest bound for next level
level := 1 // current level
for i := 1; i < len(nums); i++ {
if i > bound {
bound = farest
farest = max(farest, i+nums[i])
level++
} else {
farest = max(farest, i+nums[i])
}
}
return level
}
func main() {
fmt.Println(jump([]int{2, 3, 1, 1, 4}))
fmt.Println(jump([]int{2, 3, 1, 1}))
fmt.Println(jump([]int{4, 3, 3, 1, 1, 2, 3, 4, 3}))
}
|
[
6
] |
package main
import (
_ "Go_Learn/GoWeb开发实战_Beego框架实现项目/07myblogweb/routers"
"Go_Learn/GoWeb开发实战_Beego框架实现项目/07myblogweb/utils"
"github.com/astaxie/beego"
)
func main() {
utils.InitMysql()
//beego.BConfig.WebConfig.Session.SessionOn = true // 打开session 或者 在app.conf配置文件处写上sessionon = true
beego.Run()
}
|
[
3
] |
package main
import (
"fmt"
)
func main() {
m := make(map[interface{}]interface{})
m["branches"] = "13123"
m2 := make(map[interface{}]interface{})
m2["clsd"] = "asda"
m2["clsd2"] = "asda2"
m["steps"] = map[interface{}]interface{}{"bind_id": m2,}
//m["steps"]["aaa
mm, ok := m["steps"].(map[interface{}]interface{})
if ok {
//mm = make(map[string]string)
mm["b2"] = m2
fmt.Println(mm)
}
fmt.Println(m)
//m["steps"]["bind_id"]="qqq"
// Vargs: map[string]interface{}{"bind_id": k8s_deploy_id,
// "cluster": k8s_deploy.ClusterName,
// "tags": "latest",
// "template": path,
// },
//qq := m["steps"]
//qq["a1"] = "1111"
//map[branches:[master] steps:map[docker2:map[image:crun/kube cluster:testkube namespace:default tags:latest template:deployment.yaml]]]
fmt.Println(m)
}
|
[
3
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.