text stringlengths 11 4.05M |
|---|
package middlewares
type DefaultMiddleware struct {
}
|
package pkg2
import "fmt"
func Demo2() {
fmt.Println("demo2")
}
func init() {
fmt.Println("init2")
}
|
package registrar
import (
"log"
"github.com/pivotal-cf/on-demand-service-broker/cf"
"github.com/pivotal-cf/on-demand-service-broker/config"
"github.com/pkg/errors"
)
type RegisterBrokerRunner struct {
Config config.RegisterBrokerErrandConfig
CFClient RegisterBrokerCFClient
Logger *log.Logger
}
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
//counterfeiter:generate -o fakes/register_broker_cf_client.go . RegisterBrokerCFClient
type RegisterBrokerCFClient interface {
ServiceBrokers() ([]cf.ServiceBroker, error)
CreateServiceBroker(name, username, password, url string) error
UpdateServiceBroker(guid, name, username, password, url string) error
EnableServiceAccess(serviceOfferingID, planName string, logger *log.Logger) error
DisableServiceAccess(serviceOfferingID, planName string, logger *log.Logger) error
CreateServicePlanVisibility(orgName, serviceOfferingID, planName string, logger *log.Logger) error
}
const executionError = "failed to execute register-broker"
func (r *RegisterBrokerRunner) Run() error {
existingBrokers, err := r.CFClient.ServiceBrokers()
if err != nil {
return errors.Wrap(err, executionError)
}
if err := r.createOrUpdateBroker(existingBrokers); err != nil {
return errors.Wrap(err, executionError)
}
for _, plan := range r.Config.Plans {
if plan.CFServiceAccess == config.PlanEnabled {
err = r.CFClient.EnableServiceAccess(r.Config.ServiceOfferingID, plan.Name, r.Logger)
} else {
err = r.CFClient.DisableServiceAccess(r.Config.ServiceOfferingID, plan.Name, r.Logger)
}
if err != nil {
return errors.Wrap(err, executionError)
}
if plan.CFServiceAccess == config.PlanOrgRestricted {
err = r.CFClient.CreateServicePlanVisibility(plan.ServiceAccessOrg, r.Config.ServiceOfferingID, plan.Name, r.Logger)
if err != nil {
return errors.Wrap(err, executionError)
}
}
}
return nil
}
func (r *RegisterBrokerRunner) createOrUpdateBroker(existingBrokers []cf.ServiceBroker) error {
if brokerGUID, found := r.findBroker(existingBrokers); found {
return r.CFClient.UpdateServiceBroker(brokerGUID, r.Config.BrokerName, r.Config.BrokerUsername, r.Config.BrokerPassword, r.Config.BrokerURL)
}
return r.CFClient.CreateServiceBroker(r.Config.BrokerName, r.Config.BrokerUsername, r.Config.BrokerPassword, r.Config.BrokerURL)
}
func (r *RegisterBrokerRunner) findBroker(brokers []cf.ServiceBroker) (string, bool) {
for _, broker := range brokers {
if broker.Name == r.Config.BrokerName {
return broker.GUID, true
}
}
return "", false
}
|
package resiver
import (
"errors"
"sync"
)
type Manager struct {
mu sync.RWMutex
resivers map[string]*ResiversRuntime
}
func (m *Manager) Add(resiver *Resiver) error {
if _, ok := m.resivers[resiver.Name()]; !ok {
return errors.New("Resiver is already exist")
}
m.mu.Lock()
m.resivers[resiver.Name()] = NewResiversRuntime(resiver)
m.mu.Unlock()
return nil
}
func (m *Manager) StartResiver(resiver *Resiver) error {
runtime := m.getRuntime(resiver)
if runtime == nil {
return errors.New("Resiver is not found")
}
runtime.Start()
return nil
}
func (m *Manager) StartAllResivers() error {
for _, runtime := range m.resivers {
err := m.StartResiver(runtime.GetResiver())
if err != nil {
return err
}
}
return nil
}
func (m *Manager) GetResivers() ([]*Resiver, error) {
return nil, nil
}
func (m *Manager) getRuntime(resiver *Resiver) *ResiversRuntime {
runtime, ok := m.resivers[resiver.Name()]
if !ok {
return nil
}
return runtime
}
type ResiversRuntime struct {
resiver *Resiver
dataHandler *DataHandler
}
func NewResiversRuntime(resiver *Resiver) *ResiversRuntime {
dataHandler := NewDataHandler(resiver)
return &ResiversRuntime{
resiver: resiver,
dataHandler: dataHandler,
}
}
func (rr *ResiversRuntime) Start() error {
return rr.dataHandler.Start()
}
func (rr *ResiversRuntime) Stop() error {
return rr.dataHandler.Stop()
}
func (rr *ResiversRuntime) GetResiver() *Resiver {
return rr.resiver
}
|
package handlers
import (
"github.com/hashicorp/go-hclog"
"github.com/jinzhu/gorm"
"github.com/milutindzunic/pac-backend/data"
"github.com/milutindzunic/pac-backend/database"
"net/http"
)
type DBInitHandler struct {
db *gorm.DB
logger hclog.Logger
eventStore data.EventStore
locationStore data.LocationStore
organizationStore data.OrganizationStore
personStore data.PersonStore
roomStore data.RoomStore
topicStore data.TopicStore
talkStore data.TalkStore
talkDateStore data.TalkDateStore
}
func NewDBInitHandler(db *gorm.DB, ls data.LocationStore, es data.EventStore, os data.OrganizationStore, ps data.PersonStore, rs data.RoomStore, ts data.TopicStore, tlks data.TalkStore, tlkds data.TalkDateStore, logger hclog.Logger) *DBInitHandler {
return &DBInitHandler{
db: db,
logger: logger,
eventStore: es,
locationStore: ls,
organizationStore: os,
personStore: ps,
roomStore: rs,
topicStore: ts,
talkStore: tlks,
talkDateStore: tlkds,
}
}
func (ih *DBInitHandler) Handle(rw http.ResponseWriter, r *http.Request) {
ih.logger.Debug("Init database endpoint called...")
database.Init(ih.db, ih.locationStore, ih.eventStore, ih.organizationStore, ih.personStore, ih.roomStore, ih.topicStore, ih.talkStore, ih.talkDateStore, ih.logger)
rw.WriteHeader(http.StatusNoContent)
}
|
// Copyright © 2016 Prometheus Team
//
// 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 cmd
import (
"fmt"
"path/filepath"
"strings"
"github.com/spf13/cobra"
)
// infoCmd represents the info command
var infoCmd = &cobra.Command{
Use: "info",
Short: "Print info about current project and exit",
Long: `Print info about current project and exit`,
Run: func(cmd *cobra.Command, args []string) {
runInfo()
},
}
// init prepares cobra flags
func init() {
Promu.AddCommand(infoCmd)
}
type ProjectInfo struct {
Branch string
Name string
Owner string
Repo string
Revision string
Version string
}
func NewProjectInfo() ProjectInfo {
repo := repoLocation()
return ProjectInfo{
Branch: shellOutput("git rev-parse --abbrev-ref HEAD"),
Name: filepath.Base(repo),
Owner: filepath.Base(filepath.Dir(repo)),
Repo: repo,
Revision: shellOutput("git rev-parse --short HEAD"),
Version: findVersion(),
}
}
func runInfo() {
info := NewProjectInfo()
fmt.Println("Name:", info.Name)
fmt.Println("Version:", info.Version)
fmt.Println("Owner:", info.Owner)
fmt.Println("Repo:", info.Repo)
fmt.Println("Branch:", info.Branch)
fmt.Println("Revision:", info.Revision)
}
func repoLocation() string {
repo := shellOutput("git config --get remote.origin.url")
repo = strings.TrimPrefix(repo, "http://")
repo = strings.TrimPrefix(repo, "https://")
repo = strings.TrimPrefix(repo, "git@")
repo = strings.TrimSuffix(repo, ".git")
return strings.Replace(repo, ":", "/", -1)
}
func findVersion() string {
var files = []string{"VERSION", "version/VERSION"}
for _, file := range files {
if fileExists(file) {
return readFile(file)
}
}
return ""
}
|
package tests
import (
"github.com/ravendb/ravendb-go-client"
"github.com/stretchr/testify/assert"
"testing"
)
func getDatabaseRecordCanGetDatabaseRecord(t *testing.T, driver *RavenTestDriver) {
var err error
store := driver.getDocumentStoreMust(t)
defer store.Close()
op := ravendb.NewGetDatabaseRecordOperation(store.GetDatabase())
err = store.Maintenance().Server().Send(op)
assert.NoError(t, err)
assert.Equal(t, op.Command.Result.DatabaseName, store.GetDatabase())
}
func TestGetDatabaseRecord(t *testing.T) {
driver := createTestDriver(t)
destroy := func() { destroyDriver(t, driver) }
defer recoverTest(t, destroy)
// matches order of Java tests
getDatabaseRecordCanGetDatabaseRecord(t, driver)
}
|
// Copyright 2021 The gVisor 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 tcp
import (
"testing"
"github.com/google/go-cmp/cmp"
"gvisor.dev/gvisor/pkg/buffer"
"gvisor.dev/gvisor/pkg/tcpip/faketime"
"gvisor.dev/gvisor/pkg/tcpip/stack"
)
const trueSegSize = stack.PacketBufferStructSize + segSize
type segmentSizeWants struct {
DataSize int
SegMemSize int
}
func checkSegmentSize(t *testing.T, name string, seg *segment, want segmentSizeWants) {
t.Helper()
got := segmentSizeWants{
DataSize: seg.payloadSize(),
SegMemSize: seg.segMemSize(),
}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("%s differs (-want +got):\n%s", name, diff)
}
}
func TestSegmentMerge(t *testing.T) {
var clock faketime.NullClock
id := stack.TransportEndpointID{}
seg1 := newOutgoingSegment(id, &clock, buffer.MakeWithView(buffer.NewViewSize(10)))
defer seg1.DecRef()
seg2 := newOutgoingSegment(id, &clock, buffer.MakeWithView(buffer.NewViewSize(20)))
defer seg2.DecRef()
checkSegmentSize(t, "seg1", seg1, segmentSizeWants{
DataSize: 10,
SegMemSize: trueSegSize + 10,
})
checkSegmentSize(t, "seg2", seg2, segmentSizeWants{
DataSize: 20,
SegMemSize: trueSegSize + 20,
})
seg1.merge(seg2)
checkSegmentSize(t, "seg1", seg1, segmentSizeWants{
DataSize: 30,
SegMemSize: trueSegSize + 30,
})
checkSegmentSize(t, "seg2", seg2, segmentSizeWants{
DataSize: 0,
SegMemSize: trueSegSize,
})
}
|
package app
import (
"MF/hamsoyamodels"
"MF/helperfunc"
"MF/models"
"MF/settings"
"MF/token"
"encoding/json"
"fmt"
"github.com/julienschmidt/httprouter"
"io/ioutil"
"log"
"math"
"net/http"
"strconv"
"time"
)
//Handler for login // Get log and pass
func (server *MainServer) LoginHandler(writer http.ResponseWriter, request *http.Request, pr httprouter.Params) {
// fmt.Println("login\n")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody token.RequestDTO
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
log.Printf("login = %s, pass = %s\n", requestBody.Username, requestBody.Password)
response, err := server.tokenSvc.Generate(request.Context(), &requestBody)
//log.Println(response)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.password_mismatch", err.Error()})
if err != nil {
log.Print(err)
}
return
}
user, err := models.FindUserByLogin(requestBody.Username)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.user_mismatch", err.Error()})
if err != nil {
log.Print(err)
}
return
}
response.ID = user.Id
response.Name = user.Name
response.Surname = user.Surname
response.Role = user.Role
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Get clients By ID
func (server *MainServer) GetClientInfoByIdHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
fmt.Println("I am find client By number phone")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id := param.ByName(`id`)
fmt.Println(id)
response := models.GetClientInfoById(id)
if response.ClientID == 0 {
writer.WriteHeader(http.StatusBadRequest)
return
}
fmt.Println(response)
err := json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Get list clients Handler :
func (server *MainServer) GetClientsInfoHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var clientDefault models.ClientInfo
URL := `http://127.0.0.1:8080/api/megafon/clients`
PreURL := ``
page := request.URL.Query().Get(`page`)
pageInt, errPage := strconv.Atoi(page)
if errPage != nil {
pageInt = 1
URL += `?page=1`
}
IsActive, err := strconv.ParseBool(request.URL.Query().Get(`IsActive`))
if err == nil {
clientDefault.IsActive = IsActive
PreURL += fmt.Sprintf(`&IsActive=%s`, request.URL.Query().Get(`IsActive`))
}
IsIdentified, err := strconv.ParseBool(request.URL.Query().Get(`IsIdentified`))
if err == nil {
clientDefault.IsIdentified = IsIdentified
PreURL += fmt.Sprintf(`&IsIdentified=%s`, request.URL.Query().Get(`IsIdentified`))
}
IsBlackList, err := strconv.ParseBool(request.URL.Query().Get(`IsBlackList`))
if err == nil {
clientDefault.IsBlackList = IsBlackList
PreURL += fmt.Sprintf(`&IsBlackList=%s`, request.URL.Query().Get(`IsBlackList`))
}
SendToCft, err := strconv.ParseBool(request.URL.Query().Get(`SendToCft`))
if err == nil {
clientDefault.SendToCft = SendToCft
PreURL += fmt.Sprintf(`&SendToCft=%s`, request.URL.Query().Get(`SendToCft`))
}
Sex := request.URL.Query().Get(`Sex`)
if Sex != `` {
if Sex == "W" {
clientDefault.Sex = "Ж"
PreURL += fmt.Sprintf(`&Sex=%s`, `W`)
} else {
clientDefault.Sex = "М"
PreURL += fmt.Sprintf(`&Sex=%s`, `M`)
}
}
//Default-ные значение времени. типа с начало до конца
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseClientsInfo
response = models.GetClientsCount(clientDefault, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if errPage == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
response.URL = URL + PreURL
fmt.Println(response.URL)
models.GetClients(clientDefault, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//UnUse Handler
func (server *MainServer) LoginHandler1(writer http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
fmt.Printf("Login\n")
bytes, err := ioutil.ReadFile("web/templates/mpage.gohtml")
if err != nil {
log.Fatal("can't read from /web/templates/mgpage.gohtml\nerr: ", err)
}
_, err = writer.Write(bytes)
if err != nil {
log.Fatal("can't send bytes to writer")
}
}
//UnUse Handler
func (server *MainServer) MainPageHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
// fmt.Println("Login\n")
var requestBody token.RequestDTO
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
response, err := server.tokenSvc.Generate(request.Context(), &requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.password_mismatch", err.Error()})
if err != nil {
log.Print(err)
}
return
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//GetVendorCategory
func (server *MainServer) GetVendorsHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
URL := `http://127.0.0.1:8080/api/megafon/vendors`
PreURL := ``
vendor := models.Vendor{}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseVendors
page := request.URL.Query().Get(`page`)
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
URL += `?page=1`
}
response = models.GetVendorsCount(vendor, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
models.GetVendors(vendor, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Get View Transaction By Id Handler
func (server *MainServer) GetViewTransactionByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
param := params.ByName(`id`)
id, err := strconv.Atoi(param)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
response := models.GetViewTransactionsByID(int64(id))
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Edit status
func (server *MainServer) EditTransactionByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
param := params.ByName(`id`)
id, err := strconv.Atoi(param)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
var requestBody models.TableTransaction
err = json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
fmt.Println("HERE = ", err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
// here
response := models.GetViewTransactionsByID(int64(id))
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
// Get view Trans for report
func (server *MainServer) GetViewTransactionsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
fmt.Println("I am view Transaction")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
transaction := models.ViewTransaction{}
PreURL := ``
RequestId, err := strconv.Atoi(request.URL.Query().Get(`RequestId`))
if err == nil {
transaction.RequestId = int64(RequestId)
PreURL += `&RequestId=` + request.URL.Query().Get(`RequestId`)
}
PaymentID, err := strconv.Atoi(request.URL.Query().Get(`PaymentID`))
if err == nil {
transaction.PaymentID = int64(PaymentID)
PreURL += `&PaymentID=` + request.URL.Query().Get(`PaymentID`)
}
PreCheckQueueID, err := strconv.Atoi(request.URL.Query().Get(`PreCheckQueueID`))
if err == nil {
transaction.PreCheckQueueID = int64(PreCheckQueueID)
PreURL += `&PreCheckQueueID=` + request.URL.Query().Get(`PreCheckQueueID`)
}
Vendor, err := strconv.Atoi(request.URL.Query().Get(`Vendor`))
if err == nil {
transaction.Vendor = Vendor
PreURL += `&Vendor=` + request.URL.Query().Get(`Vendor`)
}
VendorName := request.URL.Query().Get(`VendorName`)
if VendorName != `` {
PreURL += `&VendorName=` + request.URL.Query().Get(`VendorName`)
transaction.VendorName = VendorName
}
RequestType := request.URL.Query().Get(`RequestType`)
if RequestType != `` {
PreURL += `&RequestType=` + request.URL.Query().Get(`RequestType`)
transaction.RequestType = RequestType
}
AccountPayer := request.URL.Query().Get(`AccountPayer`)
if AccountPayer != `` {
PreURL += `&AccountPayer=` + request.URL.Query().Get(`AccountPayer`)
transaction.AccountPayer = AccountPayer
}
AccountReceiver := request.URL.Query().Get(`AccountReceiver`)
if AccountReceiver != `` {
PreURL += `&AccountReceiver=` + request.URL.Query().Get(`AccountReceiver`)
transaction.AccountReceiver = AccountReceiver
}
StateID := request.URL.Query().Get(`StateID`)
if StateID != `` {
PreURL += `&StateID=` + request.URL.Query().Get(`StateID`)
transaction.StateID = StateID
}
Aggregator := request.URL.Query().Get(`Aggregator`)
if Aggregator != `` {
PreURL += `&Aggregator=` + request.URL.Query().Get(`Aggregator`)
transaction.Aggregator = Aggregator
}
GateWay := request.URL.Query().Get(`GateWay`)
if GateWay != `` {
PreURL += `&GateWay=` + request.URL.Query().Get(`GateWay`)
transaction.GateWay = GateWay
}
Amount, err := strconv.ParseFloat(request.URL.Query().Get(`Amount`), 64)
if err == nil {
PreURL += `&Amount=` + request.URL.Query().Get(`Amount`)
transaction.Amount = Amount
}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseViewTransactions
page := request.URL.Query().Get(`page`)
URL := `http://127.0.0.1:8080/api/megafon/view-transactions`
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
URL += `?page=1`
}
response = models.GetViewTransactionsCount(transaction, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
models.GetViewTransactions(transaction, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//
func (server *MainServer) GetTableTransactionByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
param := params.ByName(`id`)
id, err := strconv.Atoi(param)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
response := models.GetTableTransactionsByID(int64(id))
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//
func (server *MainServer) GetTableTransactionByIdStatusHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
param := params.ByName(`id`)
id, err := strconv.Atoi(param)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
response := models.GetTableTransactionsByID(int64(id))
type inter struct {
ID int `json:"id"`
StateID string `json:"state_id"`
}
var TransInfo inter
TransInfo.ID = response.ID
TransInfo.StateID = response.StateID
err = json.NewEncoder(writer).Encode(&TransInfo)
if err != nil {
log.Print(err)
}
}
func (server *MainServer) SetNewTransactionStatus(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
type inter struct {
ID int `json:"id"`
StateID string `json:"state_id"`
}
var requestBody inter
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
//fmt.Println("Nawud")
return
}
err, transaction := models.ChangeNewStateID(requestBody.ID, requestBody.StateID)
if err != nil {
writer.WriteHeader(http.StatusNotFound)
// fmt.Println("Nawud")
return
}
err = json.NewEncoder(writer).Encode(&transaction)
if err != nil {
log.Print(err)
}
}
// Get view Trans for report
func (server *MainServer) GetTableTransactionsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
fmt.Println("I am view Transaction")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
transaction := models.TableTransaction{}
PreURL := ``
RequestId, err := strconv.Atoi(request.URL.Query().Get(`RequestId`))
if err == nil {
transaction.RequestID = uint(RequestId)
PreURL += `&RequestId=` + request.URL.Query().Get(`RequestId`)
}
PaymentID, err := strconv.Atoi(request.URL.Query().Get(`PaymentID`))
if err == nil {
transaction.PaymentID = int64(PaymentID)
PreURL += `&PaymentID=` + request.URL.Query().Get(`PaymentID`)
}
Vendor, err := strconv.Atoi(request.URL.Query().Get(`Vendor`))
if err == nil {
transaction.Vendor = Vendor
PreURL += `&Vendor=` + request.URL.Query().Get(`Vendor`)
}
AccountPayer := request.URL.Query().Get(`AccountPayer`)
if AccountPayer != `` {
PreURL += `&AccountPayer=` + request.URL.Query().Get(`AccountPayer`)
transaction.AccountPayer = AccountPayer
}
AccountReceiver := request.URL.Query().Get(`AccountReceiver`)
if AccountReceiver != `` {
PreURL += `&AccountReceiver=` + request.URL.Query().Get(`AccountReceiver`)
transaction.AccountReceiver = AccountReceiver
}
StateID := request.URL.Query().Get(`StateID`)
if StateID != `` {
PreURL += `&StateID=` + request.URL.Query().Get(`StateID`)
transaction.StateID = StateID
}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseTransactions
page := request.URL.Query().Get(`page`)
URL := `http://127.0.0.1:8080/api/megafon/transactions`
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
URL += `?page=1`
}
response = models.GetTableTransactionsCount(transaction, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
models.GetTableTransactions(transaction, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
// Get view report for report
func (server *MainServer) GetViewReportsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
fmt.Println("I am get clients")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
viewReport := models.ViewReport{}
PreURL := ``
RequestId, err := strconv.Atoi(request.URL.Query().Get(`RequestId`))
if err == nil {
viewReport.RequestId = int64(RequestId)
PreURL += `&RequestId=` + request.URL.Query().Get(`RequestId`)
}
PaymentID, err := strconv.Atoi(request.URL.Query().Get(`PaymentID`))
if err == nil {
viewReport.PaymentID = int64(PaymentID)
PreURL += `&PaymentID=` + request.URL.Query().Get(`PaymentID`)
}
VendorID, err := strconv.Atoi(request.URL.Query().Get(`VendorId`))
if err == nil {
viewReport.VendorID = VendorID
PreURL += `&VendorId=` + request.URL.Query().Get(`VendorId`)
}
VendorName := request.URL.Query().Get(`VendorName`)
if VendorName != `` {
PreURL += `&VendorName=` + request.URL.Query().Get(`VendorName`)
viewReport.VendorName = VendorName
}
RequestType := request.URL.Query().Get(`RequestType`)
if RequestType != `` {
PreURL += `&RequestType=` + request.URL.Query().Get(`RequestType`)
viewReport.RequestType = RequestType
}
AccountPayer := request.URL.Query().Get(`AccountPayer`)
if AccountPayer != `` {
PreURL += `&AccountPayer=` + request.URL.Query().Get(`AccountPayer`)
viewReport.AccountPayer = AccountPayer
}
AccountReceiver := request.URL.Query().Get(`AccountReceiver`)
if AccountReceiver != `` {
PreURL += `&AccountReceiver=` + request.URL.Query().Get(`AccountReceiver`)
viewReport.AccountReceiver = AccountReceiver
}
StateID := request.URL.Query().Get(`StateID`)
if StateID != `` {
PreURL += `&StateID=` + request.URL.Query().Get(`StateID`)
viewReport.StateID = StateID
}
Aggregator := request.URL.Query().Get(`Aggregator`)
if Aggregator != `` {
PreURL += `&Aggregator=` + request.URL.Query().Get(`Aggregator`)
viewReport.Aggregator = Aggregator
}
GateWay := request.URL.Query().Get(`GateWay`)
if GateWay != `` {
PreURL += `&GateWay=` + request.URL.Query().Get(`GateWay`)
viewReport.GateWay = GateWay
}
Amount, err := strconv.ParseFloat(request.URL.Query().Get(`Amount`), 64)
if err == nil {
PreURL += `&Amount=` + request.URL.Query().Get(`Amount`)
viewReport.Amount = Amount
}
fmt.Println(viewReport)
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseViewReports
page := request.URL.Query().Get(`page`)
URL := `http://127.0.0.1:8080/api/megafon/reports`
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
URL += `?page=1`
}
response = models.GetViewReportCount(viewReport, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
models.GetViewReport(viewReport, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
// test for excel
// Get view report for report
func (server *MainServer) GetViewReportsForExcelHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
fmt.Println("I am get clients")
fmt.Println("id = ", request.Header.Get("ID"))
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
viewReport := models.ViewReport{}
PreURL := ``
RequestId, err := strconv.Atoi(request.URL.Query().Get(`RequestId`))
if err == nil {
viewReport.RequestId = int64(RequestId)
PreURL += `&RequestId=` + request.URL.Query().Get(`RequestId`)
}
PaymentID, err := strconv.Atoi(request.URL.Query().Get(`PaymentID`))
if err == nil {
viewReport.PaymentID = int64(PaymentID)
PreURL += `&PaymentID=` + request.URL.Query().Get(`PaymentID`)
}
VendorID, err := strconv.Atoi(request.URL.Query().Get(`VendorId`))
if err == nil {
viewReport.VendorID = VendorID
PreURL += `&VendorId=` + request.URL.Query().Get(`VendorId`)
}
VendorName := request.URL.Query().Get(`VendorName`)
if VendorName != `` {
PreURL += `&VendorName=` + request.URL.Query().Get(`VendorName`)
viewReport.VendorName = VendorName
}
RequestType := request.URL.Query().Get(`RequestType`)
if RequestType != `` {
PreURL += `&RequestType=` + request.URL.Query().Get(`RequestType`)
viewReport.RequestType = RequestType
}
AccountPayer := request.URL.Query().Get(`AccountPayer`)
if AccountPayer != `` {
PreURL += `&AccountPayer=` + request.URL.Query().Get(`AccountPayer`)
viewReport.AccountPayer = AccountPayer
}
AccountReceiver := request.URL.Query().Get(`AccountReceiver`)
if AccountReceiver != `` {
PreURL += `&AccountReceiver=` + request.URL.Query().Get(`AccountReceiver`)
viewReport.AccountReceiver = AccountReceiver
}
StateID := request.URL.Query().Get(`StateID`)
if StateID != `` {
PreURL += `&StateID=` + request.URL.Query().Get(`StateID`)
viewReport.StateID = StateID
}
Aggregator := request.URL.Query().Get(`Aggregator`)
if Aggregator != `` {
PreURL += `&Aggregator=` + request.URL.Query().Get(`Aggregator`)
viewReport.Aggregator = Aggregator
}
GateWay := request.URL.Query().Get(`GateWay`)
if GateWay != `` {
PreURL += `&GateWay=` + request.URL.Query().Get(`GateWay`)
viewReport.GateWay = GateWay
}
Amount, err := strconv.ParseFloat(request.URL.Query().Get(`Amount`), 64)
if err == nil {
PreURL += `&Amount=` + request.URL.Query().Get(`Amount`)
viewReport.Amount = Amount
}
fmt.Println(viewReport)
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseViewReports
// page := request.URL.Query().Get(`page`)
URL := `http://127.0.0.1:8080/api/megafon/download-reports`
//pageInt, err := strconv.Atoi(page)
//if err != nil {
// pageInt = 1
// URL += `?page=1`
//}
response = models.GetViewReportCount(viewReport, interval)
response.TotalPage = 0
//response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(200))))
// response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
models.GetViewReportForExcel(viewReport, &response, interval)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//
func (server *MainServer) GetViewReportsByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
param := params.ByName(`id`)
id, err := strconv.Atoi(param)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
response := models.GetViewReportById(int64(id))
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
// Save New Vendor
func (server *MainServer) SaveNewVendorHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
var requestBody models.Vendor
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
fmt.Println("HERE = ", err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
fmt.Println(requestBody)
requestBody.CreateTime = time.Now()
_, err = requestBody.Save()
if err != nil {
writer.WriteHeader(http.StatusConflict)
fmt.Println("Here")
err := json.NewEncoder(writer).Encode([]string{"err.db"})
log.Print(err)
return
}
URL := `http://127.0.0.1:8080/api/megafon/vendors`
PreURL := ``
vendor := models.Vendor{}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseVendors
page := request.URL.Query().Get(`page`)
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
URL += `?page=1`
}
response = models.GetVendorsCount(vendor, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
models.GetVendors(vendor, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
// Update Vendor
func (server *MainServer) UpdateVendorHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
var requestBody models.Vendor
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
//fmt.Println(requestBody.CatID + 10000000000)
response := requestBody.Update(requestBody)
fmt.Println(response)
if response.ID <= 0 {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Println(err)
}
}
//Get one Vendor
func (server *MainServer) GetVendorHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
param := params.ByName(`id`)
id, err := strconv.Atoi(param)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
response := models.GetVendorById(int64(id))
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Get list Merchants
func (server *MainServer) GetMerchantsHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
page := request.URL.Query().Get(`page`)
PreURL := ``
//
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
from /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseMerchants
pageInt, err := strconv.Atoi(page)
URL := `http://127.0.0.1:8080/api/megafon/merchants`
if err != nil {
pageInt = 1
URL += `?page=1`
}
var merchant models.Merchant
response = models.GetMerchantsCount(merchant, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
models.GetMerchants(merchant, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Get on Merchant
func (server *MainServer) GetMerchantHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
param := params.ByName(`id`)
id, err := strconv.Atoi(param)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
response := models.Merchant{}
merchant := response.GetMerchantById(int64(id))
err = json.NewEncoder(writer).Encode(&merchant)
if err != nil {
log.Print(err)
}
}
//Update Merchant
func (server *MainServer) UpdateMerchantHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
var requestBody models.Merchant
//var reqBody models.Merchant
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
//fmt.Println(reqBody)
response := requestBody.Update(requestBody)
///fmt.Println(response)
if response.ID <= 0 {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Println(err)
}
}
//Get all ViewLog by page
func (server *MainServer) GetViewLogsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
pageInt := 1
rowsInt := 100
page := request.URL.Query().Get(`page`)
rows := request.URL.Query().Get(`rows`)
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
}
rowsInt, err = strconv.Atoi(rows)
if err != nil {
rowsInt = 100
}
response := models.GetViewLogs(int64(rowsInt), int64(pageInt))
if response.Error != nil {
err := json.NewEncoder(writer).Encode([]string{`error mismatch this view log'`})
log.Print(err)
return
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//GetViewDTO
func (server *MainServer) GetViewLogsDTOHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
page := request.URL.Query().Get(`page`)
PreURL := ``
//
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
from /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response models.ResponseViewLogsList
pageInt, err := strconv.Atoi(page)
URL := `http://127.0.0.1:8080/api/megafon/logs`
if err != nil {
pageInt = 1
URL += `?page=1`
}
var ViewLogDTO models.ViewLogDTO
response = models.GetViewLogsDTOCount(ViewLogDTO, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
models.GetViewLogsDTO(ViewLogDTO, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//
func (server *MainServer) GetViewLogHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
id, err := strconv.Atoi(param.ByName("id"))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
viewLog, err := models.GetViewLogById(int64(id))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(viewLog)
if err != nil {
log.Print("invalid_viewlog")
return
}
}
//
func (server *MainServer) GetHamsoyaTransactionsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
fmt.Println("I am view Transaction")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
transaction := hamsoyamodels.HamsoyaTransaction{}
PreURL := ``
Id, err := strconv.Atoi(request.URL.Query().Get(`Id`))
if err == nil {
transaction.Id = int64(Id)
PreURL += `&Id=` + request.URL.Query().Get(`Id`)
}
PreCheckId, err := strconv.Atoi(request.URL.Query().Get(`PreCheckId`))
if err == nil {
transaction.PreCheckId = int64(PreCheckId)
PreURL += `&PreCheckId=` + request.URL.Query().Get(`PreCheckId`)
}
StatusId, err := strconv.Atoi(request.URL.Query().Get(`StatusId`))
if err == nil {
transaction.StatusId = int64(StatusId)
PreURL += `&StatusId=` + request.URL.Query().Get(`StatusId`)
}
TypeId, err := strconv.Atoi(request.URL.Query().Get(`TypeId`))
if err == nil {
transaction.TypeId = int64(TypeId)
PreURL += `&TypeId=` + request.URL.Query().Get(`TypeId`)
}
ExtStatusId, err := strconv.Atoi(request.URL.Query().Get(`ExtStatusId`))
if err == nil {
transaction.ExtStatusId = int64(ExtStatusId)
PreURL += `&ExtStatusId=` + request.URL.Query().Get(`ExtStatusId`)
}
ClientPayerId, err := strconv.Atoi(request.URL.Query().Get(`ClientPayerId`))
if err == nil {
transaction.ClientPayerId = int64(ClientPayerId)
PreURL += `&ClientPayerId=` + request.URL.Query().Get(`ClientPayerId`)
}
ExtTransId := request.URL.Query().Get(`ExtTransId`)
if ExtTransId != `` {
transaction.ExtTransId = ExtTransId
PreURL += `&ExtTransId=` + request.URL.Query().Get(`ExtTransId`)
}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response hamsoyamodels.ResponseHamsoyaTransactions
page := request.URL.Query().Get(`page`)
URL := `http://127.0.0.1:8080/api/hamsoya/transactions`
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
URL += `?page=1`
}
response = hamsoyamodels.GetHamsoyaTransactionsCount(transaction, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
hamsoyamodels.GetHamsoyaTransactions(transaction, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Get transaction By id
func (server *MainServer) GetHamsoyaTransactionByIdHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(param.ByName("id"))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
transaction, err := hamsoyamodels.GetHamsoyaTransactionById(int64(id))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&transaction)
if err != nil {
log.Print("invalid_transaction")
return
}
}
//
func (server *MainServer) GetHamsoyaTransactionTypeHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
page := request.URL.Query().Get(`page`)
PreURL := ``
pageInt, err := strconv.Atoi(page)
URL := `http://localhost:3000/hamsoya/transactionstype`
if err != nil {
pageInt = 1
PreURL = `?page=1`
} else {
PreURL = fmt.Sprintf(`?page=%d`, pageInt)
}
var transactionTypeDefault hamsoyamodels.HamsoyaTransactionType
IsActive, err := strconv.ParseBool(request.URL.Query().Get(`IsActive`))
if err == nil {
transactionTypeDefault.IsActive = IsActive
PreURL += fmt.Sprintf(`&IsActive=%s`, request.URL.Query().Get(`IsActive`))
}
IsForJob, err := strconv.ParseBool(request.URL.Query().Get(`IsForJob`))
if err == nil {
transactionTypeDefault.IsForJob = IsForJob
PreURL += fmt.Sprintf(`&IsForJob=%s`, request.URL.Query().Get(`IsForJob`))
}
IsPayment, err := strconv.ParseBool(request.URL.Query().Get(`IsPayment`))
if err == nil {
transactionTypeDefault.IsPayment = IsPayment
PreURL += fmt.Sprintf(`&IsPayment=%s`, request.URL.Query().Get(`IsPayment`))
}
fmt.Println(transactionTypeDefault)
var response hamsoyamodels.ResponseHamsoyaTransactionsType
response = hamsoyamodels.GetHamsoyaTransactionsTypeCount(transactionTypeDefault)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
response.URL = URL + PreURL
fmt.Println(response.URL)
hamsoyamodels.GetHamsoyaTransactionsType(transactionTypeDefault, &response, int64(pageInt)-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Get TransactionType By Id
func (server *MainServer) GetHamsoyaTransactionTypeByIdHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(param.ByName("id"))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
transaction, err := hamsoyamodels.GetHamsoyaTransactionTypeById(int64(id))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&transaction)
if err != nil {
log.Print("invalid_transaction")
return
}
}
//Save transactionType
func (server *MainServer) SaveHamsoyaTransactionType(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody hamsoyamodels.HamsoyaTransactionType
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("wrong_body")
log.Print(err)
return
}
fmt.Println(requestBody)
savedElement := requestBody.Save()
if savedElement.Id <= 0 {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
var transactionTypeDefault hamsoyamodels.HamsoyaTransactionType
var response hamsoyamodels.ResponseHamsoyaTransactionsType
response = hamsoyamodels.GetHamsoyaTransactionsTypeCount(transactionTypeDefault)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(1), response.TotalPage)
response.URL = `http://localhost:3000/hamsoya/transactionstype?page=1`
fmt.Println(response.URL)
hamsoyamodels.GetHamsoyaTransactionsType(transactionTypeDefault, &response, 0)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
//Edit transactionType
func (server *MainServer) UpdateHamsoyaTransactionTypeHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
fmt.Println("here")
var requestBody hamsoyamodels.HamsoyaTransactionType
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
response := requestBody.Update(requestBody)
fmt.Println(response)
if response.Id <= 0 {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode([]string{"err.json_invalid"})
log.Print(err)
return
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Println(err)
}
}
// Get Configs
func (server *MainServer) GetHamosyaConfigsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
pageInt := 1
rowsInt := 100
page := request.URL.Query().Get(`page`)
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
}
rows := request.URL.Query().Get(`rows`)
rowsInt, err = strconv.Atoi(rows)
if err != nil {
rowsInt = 100
}
var newHamsoyaConfig hamsoyamodels.HamsoyaConfig
id, err := strconv.Atoi(request.URL.Query().Get(`Id`))
if err == nil {
newHamsoyaConfig.Id = int64(id)
}
code := request.URL.Query().Get(`Code`)
newHamsoyaConfig.Code = code
value, err := strconv.Atoi(request.URL.Query().Get(`Value`))
if err == nil {
newHamsoyaConfig.Value = int64(value)
}
valueStr := request.URL.Query().Get(`Valuestr`)
newHamsoyaConfig.ValueStr = valueStr
HamsoyaConfig := hamsoyamodels.GetHamsoyaConfig(newHamsoyaConfig, int64(rowsInt), int64(pageInt))
if HamsoyaConfig.Error != nil {
writer.WriteHeader(http.StatusNotFound)
err := json.NewEncoder(writer).Encode(`mismatch_hamsoyaConfig`)
if err != nil {
log.Println(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(HamsoyaConfig)
if err != nil {
log.Println(err)
return
}
return
}
// Save Configs
func (server *MainServer) SaveHamsoyaConfigHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody hamsoyamodels.HamsoyaConfig
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
requestBody.CreateDate = time.Now()
err = requestBody.Save()
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("wrong_date")
if err != nil {
log.Println(err)
return
}
}
var newHamsoyaConfig hamsoyamodels.HamsoyaConfig
HamsoyaConfig := hamsoyamodels.GetHamsoyaConfig(newHamsoyaConfig, int64(100), int64(1))
if HamsoyaConfig.Error != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode(`mismatch_hamsoyaConfig`)
if err != nil {
log.Println(err)
return
}
return
}
HamsoyaConfig.URL = `http://localhost:3000/hamsoya/configs?page=1`
err = json.NewEncoder(writer).Encode(HamsoyaConfig)
if err != nil {
log.Println(err)
return
}
return
}
//
func (server *MainServer) UpdateHamsoyaConfigHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
// writer.Header().Set("Content-Type", "application/json; charset=utf-8")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody hamsoyamodels.HamsoyaConfig
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
response, err := requestBody.Update(requestBody)
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("wrong_date")
if err != nil {
log.Println(err)
return
}
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Println(err)
return
}
return
}
// GET ONE config
func (server *MainServer) GetHamsoyaConfigByIdHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(param.ByName("id"))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
transaction, err := hamsoyamodels.GetHamsoyaConfigById(int64(id))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&transaction)
if err != nil {
log.Print("invalid_config.")
return
}
}
// Get AccountTypes
func (server *MainServer) GetHamosyaAccountTypesHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
pageInt := 1
rowsInt := 100
page := request.URL.Query().Get(`page`)
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
}
rows := request.URL.Query().Get(`rows`)
rowsInt, err = strconv.Atoi(rows)
if err != nil {
rowsInt = 100
}
var newHamsoyaAccountType hamsoyamodels.HamsoyaAccountType
id, err := strconv.Atoi(request.URL.Query().Get(`id`))
if err == nil {
newHamsoyaAccountType.Id = int64(id)
}
code := request.URL.Query().Get(`code`)
newHamsoyaAccountType.Code = code
Type := request.URL.Query().Get(`type`)
newHamsoyaAccountType.Type = Type
Name := request.URL.Query().Get(`name`)
newHamsoyaAccountType.Name = Name
prefix, err := strconv.Atoi(request.URL.Query().Get(`prefix`))
if err == nil {
newHamsoyaAccountType.Prefix = int64(prefix)
}
HamsoyaAccountTypes := hamsoyamodels.GetHamsoyaAccountTypes(newHamsoyaAccountType, int64(rowsInt), int64(pageInt))
if HamsoyaAccountTypes.Error != nil {
writer.WriteHeader(http.StatusNotFound)
err := json.NewEncoder(writer).Encode(`mismatch_hamsoyaConfig`)
if err != nil {
log.Println(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(HamsoyaAccountTypes)
if err != nil {
log.Println(err)
return
}
return
}
// Get AccountType
func (server *MainServer) GetHamsoyaAccountTypeByIdHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(param.ByName("id"))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
AccountTypes, err := hamsoyamodels.GetHamsoyaAccountTypeById(int64(id))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&AccountTypes)
if err != nil {
log.Print("invalid_config.")
return
}
}
// Save AccountType
func (server *MainServer) SaveHamsoyaAccountTypeHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody hamsoyamodels.HamsoyaAccountType
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
// requestBody.CreateDate = time.Now()
response, err := requestBody.Save()
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("wrong_date")
if err != nil {
log.Println(err)
return
}
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Println(err)
return
}
return
}
// Edit AccountType
func (server *MainServer) UpdateHamsoyaAccountTypeHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
// writer.Header().Set("Content-Type", "application/json; charset=utf-8")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody hamsoyamodels.HamsoyaAccountType
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
response, err := requestBody.Update(requestBody)
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("wrong_date")
if err != nil {
log.Println(err)
return
}
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Println(err)
return
}
return
}
// Get Statuses
func (server *MainServer) GetHamsoyaStatusesHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
pageInt := 1
page := request.URL.Query().Get(`page`)
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
}
var newHamsoyaStatus hamsoyamodels.HamsoyaStatus
id, err := strconv.Atoi(request.URL.Query().Get(`id`))
if err == nil {
newHamsoyaStatus.Id = int64(id)
}
code := request.URL.Query().Get(`code`)
newHamsoyaStatus.Code = code
Name := request.URL.Query().Get(`name`)
newHamsoyaStatus.Name = Name
ExtCode := request.URL.Query().Get(`extcode`)
newHamsoyaStatus.ExtCode = ExtCode
resultCode, err := strconv.Atoi(request.URL.Query().Get(`resultcode`))
if err == nil {
newHamsoyaStatus.ResultCode = int64(resultCode)
}
final, err := strconv.ParseBool(request.URL.Query().Get(`final`))
if err == nil {
newHamsoyaStatus.Final = final
}
IsAmountHold, err := strconv.ParseBool(request.URL.Query().Get(`is_amount_hold`))
if err == nil {
newHamsoyaStatus.IsAmountHold = IsAmountHold
}
HamsoyaStatus := hamsoyamodels.GetHamsoyaStatuses(newHamsoyaStatus, int64(pageInt))
if HamsoyaStatus.Error != nil {
writer.WriteHeader(http.StatusNotFound)
err := json.NewEncoder(writer).Encode(`mismatch_hamsoyaStatus`)
if err != nil {
log.Println(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(HamsoyaStatus)
if err != nil {
log.Println(err)
return
}
return
}
// Get Status
func (server *MainServer) GetHamsoyaStatusHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(param.ByName("id"))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
HamsoyaStatus, err := hamsoyamodels.GetHamsoyaStatusById(int64(id))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&HamsoyaStatus)
if err != nil {
log.Print("invalid_HamsoyaStatus.")
return
}
}
// Save Status
func (server *MainServer) SaveHamsoyaStatusHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody hamsoyamodels.HamsoyaStatus
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
// requestBody.CreateDate = time.Now()
_, err = requestBody.Save()
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("wrong_date")
if err != nil {
log.Println(err)
return
}
}
newHamsoyaStatus := hamsoyamodels.HamsoyaStatus{}
response := hamsoyamodels.GetHamsoyaStatuses(newHamsoyaStatus, 1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Println(err)
return
}
return
}
// Edit Status
func (server *MainServer) UpdateHamsoyaStatusHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody hamsoyamodels.HamsoyaStatus
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
response, err := requestBody.Update(requestBody)
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("wrong_date")
if err != nil {
log.Println(err)
return
}
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Println(err)
return
}
return
}
// Get Hamsoya view Trans
func (server *MainServer) GetHamsoyaViewTransHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(param.ByName("id"))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
HamsoyaViewTrans, err := hamsoyamodels.GetHamsoyaViewTransById(int64(id))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&HamsoyaViewTrans)
if err != nil {
log.Print("invalid_HamsoyaViewTrans.")
return
}
}
// Get Hamsoya view Transes
// Get Hamsoya view Transaction
func (server *MainServer) GetHamsoyaViewTransactionHandler(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(param.ByName("id"))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
HamsoyaViewTransaction, err := hamsoyamodels.GetHamsoyaViewTransactionById(int64(id))
if err != nil {
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&HamsoyaViewTransaction)
if err != nil {
log.Print("invalid_HamsoyaViewTransaction.")
return
}
}
// Get Hamsoya view Transactions
func (server *MainServer) GetHamsoyaViewTransactionsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
pageInt := 1
rowsInt := 100
page := request.URL.Query().Get(`page`)
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
}
rows := request.URL.Query().Get(`rows`)
rowsInt, err = strconv.Atoi(rows)
if err != nil {
rowsInt = 100
}
var newHamsoyaViewTransaction hamsoyamodels.HamsoyaViewTransaction
HamsoyaViewTransaction := hamsoyamodels.GetHamsoyaViewTransactions(newHamsoyaViewTransaction, int64(rowsInt), int64(pageInt))
err = json.NewEncoder(writer).Encode(HamsoyaViewTransaction)
if err != nil {
log.Println(err)
return
}
return
}
// Get Hamsoya Document
func (server *MainServer) GetHamsoyaDocumentByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(params.ByName("id"))
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
Document, err := hamsoyamodels.GetHamsoyaDocument(int64(id))
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("server wrong")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&Document)
if err != nil {
log.Print("invalid_HamsoyaViewTransaction.")
return
}
}
// Get Hamsoya Documents
func (server *MainServer) GetHamsoyaDocumentsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
page := request.URL.Query().Get(`page`)
PreURL := ``
pageInt, err := strconv.Atoi(page)
URL := `http://localhost:3000/hamsoya/documents`
if err != nil {
pageInt = 1
PreURL = `?page=1`
} else {
PreURL = fmt.Sprintf(`?page=%d`, pageInt)
}
var documentDefault hamsoyamodels.HamsoyaDocument
Id, err := strconv.Atoi(request.URL.Query().Get(`Id`))
if err == nil {
documentDefault.Id = int64(Id)
PreURL += fmt.Sprintf(`&Id=%s`, request.URL.Query().Get(`Id`))
}
AccountDt, err := strconv.Atoi(request.URL.Query().Get(`AccountDt`))
if err == nil {
documentDefault.AccountDt = int64(AccountDt)
PreURL += fmt.Sprintf(`&AccountDt=%s`, request.URL.Query().Get(`AccountDt`))
}
AccountCt, err := strconv.Atoi(request.URL.Query().Get(`AccountCt`))
if err == nil {
documentDefault.AccountCt = int64(AccountCt)
PreURL += fmt.Sprintf(`&AccountCt=%s`, request.URL.Query().Get(`AccountCt`))
}
TransId, err := strconv.Atoi(request.URL.Query().Get(`TransId`))
if err == nil {
documentDefault.TransId = int64(TransId)
PreURL += fmt.Sprintf(`&TransId=%s`, request.URL.Query().Get(`TransId`))
}
StatusId, err := strconv.Atoi(request.URL.Query().Get(`StatusId`))
if err == nil {
documentDefault.StatusId = int64(StatusId)
PreURL += fmt.Sprintf(`&StatusId=%s`, request.URL.Query().Get(`StatusId`))
}
CancelDocId, err := strconv.Atoi(request.URL.Query().Get(`CancelDocId`))
if err == nil {
documentDefault.CancelDocId = int64(CancelDocId)
PreURL += fmt.Sprintf(`&CancelDocId=%s`, request.URL.Query().Get(`CancelDocId`))
}
Amount, err := strconv.ParseFloat(request.URL.Query().Get(`Amount`), 64)
if err == nil {
documentDefault.Amount = Amount
PreURL += fmt.Sprintf(`&Amount=%s`, request.URL.Query().Get(`Amount`))
}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
fmt.Println(documentDefault)
var response hamsoyamodels.ResponseHamsoyaDocuments
response = hamsoyamodels.GetHamsoyaDocumentsCount(documentDefault, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
response.URL = URL + PreURL
fmt.Println(response.URL)
hamsoyamodels.GetHamsoyaDocuments(documentDefault, &response, interval, int64(pageInt)-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
// Get Hamsoya Record
func (server *MainServer) GetHamsoyaRecordByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(params.ByName("id"))
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
Record, err := hamsoyamodels.GetHamsoyaRecordById(int64(id))
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("server wrong")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&Record)
if err != nil {
log.Print("invalid_HamsoyaRecord.")
return
}
}
//Get Hamsoya Records
func (server *MainServer) GetHamsoyaRecordsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
page := request.URL.Query().Get(`page`)
PreURL := ``
pageInt, err := strconv.Atoi(page)
URL := `http://localhost:3000/hamsoya/records`
if err != nil {
pageInt = 1
PreURL = `?page=1`
} else {
PreURL = fmt.Sprintf(`?page=%s`, page)
}
var recordDefault hamsoyamodels.HamsoyaRecord
Id, err := strconv.Atoi(request.URL.Query().Get(`Id`))
if err == nil {
recordDefault.Id = int64(Id)
PreURL += fmt.Sprintf(`&Id=%s`, request.URL.Query().Get(`Id`))
}
AccountId, err := strconv.Atoi(request.URL.Query().Get(`AccountId`))
if err == nil {
recordDefault.AccountId = int64(AccountId)
PreURL += fmt.Sprintf(`&AccountId=%s`, request.URL.Query().Get(`AccountId`))
}
DocumentId, err := strconv.Atoi(request.URL.Query().Get(`DocumentId`))
if err == nil {
recordDefault.DocumentId = int64(DocumentId)
PreURL += fmt.Sprintf(`&DocumentId=%s`, request.URL.Query().Get(`DocumentId`))
}
Amount, err := strconv.ParseFloat(request.URL.Query().Get(`Amount`), 64)
if err == nil {
recordDefault.Amount = Amount
PreURL += fmt.Sprintf(`&Amount=%s`, request.URL.Query().Get(`Amount`))
}
StartSaldo, err := strconv.ParseFloat(request.URL.Query().Get(`StartSaldo`), 64)
if err == nil {
recordDefault.StartSaldo = StartSaldo
PreURL += fmt.Sprintf(`&StartSaldo=%s`, request.URL.Query().Get(`StartSaldo`))
}
Type := request.URL.Query().Get(`Type`)
if Type != `` {
recordDefault.Type = Type
PreURL += fmt.Sprintf(`&Type=%s`, request.URL.Query().Get(`Type`))
}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
fmt.Println(recordDefault)
var response hamsoyamodels.ResponseHamsoyaRecords
response = hamsoyamodels.GetHamsoyaRecordsCount(recordDefault, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
response.URL = URL + PreURL
fmt.Println(response.URL)
fmt.Println(response.TotalPage, pageInt, response.Page)
hamsoyamodels.GetHamsoyaRecords(recordDefault, &response, interval, int64(pageInt)-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
// Get Hamsoya Precheck
func (server *MainServer) GetHamsoyaPrecheckByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(params.ByName("id"))
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
Precheck, err := hamsoyamodels.GetHamsoyaPreCheckById(int64(id))
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("server wrong")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&Precheck)
if err != nil {
log.Print("invalid_HamsoyaPrecheck.")
return
}
}
//Get Hamsoya Prechecks
func (server *MainServer) GetHamsoyaPrechecksHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
pageInt := 1
rowsInt := 100
page := request.URL.Query().Get(`page`)
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
}
rows := request.URL.Query().Get(`rows`)
rowsInt, err = strconv.Atoi(rows)
if err != nil {
rowsInt = 100
}
var newHamsoyaPreCheck hamsoyamodels.HamsoyaPreCheck
PreChecks := hamsoyamodels.GetHamsoyaPreChecks(newHamsoyaPreCheck, int64(rowsInt), int64(pageInt))
if PreChecks.Error != nil {
writer.WriteHeader(http.StatusNotFound)
err := json.NewEncoder(writer).Encode(`mismatch_hamsoyaDocuments`)
if err != nil {
log.Println(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(PreChecks)
if err != nil {
log.Println(err)
return
}
return
}
// Get Hamsoya Account
func (server *MainServer) GetHamsoyaAccountByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(params.ByName("id"))
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
Account, err := hamsoyamodels.GetHamsoyaAccountById(int64(id))
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("server wrong")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&Account)
if err != nil {
log.Print("invalid_HamsoyaPrecheck.")
return
}
}
// Get Hamsoya Accounts
func (server *MainServer) GetHamsoyaAccountsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
page := request.URL.Query().Get(`page`)
PreURL := ``
pageInt, err := strconv.Atoi(page)
URL := `http://localhost:3000/hamsoya/accounts`
if err != nil {
pageInt = 1
PreURL = `?page=1`
} else {
PreURL = fmt.Sprintf(`?page=%d`, pageInt)
}
var accountDefault hamsoyamodels.HamsoyaAccount
Id, err := strconv.Atoi(request.URL.Query().Get(`Id`))
if err == nil {
accountDefault.Id = int64(Id)
PreURL += fmt.Sprintf(`&Id=%s`, request.URL.Query().Get(`Id`))
}
ClientId, err := strconv.Atoi(request.URL.Query().Get(`ClientId`))
if err == nil {
accountDefault.ClientId = int64(ClientId)
PreURL += fmt.Sprintf(`&ClientId=%s`, request.URL.Query().Get(`ClientId`))
}
Overdraft, err := strconv.ParseFloat(request.URL.Query().Get(`Overdraft`), 64)
if err == nil {
accountDefault.Overdraft = Overdraft
PreURL += fmt.Sprintf(`&Overdraft=%s`, request.URL.Query().Get(`Overdraft`))
}
CurrencyId, err := strconv.Atoi(request.URL.Query().Get(`CurrencyId`))
if err == nil {
accountDefault.CurrencyId = int64(CurrencyId)
PreURL += fmt.Sprintf(`&CurrencyId=%s`, request.URL.Query().Get(`CurrencyId`))
}
TypeId, err := strconv.Atoi(request.URL.Query().Get(`TypeId`))
if err == nil {
accountDefault.TypeId = int64(TypeId)
PreURL += fmt.Sprintf(`&TypeId=%s`, request.URL.Query().Get(`TypeId`))
}
Saldo, err := strconv.ParseFloat(request.URL.Query().Get(`Saldo`), 64)
if err == nil {
accountDefault.Saldo = Saldo
PreURL += fmt.Sprintf(`&Saldo=%s`, request.URL.Query().Get(`Saldo`))
}
AccNum := request.URL.Query().Get(`AccNum`)
if AccNum != `` {
accountDefault.AccNum = AccNum
PreURL += fmt.Sprintf(`&AccNum=%s`, request.URL.Query().Get(`AccNum`))
}
IsActive, err := strconv.ParseBool(request.URL.Query().Get(`IsActive`))
if err == nil {
accountDefault.IsActive = IsActive
PreURL += fmt.Sprintf(`&IsActive=%s`, request.URL.Query().Get(`IsActive`))
}
IsDefault, err := strconv.ParseBool(request.URL.Query().Get(`IsDefault`))
if err == nil {
accountDefault.IsDefault = IsDefault
PreURL += fmt.Sprintf(`&IsDefault=%s`, request.URL.Query().Get(`IsDefault`))
}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
fmt.Println(accountDefault)
var response hamsoyamodels.ResponseHamsoyaAccount
response = hamsoyamodels.GetHamsoyaAccountsCount(accountDefault, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
response.URL = URL + PreURL
fmt.Println(response.URL)
hamsoyamodels.GetHamsoyaAccounts(accountDefault, &response, interval, int64(pageInt)-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
// Get Hamsoya Client
func (server *MainServer) GetHamsoyaClientByIdHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id, err := strconv.Atoi(params.ByName("id"))
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("invalid_id")
if err != nil {
log.Print(err)
return
}
return
}
Client, err := hamsoyamodels.GetHamsoyaClientById(int64(id))
if err != nil {
writer.WriteHeader(http.StatusConflict)
err := json.NewEncoder(writer).Encode("server wrong")
if err != nil {
log.Print(err)
return
}
return
}
err = json.NewEncoder(writer).Encode(&Client)
if err != nil {
log.Print("invalid_HamsoyaPrecheck.")
return
}
}
// Get Hamsoya Clients
func (server *MainServer) GetHamsoyaClientsHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
pageInt := 1
page := request.URL.Query().Get(`page`)
PreURL := ``
URL := `http://127.0.0.1:8080/api/hamsoya/clients`
pageInt, errPage := strconv.Atoi(page)
if errPage != nil {
pageInt = 1
URL += `?page=1`
}
var clientDefault hamsoyamodels.HamsoyaClient
IsActive, err := strconv.ParseBool(request.URL.Query().Get(`IsActive`))
if err == nil {
clientDefault.IsActive = IsActive
PreURL += fmt.Sprintf(`&IsActive=%s`, request.URL.Query().Get(`IsActive`))
}
Identify, err := strconv.ParseBool(request.URL.Query().Get(`Identify`))
if err == nil {
clientDefault.Identify = Identify
PreURL += fmt.Sprintf(`&Identify=%s`, request.URL.Query().Get(`Identify`))
}
PhoneNum := request.URL.Query().Get(`PhoneNum`)
if PhoneNum != `` {
clientDefault.PhoneNum = PhoneNum
PreURL += `&PhoneNum=` + PhoneNum
}
Name := request.URL.Query().Get(`Name`)
if Name != `` {
clientDefault.Name = Name
PreURL += `&Name=` + Name
}
id, err := strconv.Atoi(request.URL.Query().Get(`id`))
if err == nil {
clientDefault.Id = int64(id)
PreURL += fmt.Sprintf(`&id=%s`, request.URL.Query().Get(`id`))
}
AgentId, err := strconv.Atoi(request.URL.Query().Get(`AgentId`))
if err == nil {
clientDefault.AgentId = int64(AgentId)
PreURL += fmt.Sprintf(`&AgentId=%s`, request.URL.Query().Get(`AgentId`))
}
TypeId, err := strconv.Atoi(request.URL.Query().Get(`TypeId`))
if err == nil {
clientDefault.TypeId = int64(TypeId)
PreURL += fmt.Sprintf(`&TypeId=%s`, request.URL.Query().Get(`TypeId`))
}
//Default-ные значение времени. типа с начало до конца
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
from /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response hamsoyamodels.ResponseHamsoyaClients
response = hamsoyamodels.GetHamsoyaClientsCount(clientDefault, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if errPage == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
response.URL = URL + PreURL
fmt.Println(response.URL)
hamsoyamodels.GetHamsoyaClients(clientDefault, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
func (server *MainServer) GetHamsoyaViewTransesHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
fmt.Println("I am view Trans")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
transaction := hamsoyamodels.HamsoyaViewTrans{}
PreURL := ``
Id, err := strconv.Atoi(request.URL.Query().Get(`Id`))
if err == nil {
transaction.ID = int64(Id)
PreURL += `&Id=` + request.URL.Query().Get(`Id`)
}
VendorID, err := strconv.Atoi(request.URL.Query().Get(`VendorID`))
if err == nil {
transaction.VendorID = int64(VendorID)
PreURL += `&VendorID=` + request.URL.Query().Get(`VendorID`)
}
ExtTransId := request.URL.Query().Get(`ExtTransId`)
if ExtTransId != `` {
transaction.ExtTransId = ExtTransId
PreURL += `&ExtTransId=` + request.URL.Query().Get(`ExtTransId`)
}
RequestType := request.URL.Query().Get(`RequestType`)
if ExtTransId != `` {
transaction.RequestType = RequestType
PreURL += `&RequestType=` + request.URL.Query().Get(`RequestType`)
}
PhoneNum := request.URL.Query().Get(`PhoneNum`)
if ExtTransId != `` {
transaction.PhoneNum = PhoneNum
PreURL += `&PhoneNum=` + request.URL.Query().Get(`PhoneNum`)
}
ClientReceiver := request.URL.Query().Get(`ClientReceiver`)
if ExtTransId != `` {
transaction.ClientReceiver = ClientReceiver
PreURL += `&ClientReceiver=` + request.URL.Query().Get(`ClientReceiver`)
}
Amount, err := strconv.ParseFloat(request.URL.Query().Get(`Amount`), 64)
if err == nil {
transaction.Amount = Amount
PreURL += `&Amount=` + request.URL.Query().Get(`Amount`)
}
TotalAmount, err := strconv.ParseFloat(request.URL.Query().Get(`TotalAmount`), 64)
if err == nil {
transaction.TotalAmount = TotalAmount
PreURL += `&TotalAmount=` + request.URL.Query().Get(`TotalAmount`)
}
ExternalFee, err := strconv.ParseFloat(request.URL.Query().Get(`ExternalFee`), 64)
if err == nil {
transaction.ExternalFee = ExternalFee
PreURL += `&ExternalFee=` + request.URL.Query().Get(`ExternalFee`)
}
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
var response hamsoyamodels.ResponseHamsoyaTranses
page := request.URL.Query().Get(`page`)
URL := `http://127.0.0.1:8080/api/hamsoya/viewtranses`
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
URL += `?page=1`
}
response = hamsoyamodels.GetHamsoyaViewTransesCount(transaction, interval)
response.TotalPage = int64(math.Ceil(float64(response.TotalPage) / float64(int64(100))))
response.Page = helperfunc.MinOftoInt(int64(pageInt), response.TotalPage)
if err == nil {
URL += `?page=` + fmt.Sprintf("%d", response.Page)
}
URL += PreURL
response.URL = URL
fmt.Println(URL)
hamsoyamodels.GetHamsoyaViewTranses(transaction, &response, interval, response.Page-1)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
func (server *MainServer) GetMegafonStaticHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
fmt.Println("I am view Static")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
PreURL := ``
var interval helperfunc.TimeInterval
unix := time.Unix(0, 0)
interval.From = unix.Format(time.RFC3339)
unixTimeNow := time.Now()
interval.To = unixTimeNow.Format(time.RFC3339)
from, err := strconv.Atoi(request.URL.Query().Get(`from`))
if err == nil {
from /= 1000
i := time.Unix(int64(from), 0)
ans := i.Format(time.RFC3339)
interval.From = ans
PreURL += `&from=` + request.URL.Query().Get(`from`)
}
to, err := strconv.Atoi(request.URL.Query().Get(`to`))
if err == nil {
to /= 1000
i := time.Unix(int64(to), 0)
ans := i.Format(time.RFC3339)
interval.To = ans
PreURL += `&to=` + request.URL.Query().Get(`to`)
}
URL := `http://127.0.0.1:8080/api/static`
response := models.GetMegafonStatic(interval)
fmt.Println(URL)
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
}
}
///Cancel Megafon Transaction
func (server *MainServer) CancelMegafonTransactionHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id := params.ByName(`id`)
link := settings.AppSettings.LinkForCancelTransaction.Link + id
ok := models.CancelMegafonTransaction(settings.AppSettings.LinkForCancelTransaction.Link)
fmt.Println(link)
if !ok {
writer.WriteHeader(http.StatusBadRequest)
return
}
writer.WriteHeader(http.StatusOK)
return
}
func (server *MainServer) ChangePasswordHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
id := request.Header.Get("ID")
fmt.Println("id = ", id)
var requestBody helperfunc.PasswordChange
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
err = server.userSvc.ChangeUserPass(id, requestBody.Pass, requestBody.NewPass)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
err = json.NewEncoder(writer).Encode("success")
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
return
}
func (server *MainServer) GetUsersHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
response, err := server.userSvc.GetUsers()
if err != nil {
log.Print(err)
writer.WriteHeader(http.StatusBadRequest)
return
}
err = json.NewEncoder(writer).Encode(&response)
if err != nil {
log.Print(err)
writer.WriteHeader(http.StatusBadRequest)
return
}
return
}
func (server *MainServer) AddUserHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
var requestBody models.User
err := json.NewDecoder(request.Body).Decode(&requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
err = server.userSvc.AddNewUser(requestBody)
if err != nil {
log.Print(err)
writer.WriteHeader(http.StatusBadRequest)
return
}
err = json.NewEncoder(writer).Encode("success")
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
return
}
func (server *MainServer) RemoveUserHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
// fmt.Println("id = ", id)
type id struct {
ID string `json:"id"`
}
var requestBody id
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
err = server.userSvc.RemoveUser(requestBody.ID)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
err = json.NewEncoder(writer).Encode("success")
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
return
}
func (server *MainServer) EditUserHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
// fmt.Println("id = ", id)
var requestBody models.User
err := json.NewDecoder(request.Body).Decode(&requestBody)
fmt.Println(requestBody)
if err != nil {
log.Println(err)
writer.WriteHeader(http.StatusBadRequest)
err := json.NewEncoder(writer).Encode("err.json_invalid")
log.Println(err)
return
}
err = server.userSvc.ChangeUser(requestBody)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
err = json.NewEncoder(writer).Encode("success")
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
log.Println(err)
return
}
return
} |
package main
import("fmt"
"net/http"
"log"
"strings)
type cocktails struct {}
func drinks(w http.ResponseWriter, req * http.Request) {
id := strings.TrimPrefix(req.URL.Path, "/provisions/")
//will be for name cocktails
name := strings.TrimPrefix(req.URL.Path, "/provisions/")
fmt.Fprintf(w, "hello friend!\n")
}
func main(){
var c cocktails
mux := http.NewServeMux()
mux.handle(“/drinks/”, c)
http.ListenAndServe(“:80”, mux)
}
|
/*
Copyright 2021 The Skaffold 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 docker
import (
"context"
"fmt"
"io"
"math"
"path"
"strings"
"sync"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/go-connections/nat"
"github.com/fatih/semgroup"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/constants"
dockerport "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/deploy/docker/port"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/deploy/label"
dockerutil "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/docker"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/docker/logger"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/docker/tracker"
eventV2 "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/event/v2"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/graph"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/log"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/output"
olog "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/output/log"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/schema/latest"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/status"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/util"
)
// Verifier verifies deployments using Docker libs/CLI.
type Verifier struct {
logger log.Logger
monitor status.Monitor
cfg []*latest.VerifyTestCase
tracker *tracker.ContainerTracker
portManager *dockerport.PortManager // functions as Accessor
client dockerutil.LocalDaemon
network string
networkFlagPassed bool
globalConfig string
insecureRegistries map[string]bool
envMap map[string]string
resources []*latest.PortForwardResource
once sync.Once
}
func NewVerifier(ctx context.Context, cfg dockerutil.Config, labeller *label.DefaultLabeller, testCases []*latest.VerifyTestCase, resources []*latest.PortForwardResource, network string, envMap map[string]string) (*Verifier, error) {
client, err := dockerutil.NewAPIClient(ctx, cfg)
if err != nil {
return nil, err
}
tracker := tracker.NewContainerTracker()
l, err := logger.NewLogger(ctx, tracker, cfg, false)
if err != nil {
return nil, err
}
networkFlagPassed := false
ntwrk := fmt.Sprintf("skaffold-network-%s", labeller.GetRunID())
if network != "" {
networkFlagPassed = true
ntwrk = network
}
return &Verifier{
cfg: testCases,
client: client,
network: ntwrk,
networkFlagPassed: networkFlagPassed,
resources: resources,
globalConfig: cfg.GlobalConfig(),
insecureRegistries: cfg.GetInsecureRegistries(),
envMap: envMap,
tracker: tracker,
portManager: dockerport.NewPortManager(), // fulfills Accessor interface
logger: l,
monitor: &status.NoopMonitor{},
}, nil
}
func (v *Verifier) TrackBuildArtifacts(artifacts []graph.Artifact) {
v.logger.RegisterArtifacts(artifacts)
}
// TrackContainerFromBuild adds an artifact and its newly-associated container
// to the container tracker.
func (v *Verifier) TrackContainerFromBuild(artifact graph.Artifact, container tracker.Container) {
v.tracker.Add(artifact, container)
}
// Verify executes specified artifacts by creating containers in the local docker daemon
// from each specified image, executing them, and waiting for execution to complete.
func (v *Verifier) Verify(ctx context.Context, out io.Writer, allbuilds []graph.Artifact) error {
var err error
if !v.networkFlagPassed {
v.once.Do(func() {
err = v.client.NetworkCreate(ctx, v.network, nil)
})
if err != nil {
return fmt.Errorf("creating skaffold network %s: %w", v.network, err)
}
}
builds := []graph.Artifact{}
const maxWorkers = math.MaxInt64
s := semgroup.NewGroup(context.Background(), maxWorkers)
for _, tc := range v.cfg {
var na graph.Artifact
foundArtifact := false
testCase := tc
for _, b := range allbuilds {
if tc.Container.Image == b.ImageName {
foundArtifact = true
imageID, err := v.client.ImageID(ctx, b.Tag)
if err != nil {
return fmt.Errorf("getting imageID for %q: %w", b.Tag, err)
}
if imageID == "" {
// not available in local docker daemon, needs to be pulled
if err := v.client.Pull(ctx, out, b.Tag, v1.Platform{}); err != nil {
return err
}
}
na = graph.Artifact{
ImageName: tc.Container.Image,
Tag: b.Tag,
}
builds = append(builds, graph.Artifact{
ImageName: tc.Container.Image,
Tag: tc.Name,
})
break
}
}
if !foundArtifact {
if err := v.client.Pull(ctx, out, tc.Container.Image, v1.Platform{}); err != nil {
return err
}
na = graph.Artifact{
ImageName: tc.Container.Image,
Tag: tc.Container.Image,
}
builds = append(builds, graph.Artifact{
ImageName: tc.Container.Image,
Tag: tc.Name,
})
}
s.Go(func() error {
return v.createAndRunContainer(ctx, out, na, *testCase)
})
}
v.TrackBuildArtifacts(builds)
return s.Wait()
}
// createAndRunContainer creates and runs a container in the local docker daemon from the specified verify image.
func (v *Verifier) createAndRunContainer(ctx context.Context, out io.Writer, artifact graph.Artifact, tc latest.VerifyTestCase) error {
out, ctx = output.WithEventContext(ctx, out, constants.Verify, tc.Name)
if container, found := v.tracker.ContainerForImage(artifact.ImageName); found {
olog.Entry(ctx).Debugf("removing old container %s for image %s", container.ID, artifact.ImageName)
v.client.Stop(ctx, container.ID, nil)
if err := v.client.Remove(ctx, container.ID); err != nil {
return fmt.Errorf("failed to remove old container %s for image %s: %w", container.ID, artifact.ImageName, err)
}
v.portManager.RelinquishPorts(container.Name)
}
containerCfg, err := v.containerConfigFromImage(ctx, artifact.Tag)
if err != nil {
return err
}
// user has set the container Entrypoint, use user value
if len(tc.Container.Command) != 0 {
containerCfg.Entrypoint = tc.Container.Command
}
// user has set the container Cmd values, use user value
if len(tc.Container.Args) != 0 {
containerCfg.Cmd = tc.Container.Args
}
containerName := v.getContainerName(ctx, artifact.ImageName)
opts := dockerutil.ContainerCreateOpts{
Name: containerName,
Network: v.network,
ContainerConfig: containerCfg,
VerifyTestName: tc.Name,
}
bindings, err := v.portManager.AllocatePorts(artifact.ImageName, v.resources, containerCfg, nat.PortMap{})
if err != nil {
return err
}
opts.Bindings = bindings
// verify waits for run to complete
opts.Wait = true
// adding in env vars from verify container schema field
envVars := []string{}
for _, env := range tc.Container.Env {
envVars = append(envVars, env.Name+"="+env.Value)
}
// adding in env vars parsed from --verify-env-file flag
for k, v := range v.envMap {
envVars = append(envVars, k+"="+v)
}
opts.ContainerConfig.Env = envVars
eventV2.VerifyInProgress(opts.VerifyTestName)
statusCh, errCh, id, err := v.client.Run(ctx, out, opts)
if err != nil {
eventV2.VerifyFailed(tc.Name, err)
return errors.Wrap(err, "creating container in local docker")
}
v.TrackContainerFromBuild(graph.Artifact{
ImageName: opts.VerifyTestName,
Tag: opts.VerifyTestName,
}, tracker.Container{Name: containerName, ID: id})
var timeoutDuration *time.Duration = nil
if tc.Config.Timeout != nil {
timeoutDuration = util.Ptr(time.Second * time.Duration(*tc.Config.Timeout))
}
var containerErr error
select {
case err := <-errCh:
if err != nil {
containerErr = err
}
case status := <-statusCh:
if status.StatusCode != 0 {
containerErr = errors.New(fmt.Sprintf("%q running container image %q errored during run with status code: %d", opts.VerifyTestName, opts.ContainerConfig.Image, status.StatusCode))
}
case <-v.timeout(timeoutDuration):
// verify test timed out
containerErr = errors.New(fmt.Sprintf("%q running container image %q timed out after : %v", opts.VerifyTestName, opts.ContainerConfig.Image, *timeoutDuration))
v.client.Stop(ctx, id, util.Ptr(time.Second*0))
err := v.client.Remove(ctx, id)
if err != nil {
return errors.Wrap(containerErr, err.Error())
}
}
if containerErr != nil {
eventV2.VerifyFailed(tc.Name, containerErr)
return errors.Wrap(containerErr, "verify test failed")
}
eventV2.VerifySucceeded(opts.VerifyTestName)
return nil
}
func (v *Verifier) containerConfigFromImage(ctx context.Context, taggedImage string) (*container.Config, error) {
config, _, err := v.client.ImageInspectWithRaw(ctx, taggedImage)
if err != nil {
return nil, err
}
config.Config.Image = taggedImage // the client replaces this with an image ID. put back the originally provided tagged image
return config.Config, err
}
func (v *Verifier) getContainerName(ctx context.Context, name string) string {
// this is done to fix the for naming convention of non-skaffold built images which verify supports
name = path.Base(strings.Split(name, ":")[0])
currentName := name
for {
if !v.client.ContainerExists(ctx, currentName) {
break
}
currentName = fmt.Sprintf("%s-%s", name, uuid.New().String()[0:8])
}
if currentName != name {
olog.Entry(ctx).Debugf("container %s already present in local daemon: using %s instead", name, currentName)
}
return currentName
}
func (v *Verifier) Dependencies() ([]string, error) {
// noop since there is no deploy config
return nil, nil
}
func (v *Verifier) Cleanup(ctx context.Context, out io.Writer, dryRun bool) error {
if dryRun {
for _, container := range v.tracker.DeployedContainers() {
output.Yellow.Fprintln(out, container.ID)
}
return nil
}
for _, container := range v.tracker.DeployedContainers() {
v.client.Stop(ctx, container.ID, nil)
if err := v.client.Remove(ctx, container.ID); err != nil {
olog.Entry(ctx).Debugf("cleaning up deployed container: %s", err.Error())
}
v.portManager.RelinquishPorts(container.ID)
}
if !v.networkFlagPassed {
err := v.client.NetworkRemove(ctx, v.network)
return errors.Wrap(err, "cleaning up skaffold created network")
}
return nil
}
func (v *Verifier) GetLogger() log.Logger {
return v.logger
}
func (v *Verifier) GetStatusMonitor() status.Monitor {
return v.monitor
}
func (v *Verifier) RegisterLocalImages([]graph.Artifact) {
// all images are local, so this is a noop
}
func (v *Verifier) timeout(duration *time.Duration) <-chan time.Time {
if duration != nil {
return time.After(*duration)
}
// Nil channel will never emit a value, so it will simulate an endless timeout.
return nil
}
|
package function
import (
"encoding/json"
"math/rand"
"net/http"
"time"
)
// PasswordSpec is function body reference
type PasswordSpec struct {
Length int `json:"length,omitempty"`
UpperCaseNum int `json:"upper_case_num,omitempty"`
DigitNum int `json:"digit_num,omitempty"`
SpecialCharNum int `json:"special_char_num,omitempty"`
}
// ResponseCode is code of each response
type ResponseCode struct {
Code int `json:"code"`
}
// Response is the structure of function response
type Response struct {
ResponseCode
Password string `json:"password"`
}
// Handle is the function main method triggered each time the function is called
func Handle(req []byte) string {
var passwordSpec PasswordSpec
var encodedResponse []byte
var err error
passwordSpec.Length = 8
passwordSpec.UpperCaseNum = 1
passwordSpec.DigitNum = 1
passwordSpec.SpecialCharNum = 1
if len(req) != 0 {
err = json.Unmarshal(req, &passwordSpec)
}
if err != nil {
marshalJSON, _ := json.Marshal(ResponseCode{Code: http.StatusBadRequest})
encodedResponse = marshalJSON
} else {
marshalJSON, _ := json.Marshal(Response{ResponseCode{Code: http.StatusOK}, generate(passwordSpec)})
encodedResponse = marshalJSON
}
return string(encodedResponse)
}
func generate(passwordSpec PasswordSpec) string {
rand.Seed(time.Now().UTC().UnixNano())
upperCaseLetters := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
digits := []rune("0123456789")
specialChars := []rune("/-+!\\:;[]{}_$#@")
allChars := append(
append(upperCaseLetters, []rune("abcdefghijklmnopqrstuvwxyz")...),
append(digits, specialChars...)...,
)
upperCaseUsed, digitUsed, specialChar := 0, 0, 0
passwordLength := passwordSpec.Length
minimalRequiredCharsLength := passwordSpec.UpperCaseNum + passwordSpec.DigitNum + passwordSpec.SpecialCharNum
if passwordLength < minimalRequiredCharsLength {
passwordLength = minimalRequiredCharsLength
}
passwordArray := make([]rune, passwordLength)
for index := range passwordArray {
if passwordSpec.UpperCaseNum != upperCaseUsed {
passwordArray[index] = upperCaseLetters[rand.Intn(len(upperCaseLetters))]
upperCaseUsed++
} else if passwordSpec.DigitNum != digitUsed {
passwordArray[index] = digits[rand.Intn(len(digits))]
digitUsed++
} else if passwordSpec.SpecialCharNum != specialChar {
passwordArray[index] = specialChars[rand.Intn(len(specialChars))]
specialChar++
} else {
passwordArray[index] = allChars[rand.Intn(len(allChars))]
}
}
return string(passwordArray)
}
|
// Copyright 2019 The gVisor 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.
//go:build amd64
// +build amd64
package linux
// EpollEvent is equivalent to struct epoll_event from epoll(2).
//
// +marshal slice:EpollEventSlice
type EpollEvent struct {
Events uint32
// Linux makes struct epoll_event::data a __u64. We represent it as
// [2]int32 because, on amd64, Linux also makes struct epoll_event
// __attribute__((packed)), such that there is no padding between Events
// and Data.
Data [2]int32
}
|
//This file contains code for node info and user info
//@author Devansh Gupta
//facebook.com/devansh42
//github.com/devansh42
package utils
import "strings"
type NodeInfo struct {
Name string
Email string
Contact string
Domain string
Id int64
Pubkey string
}
//Map for userinfo tree
type UserInfo map[byte]interface{}
//GetUserInfoKey, Returns byte key in for string key of the user info
func GetUserInfoKey(key string) (re byte) {
key = strings.TrimSpace(key)
key = strings.ToLower(key)
switch key {
case "fname":
re = 1
case "mname":
re = 2
case "lname":
re = 3
case "dob":
re = 4
case "gender":
re = 5
case "cid":
re = 6
case "passcode":
re = 7
case "password":
re = 8
case "username":
re = 9
case "timestamp":
re = 10
case "pubaddr":
re = 11
default:
re = 0
}
return
}
|
package resample_test
import (
"fmt"
"github.com/paulmach/orb"
"github.com/paulmach/orb/planar"
"github.com/paulmach/orb/resample"
)
func ExampleResample() {
ls := orb.LineString{
{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0},
{5, 0}, {6, 0}, {7, 0}, {8, 0}, {9, 0}, {10, 0},
}
// downsample in this case so there are 2.5 units between points
ls = resample.ToInterval(ls, planar.Distance, 2.5)
fmt.Println(ls)
// Output:
// [[0 0] [2.5 0] [5 0] [7.5 0] [10 0]]
}
func ExampleToInterval() {
ls := orb.LineString{{0, 0}, {10, 0}}
// upsample so there are 6 total points
ls = resample.Resample(ls, planar.Distance, 6)
fmt.Println(ls)
// Output:
// [[0 0] [2 0] [4 0] [6 0] [8 0] [10 0]]
}
|
package pipelineconfig
import (
"log"
"alauda.io/devops-apiserver/pkg/apis/devops/v1alpha1"
devopsclient "alauda.io/devops-apiserver/pkg/client/clientset/versioned"
)
// RenderJenkinsfile render jenkinsfile
func RenderJenkinsfile(client devopsclient.Interface, namespace string, spec *PipelineConfigDetail) (jenkinsfile string, err error) {
opts := &v1alpha1.JenkinsfilePreviewOptions{
PipelineConfigSpec: &spec.Spec,
}
name := spec.PipelineConfig.ObjectMeta.Name
result, err := client.DevopsV1alpha1().PipelineConfigs(namespace).Preview(name, opts)
if err != nil {
log.Printf("jenkinsfile preview error: %v", err)
return "", err
}
return result.Jenkinsfile, nil
}
|
package main
import (
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/exercism/cli/configuration"
"github.com/stretchr/testify/assert"
)
func assertFileDoesNotExist(t *testing.T, filename string) {
_, err := os.Stat(filename)
if err == nil {
t.Errorf("File [%s] already exist.", filename)
}
}
func TestLogoutDeletesConfigFile(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "")
assert.NoError(t, err)
c := configuration.Config{}
configuration.ToFile(tmpDir, c)
logout(tmpDir)
assertFileDoesNotExist(t, configuration.Filename(tmpDir))
}
func TestAskForConfigInfoAllowsSpaces(t *testing.T) {
oldStdin := os.Stdin
dirName := "dirname with spaces"
userName := "TestUsername"
apiKey := "abc123"
fakeStdin, err := ioutil.TempFile("", "stdin_mock")
assert.NoError(t, err)
fakeStdin.WriteString(fmt.Sprintf("%s\r\n%s\r\n%s\r\n", userName, apiKey, dirName))
assert.NoError(t, err)
_, err = fakeStdin.Seek(0, os.SEEK_SET)
assert.NoError(t, err)
defer fakeStdin.Close()
os.Stdin = fakeStdin
c, err := askForConfigInfo()
if err != nil {
t.Errorf("Error asking for configuration info [%v]", err)
}
os.Stdin = oldStdin
absoluteDirName, _ := absolutePath(dirName)
_, err = os.Stat(absoluteDirName)
if err != nil {
t.Errorf("Excercism directory [%s] was not created.", absoluteDirName)
}
os.Remove(absoluteDirName)
os.Remove(fakeStdin.Name())
assert.Equal(t, c.ExercismDirectory, absoluteDirName)
assert.Equal(t, c.GithubUsername, userName)
assert.Equal(t, c.ApiKey, apiKey)
}
|
//https://tour.golang.org/moretypes/2
//here are structs, simmiliar to the classes we are used to in ruby. However structs have been a thing for a while, theyre a core datatype in C.
//https://flaviocopes.com/golang-is-go-object-oriented/
package main
import "fmt"
type position struct{ //declaration syntax will take some getting used to
x int // declare attributes and there datatypes
y int
}
func main(){
pos := position{4, 19} // declarea and init pos variable to a new position 'instance' i guess, variabes assigned proceduraly
fmt.Println(pos)
//you can also use key value pairs to assign attributes
newPos := position{y:4, x:19}
fmt.Println(newPos)
fmt.Println(pos.x) //dot notation to get attributes
fmt.Println(newPos.x)
}
|
package api_test
import (
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/porter-dev/porter/internal/config"
"github.com/porter-dev/porter/internal/helm"
"github.com/porter-dev/porter/internal/kubernetes"
lr "github.com/porter-dev/porter/internal/logger"
"github.com/porter-dev/porter/internal/repository"
memory "github.com/porter-dev/porter/internal/repository/memory"
"github.com/porter-dev/porter/server/api"
"github.com/porter-dev/porter/server/router"
"github.com/porter-dev/porter/internal/auth/sessionstore"
)
type tester struct {
app *api.App
repo *repository.Repository
store *sessionstore.PGStore
router *chi.Mux
req *http.Request
rr *httptest.ResponseRecorder
cookie *http.Cookie
}
func (t *tester) execute() {
t.router.ServeHTTP(t.rr, t.req)
}
func (t *tester) reset() {
t.rr = httptest.NewRecorder()
t.req = nil
}
func (t *tester) createUserSession(email string, pw string) {
req, err := http.NewRequest(
"POST",
"/api/users",
strings.NewReader(`{"email":"`+email+`","password":"`+pw+`"}`),
)
if err != nil {
panic(err)
}
t.req = req
t.execute()
if cookies := t.rr.Result().Cookies(); len(cookies) > 0 {
t.cookie = cookies[0]
}
t.reset()
}
func newTester(canQuery bool) *tester {
appConf := config.Conf{
Debug: true,
Server: config.ServerConf{
Port: 8080,
CookieName: "porter",
CookieSecrets: []string{"secret"},
TimeoutRead: time.Second * 5,
TimeoutWrite: time.Second * 10,
TimeoutIdle: time.Second * 15,
IsTesting: true,
TokenGeneratorSecret: "secret",
BasicLoginEnabled: true,
},
// unimportant here
Db: config.DBConf{},
// set the helm config to testing
K8s: config.K8sConf{
IsTesting: true,
},
}
logger := lr.NewConsole(appConf.Debug)
repo := memory.NewRepository(canQuery)
store, _ := sessionstore.NewStore(repo, appConf.Server)
k8sAgent := kubernetes.GetAgentTesting()
app, _ := api.New(&api.AppConfig{
Logger: logger,
Repository: repo,
ServerConf: appConf.Server,
TestAgents: &api.TestAgents{
HelmAgent: helm.GetAgentTesting(&helm.Form{}, nil, logger, k8sAgent),
HelmTestStorageDriver: helm.StorageMap["memory"](nil, nil, ""),
K8sAgent: k8sAgent,
},
})
r := router.New(app)
return &tester{
app: app,
repo: repo,
store: store,
router: r,
req: nil,
rr: httptest.NewRecorder(),
cookie: nil,
}
}
|
// Copyright 2018 The gVisor 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 kernel
// CPU scheduling, real and fake.
import (
"fmt"
"math/rand"
"time"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/errors/linuxerr"
"gvisor.dev/gvisor/pkg/sentry/hostcpu"
"gvisor.dev/gvisor/pkg/sentry/kernel/sched"
ktime "gvisor.dev/gvisor/pkg/sentry/kernel/time"
"gvisor.dev/gvisor/pkg/sentry/limits"
"gvisor.dev/gvisor/pkg/sentry/usage"
)
// TaskGoroutineState is a coarse representation of the current execution
// status of a kernel.Task goroutine.
type TaskGoroutineState int
const (
// TaskGoroutineNonexistent indicates that the task goroutine has either
// not yet been created by Task.Start() or has returned from Task.run().
// This must be the zero value for TaskGoroutineState.
TaskGoroutineNonexistent TaskGoroutineState = iota
// TaskGoroutineRunningSys indicates that the task goroutine is executing
// sentry code.
TaskGoroutineRunningSys
// TaskGoroutineRunningApp indicates that the task goroutine is executing
// application code.
TaskGoroutineRunningApp
// TaskGoroutineBlockedInterruptible indicates that the task goroutine is
// blocked in Task.block(), and hence may be woken by Task.interrupt()
// (e.g. due to signal delivery).
TaskGoroutineBlockedInterruptible
// TaskGoroutineBlockedUninterruptible indicates that the task goroutine is
// stopped outside of Task.block() and Task.doStop(), and hence cannot be
// woken by Task.interrupt().
TaskGoroutineBlockedUninterruptible
// TaskGoroutineStopped indicates that the task goroutine is blocked in
// Task.doStop(). TaskGoroutineStopped is similar to
// TaskGoroutineBlockedUninterruptible, but is a separate state to make it
// possible to determine when Task.stop is meaningful.
TaskGoroutineStopped
)
// TaskGoroutineSchedInfo contains task goroutine scheduling state which must
// be read and updated atomically.
//
// +stateify savable
type TaskGoroutineSchedInfo struct {
// Timestamp was the value of Kernel.cpuClock when this
// TaskGoroutineSchedInfo was last updated.
Timestamp uint64
// State is the current state of the task goroutine.
State TaskGoroutineState
// UserTicks is the amount of time the task goroutine has spent executing
// its associated Task's application code, in units of linux.ClockTick.
UserTicks uint64
// SysTicks is the amount of time the task goroutine has spent executing in
// the sentry, in units of linux.ClockTick.
SysTicks uint64
}
// userTicksAt returns the extrapolated value of ts.UserTicks after
// Kernel.CPUClockNow() indicates a time of now.
//
// Preconditions: now <= Kernel.CPUClockNow(). (Since Kernel.cpuClock is
// monotonic, this is satisfied if now is the result of a previous call to
// Kernel.CPUClockNow().) This requirement exists because otherwise a racing
// change to t.gosched can cause userTicksAt to adjust stats by too much,
// making the observed stats non-monotonic.
func (ts *TaskGoroutineSchedInfo) userTicksAt(now uint64) uint64 {
if ts.Timestamp < now && ts.State == TaskGoroutineRunningApp {
// Update stats to reflect execution since the last update.
return ts.UserTicks + (now - ts.Timestamp)
}
return ts.UserTicks
}
// sysTicksAt returns the extrapolated value of ts.SysTicks after
// Kernel.CPUClockNow() indicates a time of now.
//
// Preconditions: As for userTicksAt.
func (ts *TaskGoroutineSchedInfo) sysTicksAt(now uint64) uint64 {
if ts.Timestamp < now && ts.State == TaskGoroutineRunningSys {
return ts.SysTicks + (now - ts.Timestamp)
}
return ts.SysTicks
}
// Preconditions: The caller must be running on the task goroutine.
func (t *Task) accountTaskGoroutineEnter(state TaskGoroutineState) {
now := t.k.CPUClockNow()
if t.gosched.State != TaskGoroutineRunningSys {
panic(fmt.Sprintf("Task goroutine switching from state %v (expected %v) to %v", t.gosched.State, TaskGoroutineRunningSys, state))
}
t.goschedSeq.BeginWrite()
// This function is very hot; avoid defer.
t.gosched.SysTicks += now - t.gosched.Timestamp
t.gosched.Timestamp = now
t.gosched.State = state
t.goschedSeq.EndWrite()
if state != TaskGoroutineRunningApp {
// Task is blocking/stopping.
t.k.decRunningTasks()
}
}
// Preconditions:
// - The caller must be running on the task goroutine
// - The caller must be leaving a state indicated by a previous call to
// t.accountTaskGoroutineEnter(state).
func (t *Task) accountTaskGoroutineLeave(state TaskGoroutineState) {
if state != TaskGoroutineRunningApp {
// Task is unblocking/continuing.
t.k.incRunningTasks()
}
now := t.k.CPUClockNow()
if t.gosched.State != state {
panic(fmt.Sprintf("Task goroutine switching from state %v (expected %v) to %v", t.gosched.State, state, TaskGoroutineRunningSys))
}
t.goschedSeq.BeginWrite()
// This function is very hot; avoid defer.
if state == TaskGoroutineRunningApp {
t.gosched.UserTicks += now - t.gosched.Timestamp
}
t.gosched.Timestamp = now
t.gosched.State = TaskGoroutineRunningSys
t.goschedSeq.EndWrite()
}
// Preconditions: The caller must be running on the task goroutine.
func (t *Task) accountTaskGoroutineRunning() {
now := t.k.CPUClockNow()
if t.gosched.State != TaskGoroutineRunningSys {
panic(fmt.Sprintf("Task goroutine in state %v (expected %v)", t.gosched.State, TaskGoroutineRunningSys))
}
t.goschedSeq.BeginWrite()
t.gosched.SysTicks += now - t.gosched.Timestamp
t.gosched.Timestamp = now
t.goschedSeq.EndWrite()
}
// TaskGoroutineSchedInfo returns a copy of t's task goroutine scheduling info.
// Most clients should use t.CPUStats() instead.
func (t *Task) TaskGoroutineSchedInfo() TaskGoroutineSchedInfo {
return SeqAtomicLoadTaskGoroutineSchedInfo(&t.goschedSeq, &t.gosched)
}
// CPUStats returns the CPU usage statistics of t.
func (t *Task) CPUStats() usage.CPUStats {
return t.cpuStatsAt(t.k.CPUClockNow())
}
// Preconditions: As for TaskGoroutineSchedInfo.userTicksAt.
func (t *Task) cpuStatsAt(now uint64) usage.CPUStats {
tsched := t.TaskGoroutineSchedInfo()
return usage.CPUStats{
UserTime: time.Duration(tsched.userTicksAt(now) * uint64(linux.ClockTick)),
SysTime: time.Duration(tsched.sysTicksAt(now) * uint64(linux.ClockTick)),
VoluntarySwitches: t.yieldCount.Load(),
}
}
// CPUStats returns the combined CPU usage statistics of all past and present
// threads in tg.
func (tg *ThreadGroup) CPUStats() usage.CPUStats {
tg.pidns.owner.mu.RLock()
defer tg.pidns.owner.mu.RUnlock()
// Hack to get a pointer to the Kernel.
if tg.leader == nil {
// Per comment on tg.leader, this is only possible if nothing in the
// ThreadGroup has ever executed anyway.
return usage.CPUStats{}
}
return tg.cpuStatsAtLocked(tg.leader.k.CPUClockNow())
}
// Preconditions: Same as TaskGoroutineSchedInfo.userTicksAt, plus:
// - The TaskSet mutex must be locked.
func (tg *ThreadGroup) cpuStatsAtLocked(now uint64) usage.CPUStats {
stats := tg.exitedCPUStats
// Account for live tasks.
for t := tg.tasks.Front(); t != nil; t = t.Next() {
stats.Accumulate(t.cpuStatsAt(now))
}
return stats
}
// JoinedChildCPUStats implements the semantics of RUSAGE_CHILDREN: "Return
// resource usage statistics for all children of [tg] that have terminated and
// been waited for. These statistics will include the resources used by
// grandchildren, and further removed descendants, if all of the intervening
// descendants waited on their terminated children."
func (tg *ThreadGroup) JoinedChildCPUStats() usage.CPUStats {
tg.pidns.owner.mu.RLock()
defer tg.pidns.owner.mu.RUnlock()
return tg.childCPUStats
}
// taskClock is a ktime.Clock that measures the time that a task has spent
// executing. taskClock is primarily used to implement CLOCK_THREAD_CPUTIME_ID.
//
// +stateify savable
type taskClock struct {
t *Task
// If includeSys is true, the taskClock includes both time spent executing
// application code as well as time spent in the sentry. Otherwise, the
// taskClock includes only time spent executing application code.
includeSys bool
// Implements waiter.Waitable. TimeUntil wouldn't change its estimation
// based on either of the clock events, so there's no event to be
// notified for.
ktime.NoClockEvents `state:"nosave"`
// Implements ktime.Clock.WallTimeUntil.
//
// As an upper bound, a task's clock cannot advance faster than CPU
// time. It would have to execute at a rate of more than 1 task-second
// per 1 CPU-second, which isn't possible.
ktime.WallRateClock `state:"nosave"`
}
// UserCPUClock returns a clock measuring the CPU time the task has spent
// executing application code.
func (t *Task) UserCPUClock() ktime.Clock {
return &taskClock{t: t, includeSys: false}
}
// CPUClock returns a clock measuring the CPU time the task has spent executing
// application and "kernel" code.
func (t *Task) CPUClock() ktime.Clock {
return &taskClock{t: t, includeSys: true}
}
// Now implements ktime.Clock.Now.
func (tc *taskClock) Now() ktime.Time {
stats := tc.t.CPUStats()
if tc.includeSys {
return ktime.FromNanoseconds((stats.UserTime + stats.SysTime).Nanoseconds())
}
return ktime.FromNanoseconds(stats.UserTime.Nanoseconds())
}
// tgClock is a ktime.Clock that measures the time a thread group has spent
// executing. tgClock is primarily used to implement CLOCK_PROCESS_CPUTIME_ID.
//
// +stateify savable
type tgClock struct {
tg *ThreadGroup
// If includeSys is true, the tgClock includes both time spent executing
// application code as well as time spent in the sentry. Otherwise, the
// tgClock includes only time spent executing application code.
includeSys bool
// Implements waiter.Waitable.
ktime.ClockEventsQueue `state:"nosave"`
}
// Now implements ktime.Clock.Now.
func (tgc *tgClock) Now() ktime.Time {
stats := tgc.tg.CPUStats()
if tgc.includeSys {
return ktime.FromNanoseconds((stats.UserTime + stats.SysTime).Nanoseconds())
}
return ktime.FromNanoseconds(stats.UserTime.Nanoseconds())
}
// WallTimeUntil implements ktime.Clock.WallTimeUntil.
func (tgc *tgClock) WallTimeUntil(t, now ktime.Time) time.Duration {
// Thread group CPU time should not exceed wall time * live tasks, since
// task goroutines exit after the transition to TaskExitZombie in
// runExitNotify.
tgc.tg.pidns.owner.mu.RLock()
n := tgc.tg.liveTasks
tgc.tg.pidns.owner.mu.RUnlock()
if n == 0 {
if t.Before(now) {
return 0
}
// The timer tick raced with thread group exit, after which no more
// tasks can enter the thread group. So tgc.Now() will never advance
// again. Return a large delay; the timer should be stopped long before
// it comes again anyway.
return time.Hour
}
// This is a lower bound on the amount of time that can elapse before an
// associated timer expires, so returning this value tends to result in a
// sequence of closely-spaced ticks just before timer expiry. To avoid
// this, round up to the nearest ClockTick; CPU usage measurements are
// limited to this resolution anyway.
remaining := time.Duration(t.Sub(now).Nanoseconds()/int64(n)) * time.Nanosecond
return ((remaining + (linux.ClockTick - time.Nanosecond)) / linux.ClockTick) * linux.ClockTick
}
// UserCPUClock returns a ktime.Clock that measures the time that a thread
// group has spent executing.
func (tg *ThreadGroup) UserCPUClock() ktime.Clock {
return &tgClock{tg: tg, includeSys: false}
}
// CPUClock returns a ktime.Clock that measures the time that a thread group
// has spent executing, including sentry time.
func (tg *ThreadGroup) CPUClock() ktime.Clock {
return &tgClock{tg: tg, includeSys: true}
}
func (k *Kernel) runCPUClockTicker() {
rng := rand.New(rand.NewSource(rand.Int63()))
var tgs []*ThreadGroup
for {
// Stop the CPU clock while nothing is running.
if k.runningTasks.Load() == 0 {
k.runningTasksMu.Lock()
if k.runningTasks.Load() == 0 {
k.cpuClockTickerRunning = false
k.cpuClockTickerStopCond.Broadcast()
k.runningTasksCond.Wait()
// k.cpuClockTickerRunning was set to true by our waker
// (Kernel.incRunningTasks()). For reasons described there, we must
// process at least one CPU clock tick between calls to
// k.runningTasksCond.Wait().
}
k.runningTasksMu.Unlock()
}
// Wait for the next CPU clock tick.
select {
case <-k.cpuClockTickTimer.C:
k.cpuClockTickTimer.Reset(linux.ClockTick)
case <-k.cpuClockTickerWakeCh:
continue
}
// Advance the CPU clock, and timers based on the CPU clock, atomically
// under cpuClockMu.
k.cpuClockMu.Lock()
now := k.cpuClock.Add(1)
// Check thread group CPU timers.
tgs = k.tasks.Root.ThreadGroupsAppend(tgs)
for _, tg := range tgs {
if tg.cpuTimersEnabled.Load() == 0 {
continue
}
k.tasks.mu.RLock()
if tg.leader == nil {
// No tasks have ever run in this thread group.
k.tasks.mu.RUnlock()
continue
}
// Accumulate thread group CPU stats, and randomly select running tasks
// using reservoir sampling to receive CPU timer signals.
var virtReceiver *Task
nrVirtCandidates := 0
var profReceiver *Task
nrProfCandidates := 0
tgUserTime := tg.exitedCPUStats.UserTime
tgSysTime := tg.exitedCPUStats.SysTime
for t := tg.tasks.Front(); t != nil; t = t.Next() {
tsched := t.TaskGoroutineSchedInfo()
tgUserTime += time.Duration(tsched.userTicksAt(now) * uint64(linux.ClockTick))
tgSysTime += time.Duration(tsched.sysTicksAt(now) * uint64(linux.ClockTick))
switch tsched.State {
case TaskGoroutineRunningApp:
// Considered by ITIMER_VIRT, ITIMER_PROF, and RLIMIT_CPU
// timers.
nrVirtCandidates++
if int(randInt31n(rng, int32(nrVirtCandidates))) == 0 {
virtReceiver = t
}
fallthrough
case TaskGoroutineRunningSys:
// Considered by ITIMER_PROF and RLIMIT_CPU timers.
nrProfCandidates++
if int(randInt31n(rng, int32(nrProfCandidates))) == 0 {
profReceiver = t
}
}
}
tgVirtNow := ktime.FromNanoseconds(tgUserTime.Nanoseconds())
tgProfNow := ktime.FromNanoseconds((tgUserTime + tgSysTime).Nanoseconds())
// All of the following are standard (not real-time) signals, which are
// automatically deduplicated, so we ignore the number of expirations.
tg.signalHandlers.mu.Lock()
// It should only be possible for these timers to advance if we found
// at least one running task.
if virtReceiver != nil {
// ITIMER_VIRTUAL
newItimerVirtSetting, exp := tg.itimerVirtSetting.At(tgVirtNow)
tg.itimerVirtSetting = newItimerVirtSetting
if exp != 0 {
virtReceiver.sendSignalLocked(SignalInfoPriv(linux.SIGVTALRM), true)
}
}
if profReceiver != nil {
// ITIMER_PROF
newItimerProfSetting, exp := tg.itimerProfSetting.At(tgProfNow)
tg.itimerProfSetting = newItimerProfSetting
if exp != 0 {
profReceiver.sendSignalLocked(SignalInfoPriv(linux.SIGPROF), true)
}
// RLIMIT_CPU soft limit
newRlimitCPUSoftSetting, exp := tg.rlimitCPUSoftSetting.At(tgProfNow)
tg.rlimitCPUSoftSetting = newRlimitCPUSoftSetting
if exp != 0 {
profReceiver.sendSignalLocked(SignalInfoPriv(linux.SIGXCPU), true)
}
// RLIMIT_CPU hard limit
rlimitCPUMax := tg.limits.Get(limits.CPU).Max
if rlimitCPUMax != limits.Infinity && !tgProfNow.Before(ktime.FromSeconds(int64(rlimitCPUMax))) {
profReceiver.sendSignalLocked(SignalInfoPriv(linux.SIGKILL), true)
}
}
tg.signalHandlers.mu.Unlock()
k.tasks.mu.RUnlock()
}
k.cpuClockMu.Unlock()
// Retain tgs between calls to Notify to reduce allocations.
for i := range tgs {
tgs[i] = nil
}
tgs = tgs[:0]
}
}
// randInt31n returns a random integer in [0, n).
//
// randInt31n is equivalent to math/rand.Rand.int31n(), which is unexported.
// See that function for details.
func randInt31n(rng *rand.Rand, n int32) int32 {
v := rng.Uint32()
prod := uint64(v) * uint64(n)
low := uint32(prod)
if low < uint32(n) {
thresh := uint32(-n) % uint32(n)
for low < thresh {
v = rng.Uint32()
prod = uint64(v) * uint64(n)
low = uint32(prod)
}
}
return int32(prod >> 32)
}
// NotifyRlimitCPUUpdated is called by setrlimit.
//
// Preconditions: The caller must be running on the task goroutine.
func (t *Task) NotifyRlimitCPUUpdated() {
t.k.cpuClockMu.Lock()
defer t.k.cpuClockMu.Unlock()
t.tg.pidns.owner.mu.RLock()
defer t.tg.pidns.owner.mu.RUnlock()
t.tg.signalHandlers.mu.Lock()
defer t.tg.signalHandlers.mu.Unlock()
rlimitCPU := t.tg.limits.Get(limits.CPU)
t.tg.rlimitCPUSoftSetting = ktime.Setting{
Enabled: rlimitCPU.Cur != limits.Infinity,
Next: ktime.FromNanoseconds((time.Duration(rlimitCPU.Cur) * time.Second).Nanoseconds()),
Period: time.Second,
}
if rlimitCPU.Max != limits.Infinity {
// Check if tg is already over the hard limit.
tgcpu := t.tg.cpuStatsAtLocked(t.k.CPUClockNow())
tgProfNow := ktime.FromNanoseconds((tgcpu.UserTime + tgcpu.SysTime).Nanoseconds())
if !tgProfNow.Before(ktime.FromSeconds(int64(rlimitCPU.Max))) {
t.sendSignalLocked(SignalInfoPriv(linux.SIGKILL), true)
}
}
t.tg.updateCPUTimersEnabledLocked()
}
// Preconditions: The signal mutex must be locked.
func (tg *ThreadGroup) updateCPUTimersEnabledLocked() {
rlimitCPU := tg.limits.Get(limits.CPU)
if tg.itimerVirtSetting.Enabled || tg.itimerProfSetting.Enabled || tg.rlimitCPUSoftSetting.Enabled || rlimitCPU.Max != limits.Infinity {
tg.cpuTimersEnabled.Store(1)
} else {
tg.cpuTimersEnabled.Store(0)
}
}
// StateStatus returns a string representation of the task's current state,
// appropriate for /proc/[pid]/status.
func (t *Task) StateStatus() string {
switch s := t.TaskGoroutineSchedInfo().State; s {
case TaskGoroutineNonexistent, TaskGoroutineRunningSys:
t.tg.pidns.owner.mu.RLock()
defer t.tg.pidns.owner.mu.RUnlock()
switch t.exitState {
case TaskExitZombie:
return "Z (zombie)"
case TaskExitDead:
return "X (dead)"
default:
// The task goroutine can't exit before passing through
// runExitNotify, so if s == TaskGoroutineNonexistent, the task has
// been created but the task goroutine hasn't yet started. The
// Linux equivalent is struct task_struct::state == TASK_NEW
// (kernel/fork.c:copy_process() =>
// kernel/sched/core.c:sched_fork()), but the TASK_NEW bit is
// masked out by TASK_REPORT for /proc/[pid]/status, leaving only
// TASK_RUNNING.
return "R (running)"
}
case TaskGoroutineRunningApp:
return "R (running)"
case TaskGoroutineBlockedInterruptible:
return "S (sleeping)"
case TaskGoroutineStopped:
t.tg.signalHandlers.mu.Lock()
defer t.tg.signalHandlers.mu.Unlock()
switch t.stop.(type) {
case *groupStop:
return "T (stopped)"
case *ptraceStop:
return "t (tracing stop)"
}
fallthrough
case TaskGoroutineBlockedUninterruptible:
// This is the name Linux uses for TASK_UNINTERRUPTIBLE and
// TASK_KILLABLE (= TASK_UNINTERRUPTIBLE | TASK_WAKEKILL):
// fs/proc/array.c:task_state_array.
return "D (disk sleep)"
default:
panic(fmt.Sprintf("Invalid TaskGoroutineState: %v", s))
}
}
// CPUMask returns a copy of t's allowed CPU mask.
func (t *Task) CPUMask() sched.CPUSet {
t.mu.Lock()
defer t.mu.Unlock()
return t.allowedCPUMask.Copy()
}
// SetCPUMask sets t's allowed CPU mask based on mask. It takes ownership of
// mask.
//
// Preconditions: mask.Size() ==
// sched.CPUSetSize(t.Kernel().ApplicationCores()).
func (t *Task) SetCPUMask(mask sched.CPUSet) error {
if want := sched.CPUSetSize(t.k.applicationCores); mask.Size() != want {
panic(fmt.Sprintf("Invalid CPUSet %v (expected %d bytes)", mask, want))
}
// Remove CPUs in mask above Kernel.applicationCores.
mask.ClearAbove(t.k.applicationCores)
// Ensure that at least 1 CPU is still allowed.
if mask.NumCPUs() == 0 {
return linuxerr.EINVAL
}
if t.k.useHostCores {
// No-op; pretend the mask was immediately changed back.
return nil
}
t.tg.pidns.owner.mu.RLock()
rootTID := t.tg.pidns.owner.Root.tids[t]
t.tg.pidns.owner.mu.RUnlock()
t.mu.Lock()
defer t.mu.Unlock()
t.allowedCPUMask = mask
t.cpu.Store(assignCPU(mask, rootTID))
return nil
}
// CPU returns the cpu id for a given task.
func (t *Task) CPU() int32 {
if t.k.useHostCores {
return int32(hostcpu.GetCPU())
}
return t.cpu.Load()
}
// assignCPU returns the virtualized CPU number for the task with global TID
// tid and allowedCPUMask allowed.
func assignCPU(allowed sched.CPUSet, tid ThreadID) (cpu int32) {
// To pretend that threads are evenly distributed to allowed CPUs, choose n
// to be less than the number of CPUs in allowed ...
n := int(tid) % int(allowed.NumCPUs())
// ... then pick the nth CPU in allowed.
allowed.ForEachCPU(func(c uint) {
if n--; n == 0 {
cpu = int32(c)
}
})
return cpu
}
// Niceness returns t's niceness.
func (t *Task) Niceness() int {
t.mu.Lock()
defer t.mu.Unlock()
return t.niceness
}
// Priority returns t's priority.
func (t *Task) Priority() int {
t.mu.Lock()
defer t.mu.Unlock()
return t.niceness + 20
}
// SetNiceness sets t's niceness to n.
func (t *Task) SetNiceness(n int) {
t.mu.Lock()
defer t.mu.Unlock()
t.niceness = n
}
// NumaPolicy returns t's current numa policy.
func (t *Task) NumaPolicy() (policy linux.NumaPolicy, nodeMask uint64) {
t.mu.Lock()
defer t.mu.Unlock()
return t.numaPolicy, t.numaNodeMask
}
// SetNumaPolicy sets t's numa policy.
func (t *Task) SetNumaPolicy(policy linux.NumaPolicy, nodeMask uint64) {
t.mu.Lock()
defer t.mu.Unlock()
t.numaPolicy = policy
t.numaNodeMask = nodeMask
}
|
package delta
import (
"github.com/coreos/go-systemd/sdjournal"
"log"
)
var LogChannel = "logstream"
func (dc *DeltaCore) StartLogStreamEngine() {
j, err := sdjournal.NewJournal()
if err != nil {
log.Println(err)
return
}
err = j.SeekTail()
if err != nil {
log.Println(err)
return
}
for {
n, _ := j.Next()
if n < 1 {
j.Wait(sdjournal.IndefiniteWait)
continue
}
m, err := j.GetEntry()
if err != nil {
log.Printf("Error: " + err.Error())
} else {
key := genKeyName(LogChannel, "log_event")
if _, ok := m.Fields["_SOURCE_REALTIME_TIMESTAMP"]; ok {
event := BuildEvent(m.Fields["_SOURCE_REALTIME_TIMESTAMP"],
m.Fields["_SOURCE_REALTIME_TIMESTAMP"],
key,
m.Fields)
event.PublishEvent(LogChannel)
} else {
event := BuildEvent(m.Fields["_SOURCE_MONOTONIC_TIMESTAMP"],
m.Fields["_SOURCE_MONOTONIC_TIMESTAMP"],
key,
m.Fields)
event.PublishEvent(LogChannel)
}
}
}
}
|
// SPDX-License-Identifier: MIT
package lsp
import (
"io/ioutil"
"log"
"path/filepath"
"testing"
"github.com/issue9/assert/v3"
"github.com/caixw/apidoc/v7/core"
"github.com/caixw/apidoc/v7/core/messagetest"
"github.com/caixw/apidoc/v7/internal/ast"
"github.com/caixw/apidoc/v7/internal/lsp/protocol"
"github.com/caixw/apidoc/v7/internal/xmlenc"
)
func TestServer_textDocumentDidChange(t *testing.T) {
a := assert.New(t, false)
s := newTestServer(true, log.New(ioutil.Discard, "", 0), log.New(ioutil.Discard, "", 0))
err := s.textDocumentDidChange(true, &protocol.DidChangeTextDocumentParams{
TextDocument: protocol.VersionedTextDocumentIdentifier{
TextDocumentIdentifier: protocol.TextDocumentIdentifier{URI: "not-exists"},
},
}, nil)
a.NotError(err)
path, err := filepath.Abs("../../docs/example")
a.NotError(err)
path = filepath.FromSlash(path)
s.appendFolders(
protocol.WorkspaceFolder{
URI: core.FileURI(path),
Name: "example",
},
)
changeFile := core.FileURI(filepath.Join(path, "apis.cpp"))
text, err := changeFile.ReadAll(nil)
err = s.textDocumentDidChange(true, &protocol.DidChangeTextDocumentParams{
TextDocument: protocol.VersionedTextDocumentIdentifier{
TextDocumentIdentifier: protocol.TextDocumentIdentifier{URI: changeFile},
},
ContentChanges: []protocol.TextDocumentContentChangeEvent{
{Text: string(text)},
},
}, nil)
a.NotError(err)
}
func TestDeleteURI(t *testing.T) {
a := assert.New(t, false)
d := &ast.APIDoc{}
d.APIDoc = &ast.APIDocVersionAttribute{Value: xmlenc.String{Value: "1.0.0"}}
d.URI = core.URI("uri1")
d.APIs = []*ast.API{
{ //1
BaseTag: xmlenc.BaseTag{Base: xmlenc.Base{Location: core.Location{URI: "uri1"}}},
},
{ //2
BaseTag: xmlenc.BaseTag{Base: xmlenc.Base{Location: core.Location{URI: "uri2"}}},
},
{ //3
BaseTag: xmlenc.BaseTag{Base: xmlenc.Base{Location: core.Location{URI: "uri3"}}},
},
}
a.True(deleteURI(d, "uri3"))
a.Equal(2, len(d.APIs)).NotNil(d.APIDoc)
a.True(deleteURI(d, "uri1"))
a.Equal(1, len(d.APIs)).Nil(d.APIDoc)
a.True(deleteURI(d, "uri2"))
a.Equal(0, len(d.APIs)).Nil(d.APIDoc)
a.False(deleteURI(d, "uri2"))
}
func TestServer_textDocumentFoldingRange(t *testing.T) {
a := assert.New(t, false)
const referenceDefinitionDoc = `<apidoc version="1.1.1">
<title>标题</title>
<mimetype>xml</mimetype>
<tag name="t1" title="tag1" />
<tag name="t2" title="tag2" />
<api method="GET">
<tag>t1</tag>
<path path="/users" />
<response status="200" />
</api>
</apidoc>`
uri := core.URI("file:///root/doc.go")
blk := core.Block{Data: []byte(referenceDefinitionDoc), Location: core.Location{URI: uri}}
rslt := messagetest.NewMessageHandler()
doc := &ast.APIDoc{}
doc.Parse(rslt.Handler, blk)
rslt.Handler.Stop()
a.Empty(rslt.Errors)
s := newTestServer(true, log.New(ioutil.Discard, "", 0), log.New(ioutil.Discard, "", 0))
s.folders = append(s.folders, &folder{srv: s, doc: doc})
a.NotNil(s)
result := make([]protocol.FoldingRange, 0, 10)
err := s.textDocumentFoldingRange(false, &protocol.FoldingRangeParams{}, &result) // 未指定 URI
a.NotError(err).Empty(result)
err = s.textDocumentFoldingRange(false, &protocol.FoldingRangeParams{
TextDocument: protocol.TextDocumentIdentifier{URI: uri},
}, &result)
a.NotError(err)
a.Equal(result, []protocol.FoldingRange{
{
StartLine: 0,
EndLine: 10,
Kind: "comment",
},
{
StartLine: 5,
EndLine: 9,
Kind: "comment",
},
})
}
|
// Copyright (c) 2018 The MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package p2p
import (
"encoding/json"
"math/big"
"sync"
"time"
"github.com/MatrixAINetwork/go-matrix/ca"
"github.com/MatrixAINetwork/go-matrix/common"
"github.com/MatrixAINetwork/go-matrix/event"
"github.com/MatrixAINetwork/go-matrix/log"
"github.com/MatrixAINetwork/go-matrix/mc"
"github.com/MatrixAINetwork/go-matrix/p2p/discover"
)
type Linker struct {
role common.RoleType
active bool
broadcastActive bool
sub event.Subscription
quit chan struct{}
activeQuit chan struct{}
roleChan chan mc.BlockToLinker
mu sync.Mutex
topMu sync.RWMutex
linkMap map[common.Address]uint32
selfPeer map[common.RoleType][]*Peer
topNode map[common.RoleType]map[common.Address][]uint8
topNodeCache map[common.RoleType]map[common.Address][]uint8
}
type NodeAliveInfo struct {
Account common.Address
Position uint16
Type common.RoleType
Heartbeats []uint8
}
const MaxLinkers = 1000
var Link = &Linker{
role: common.RoleNil,
selfPeer: make(map[common.RoleType][]*Peer),
quit: make(chan struct{}),
activeQuit: make(chan struct{}),
topNode: make(map[common.RoleType]map[common.Address][]uint8),
topNodeCache: make(map[common.RoleType]map[common.Address][]uint8),
}
var (
EmptyNodeId = discover.NodeID{}
EmptyAddress = common.Address{}
)
func (l *Linker) Start() {
defer func() {
l.sub.Unsubscribe()
close(l.roleChan)
close(l.quit)
close(l.activeQuit)
}()
l.roleChan = make(chan mc.BlockToLinker)
l.sub, _ = mc.SubscribeEvent(mc.BlockToLinkers, l.roleChan)
l.initTopNodeMap()
l.initTopNodeMapCache()
for {
select {
case r := <-l.roleChan:
{
height := r.Height.Uint64()
if r.BroadCastInterval == nil {
log.Error("p2p link", "broadcast interval err", "is nil")
continue
}
if r.Role <= common.RoleBucket {
l.role = common.RoleNil
break
}
if l.role != r.Role {
l.role = r.Role
}
dropNodes := ca.GetDropNode()
l.dropNode(dropNodes)
l.maintainPeer()
if r.BroadCastInterval.IsReElectionNumber(height) {
l.topNodeCache = l.topNode
l.initTopNodeMap()
}
if r.BroadCastInterval.IsReElectionNumber(height - 10) {
l.initTopNodeMapCache()
}
if !l.active {
// recode top node active info
go l.Active()
l.active = true
}
// broadcast link and message
if l.role != common.RoleBroadcast {
break
}
switch {
case r.BroadCastInterval.IsBroadcastNumber(height):
l.ToLink()
l.broadcastActive = true
case r.BroadCastInterval.IsBroadcastNumber(height + 2):
Link.mu.Lock()
if len(l.linkMap) <= 0 {
Link.mu.Unlock()
break
}
Link.mu.Unlock()
bytes, err := l.encodeData()
if err != nil {
log.Error("encode error", "error", err)
break
}
mc.PublishEvent(mc.SendBroadCastTx, mc.BroadCastEvent{Txtyps: mc.CallTheRoll, Height: big.NewInt(r.Height.Int64() + 2), Data: bytes})
case r.BroadCastInterval.IsBroadcastNumber(height + 1):
break
default:
l.sendToAllPeersPing()
}
if !l.broadcastActive {
l.ToLink()
l.broadcastActive = true
}
}
case <-l.quit:
return
}
}
}
func (l *Linker) Stop() {
l.quit <- struct{}{}
if l.active {
l.activeQuit <- struct{}{}
}
}
func (l *Linker) initTopNodeMap() {
l.topMu.Lock()
l.topNode = make(map[common.RoleType]map[common.Address][]uint8)
for i := int(common.RoleBackupMiner); i <= int(common.RoleValidator); i = i << 1 {
l.topNode[common.RoleType(i)] = make(map[common.Address][]uint8)
}
l.topMu.Unlock()
}
func (l *Linker) initTopNodeMapCache() {
l.topMu.Lock()
l.topNodeCache = make(map[common.RoleType]map[common.Address][]uint8)
for i := int(common.RoleBackupMiner); i <= int(common.RoleValidator); i = i << 1 {
l.topNodeCache[common.RoleType(i)] = make(map[common.Address][]uint8)
}
l.topMu.Unlock()
}
// MaintainPeer
func (l *Linker) maintainPeer() {
l.link(l.role)
}
// disconnect all peers.
func (l *Linker) dropNode(drops []common.Address) {
for _, drop := range drops {
ServerP2p.RemovePeerByAddress(drop)
}
}
// dropNodeDefer disconnect all peers.
func (l *Linker) dropNodeDefer(drops []common.Address) {
select {
case <-time.After(time.Second * 5):
for _, drop := range drops {
ServerP2p.RemovePeerByAddress(drop)
}
}
}
// Link peers that should to link.
// link peers by group
func (l *Linker) link(roleType common.RoleType) {
all := ca.GetTopologyInLinker()
for key, peers := range all {
if key >= roleType {
for _, peer := range peers {
ServerP2p.AddPeerTask(peer)
}
}
}
if roleType&(common.RoleValidator|common.RoleBackupValidator) != 0 {
gap := ca.GetGapValidator()
for _, val := range gap {
ServerP2p.AddPeerTask(val)
}
}
}
func (l *Linker) Active() {
tk := time.NewTicker(time.Second * 15)
defer tk.Stop()
for {
select {
case <-tk.C:
l.recordTopNodeActiveInfo()
case <-l.activeQuit:
l.active = false
return
}
}
}
func (l *Linker) recordTopNodeActiveInfo() {
l.topMu.Lock()
defer l.topMu.Unlock()
for i := int(common.RoleBackupMiner); i <= int(common.RoleValidator); i = i << 1 {
topNodes := ca.GetRolesByGroup(common.RoleType(i))
for _, tn := range topNodes {
if tn == ServerP2p.ManAddress {
continue
}
if _, ok := l.topNode[common.RoleType(i)][tn]; !ok {
l.topNode[common.RoleType(i)][tn] = []uint8{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
}
}
}
for role := range l.topNode {
for key := range l.topNode[role] {
ok := false
for _, peer := range ServerP2p.Peers() {
id := ServerP2p.ConvertAddressToId(key)
if id != EmptyNodeId && peer.ID() == id {
ok = true
}
}
if ok {
l.topNode[role][key] = append(l.topNode[role][key], 1)
} else {
l.topNode[role][key] = append(l.topNode[role][key], 0)
}
if len(l.topNode[role][key]) > 20 {
l.topNode[role][key] = l.topNode[role][key][len(l.topNode[role][key])-20:]
}
}
}
}
// GetTopNodeAliveInfo
func GetTopNodeAliveInfo(roleType common.RoleType) (result []NodeAliveInfo) {
Link.topMu.RLock()
defer Link.topMu.RUnlock()
if len(Link.topNode) <= 0 {
for key, val := range Link.topNodeCache {
if (key & roleType) != 0 {
for signAddr, hearts := range val {
result = append(result, NodeAliveInfo{Account: signAddr, Heartbeats: hearts})
}
}
}
return
}
for key, vals := range Link.topNode {
if (key & roleType) != 0 {
for signAddr, val := range vals {
result = append(result, NodeAliveInfo{Account: signAddr, Heartbeats: val})
}
}
}
return
}
func (l *Linker) ToLink() {
Link.mu.Lock()
defer Link.mu.Unlock()
l.linkMap = make(map[common.Address]uint32)
h := ca.GetHash()
elects, _ := ca.GetElectedByHeightByHash(h)
if len(elects) <= MaxLinkers {
for _, elect := range elects {
ServerP2p.AddPeerTask(elect.SignAddress)
l.linkMap[elect.SignAddress] = 0
}
return
}
randoms := Random(len(elects), MaxLinkers)
for _, index := range randoms {
ServerP2p.AddPeerTask(elects[index].SignAddress)
l.linkMap[elects[index].SignAddress] = 0
}
}
func Record(id discover.NodeID) error {
Link.mu.Lock()
defer Link.mu.Unlock()
signAddr := ServerP2p.ConvertIdToAddress(id)
if signAddr == EmptyAddress {
return nil
}
if _, ok := Link.linkMap[signAddr]; ok {
Link.linkMap[signAddr]++
}
return nil
}
func (l *Linker) sendToAllPeersPing() {
peers := ServerP2p.Peers()
for _, peer := range peers {
Send(peer.msgReadWriter, common.BroadcastReqMsg, []uint8{0})
}
}
func (l *Linker) encodeData() ([]byte, error) {
Link.mu.Lock()
defer Link.mu.Unlock()
r := make(map[string]uint32)
for key, value := range l.linkMap {
r[key.Hex()] = value
}
return json.Marshal(r)
}
// GetRollBook
func GetRollBook() (map[common.Address]struct{}, error) {
Link.mu.Lock()
defer Link.mu.Unlock()
r := make(map[common.Address]struct{})
for key := range Link.linkMap {
r[key] = struct{}{}
}
return r, nil
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type response struct {
Message string `json:"message,omitempty"`
}
func main() {
port := 3000
host := "0.0.0.0"
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "application/json")
bytes, errBody := ioutil.ReadAll(request.Body)
defer request.Body.Close()
if errBody != nil {
http.Error(writer, errBody.Error(), http.StatusInternalServerError)
return
}
resp := response{
Message: string(bytes),
}
json.NewEncoder(writer).Encode(resp)
})
http.HandleFunc("/alive", func(writer http.ResponseWriter, request *http.Request) {
log.Print("I'm alive - yeah !")
writer.Write([]byte("ok"))
})
http.HandleFunc("/ready", func(writer http.ResponseWriter, request *http.Request) {
log.Print("I'm ready - yeah !")
writer.Write([]byte("ok"))
})
log.Printf("I'm listening on %s:%d\n", host, port)
http.ListenAndServe(fmt.Sprintf("%s:%d", host, port), nil)
}
|
package mysql
import "reflect"
const (
TagDB = "db" // 数据库内字段名称
TagMajor = "major" // 主键
)
type Tag struct {
DB string
Major string
}
func NewTag(tag reflect.StructTag) *Tag {
return &Tag{
DB: tag.Get(TagDB),
Major: tag.Get(TagMajor),
}
}
|
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
strfmt "github.com/go-openapi/strfmt"
)
// NewCreateGetReportInputParametersForSpecifiedInputControlsViaPostParams creates a new CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams object
// with the default values initialized.
func NewCreateGetReportInputParametersForSpecifiedInputControlsViaPostParams() *CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams {
var ()
return &CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams{
timeout: cr.DefaultTimeout,
}
}
// NewCreateGetReportInputParametersForSpecifiedInputControlsViaPostParamsWithTimeout creates a new CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewCreateGetReportInputParametersForSpecifiedInputControlsViaPostParamsWithTimeout(timeout time.Duration) *CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams {
var ()
return &CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams{
timeout: timeout,
}
}
/*CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams contains all the parameters to send to the API endpoint
for the create get report input parameters for specified input controls via post operation typically these are written to a http.Request
*/
type CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams struct {
/*InputControlIds*/
InputControlIds *string
/*ReportUnitURI*/
ReportUnitURI *string
timeout time.Duration
}
// WithInputControlIds adds the inputControlIds to the create get report input parameters for specified input controls via post params
func (o *CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams) WithInputControlIds(InputControlIds *string) *CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams {
o.InputControlIds = InputControlIds
return o
}
// WithReportUnitURI adds the reportUnitUri to the create get report input parameters for specified input controls via post params
func (o *CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams) WithReportUnitURI(ReportUnitURI *string) *CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams {
o.ReportUnitURI = ReportUnitURI
return o
}
// WriteToRequest writes these params to a swagger request
func (o *CreateGetReportInputParametersForSpecifiedInputControlsViaPostParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
r.SetTimeout(o.timeout)
var res []error
if o.InputControlIds != nil {
// query param inputControlIds
var qrInputControlIds string
if o.InputControlIds != nil {
qrInputControlIds = *o.InputControlIds
}
qInputControlIds := qrInputControlIds
if qInputControlIds != "" {
if err := r.SetQueryParam("inputControlIds", qInputControlIds); err != nil {
return err
}
}
}
if o.ReportUnitURI != nil {
// query param reportUnitURI
var qrReportUnitURI string
if o.ReportUnitURI != nil {
qrReportUnitURI = *o.ReportUnitURI
}
qReportUnitURI := qrReportUnitURI
if qReportUnitURI != "" {
if err := r.SetQueryParam("reportUnitURI", qReportUnitURI); err != nil {
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
|
package main
import (
"fmt"
"math"
)
// todo
// 别人的答案
// 奇数长度和偶数长度
// 左右指针从中间向两端,回文类问题;别的左右指针从两端向中间
func longestPalindrome(s string) string {
l := math.MinInt
res := ""
for i := 0; i < len(s); i++ {
v := longestPalindromeInNK(s, i, i)
v1 := longestPalindromeInNK(s, i, i+1)
if len(v) > l {
res = v
// todo: 注意别忘了更新l的值
l = len(v)
}
if len(v1) > l {
res = v1
// todo: 注意别忘了更新l的值
l = len(v1)
}
}
return res
}
// todo: 优化,实际上这个函数不需要
// func longestPalindromeInN(s string, n int) string {
// res := ""
// left := n
// right := n
// for left >= 0 && right < len(s) && s[left] == s[right] {
// res = s[left:right+1]
// left--
// right++
// }
// return res
// }
func longestPalindromeInNK(s string, n, k int) string {
res := ""
left := n
right := k
for left >= 0 && right < len(s) && s[left] == s[right] {
res = s[left : right+1]
left--
right++
}
return res
}
func main() {
fmt.Println(longestPalindromeInNK("babad", 1, 1))
}
// 我的答案超时
func longestPalindrome2(s string) string {
if isPalindrome2(s) {
return s
}
left := longestPalindrome2(s[1:])
right := longestPalindrome2(s[:len(s)-1])
if len(left) > len(right) {
return left
}
return right
}
func isPalindrome2(s string) bool {
left := 0
right := len(s) - 1
for left <= right {
if s[left] != s[right] {
return false
}
left++
right--
}
return true
}
|
package main
import (
"errors"
"fmt"
"time"
)
// User struct your colleague is implementing this
type User struct {
ID string
Name string
Email string
}
func (u User) GetUserDetails(id string) (User, error) {
if id != ""{
return User{
ID: id,
Name: "Miikka",
}, nil
}
return User{}, errors.New("no user id given")
}
func (u User) EditUserDetails(user User) error {
if u.ID == ""{
return errors.New("no user id given")
}
return nil
}
func (u User) DeleteUserDetails(id string) error {
if u.ID != ""{
return nil
}
return errors.New("no user id given")
}
// DBFuncUser is what you are writing as an interface
type DBFuncUser interface{
GetUserDetails(id string) (User, error)
EditUserDetails(user User) error
DeleteUserDetails(id string) error
}
type AppContext struct {
dbImpl DBFuncUser
}
func main(){
u := User{}
db := AppContext{
dbImpl: u,
}
id := "19230213"
user, err := db.dbImpl.GetUserDetails(id)
if err != nil {
fmt.Println( fmt.Errorf("%s", err) )
}
fmt.Println(user)
str := "This is a string"
myString(str)
myStringPtr(&str)
fmt.Printf("%s \n", str)
fmt.Printf("%p \n", &str)
//InterfaceExample()
fmt.Println("New example ------ ")
a := new(int)
var abc int
b := make([]int, 0)
*a = 90
fmt.Println("---a---")
fmt.Println(a)
fmt.Println(*a)
fmt.Println("---b---")
fmt.Println(b)
fmt.Println("---abc---")
fmt.Println(abc)
fmt.Println(&abc)
getValue(*a)
}
func getValue(in int) {
fmt.Println("---getValue---")
str := "some value"
fmt.Println("---str---")
fmt.Println(str)
fmt.Println(&str)
fmt.Println("---in---")
fmt.Println(in)
fmt.Println(&in)
}
func myString(str string) {
fmt.Println(str)
fmt.Printf("myString `str` pointer %p \n", &str)
str = "Changed string"
}
func myStringPtr(str *string) {
fmt.Println(str)
fmt.Printf("myStringPtr `str` pointer %p \n", str)
*str = "Changed string"
}
type myStruct struct {
myIntf myInterface
}
// Interface example
type ServerInterface struct {}
func (s ServerInterface) Start() {
fmt.Println("Server started")
s.Run()
}
func (s ServerInterface) Stop() {
fmt.Println("Server stopped")
}
func (s ServerInterface) Run() {
fmt.Println("Server running")
}
type myInterface interface {
Start()
Stop()
}
func InterfaceExample() {
server := new(ServerInterface)
mystrct := myStruct{
myIntf: server,
}
mystrct.myIntf.Start()
time.Sleep(time.Second * 5)
mystrct.myIntf.Stop()
} |
// Copyright 2020 The gVisor 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 linux
import (
"fmt"
"time"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/errors/linuxerr"
"gvisor.dev/gvisor/pkg/hostarch"
"gvisor.dev/gvisor/pkg/sentry/arch"
"gvisor.dev/gvisor/pkg/sentry/kernel"
ktime "gvisor.dev/gvisor/pkg/sentry/kernel/time"
"gvisor.dev/gvisor/pkg/sentry/limits"
"gvisor.dev/gvisor/pkg/sentry/vfs"
"gvisor.dev/gvisor/pkg/waiter"
)
// fileCap is the maximum allowable files for poll & select. This has no
// equivalent in Linux; it exists in gVisor since allocation failure in Go is
// unrecoverable.
const fileCap = 1024 * 1024
// Masks for "readable", "writable", and "exceptional" events as defined by
// select(2).
const (
// selectReadEvents is analogous to the Linux kernel's
// fs/select.c:POLLIN_SET.
selectReadEvents = linux.POLLIN | linux.POLLHUP | linux.POLLERR
// selectWriteEvents is analogous to the Linux kernel's
// fs/select.c:POLLOUT_SET.
selectWriteEvents = linux.POLLOUT | linux.POLLERR
// selectExceptEvents is analogous to the Linux kernel's
// fs/select.c:POLLEX_SET.
selectExceptEvents = linux.POLLPRI
)
// pollState tracks the associated file description and waiter of a PollFD.
type pollState struct {
file *vfs.FileDescription
waiter waiter.Entry
}
// initReadiness gets the current ready mask for the file represented by the FD
// stored in pfd.FD. If a channel is passed in, the waiter entry in "state" is
// used to register with the file for event notifications, and a reference to
// the file is stored in "state".
func initReadiness(t *kernel.Task, pfd *linux.PollFD, state *pollState, ch chan struct{}) error {
if pfd.FD < 0 {
pfd.REvents = 0
return nil
}
file := t.GetFile(pfd.FD)
if file == nil {
pfd.REvents = linux.POLLNVAL
return nil
}
if ch == nil {
defer file.DecRef(t)
} else {
state.file = file
state.waiter.Init(waiter.ChannelNotifier(ch), waiter.EventMaskFromLinux(uint32(pfd.Events)))
if err := file.EventRegister(&state.waiter); err != nil {
return err
}
}
r := file.Readiness(waiter.EventMaskFromLinux(uint32(pfd.Events)))
pfd.REvents = int16(r.ToLinux()) & pfd.Events
return nil
}
// releaseState releases all the pollState in "state".
func releaseState(t *kernel.Task, state []pollState) {
for i := range state {
if state[i].file != nil {
state[i].file.EventUnregister(&state[i].waiter)
state[i].file.DecRef(t)
}
}
}
// pollBlock polls the PollFDs in "pfd" with a bounded time specified in "timeout"
// when "timeout" is greater than zero.
//
// pollBlock returns the remaining timeout, which is always 0 on a timeout; and 0 or
// positive if interrupted by a signal.
func pollBlock(t *kernel.Task, pfd []linux.PollFD, timeout time.Duration) (time.Duration, uintptr, error) {
var ch chan struct{}
if timeout != 0 {
ch = make(chan struct{}, 1)
}
// Register for event notification in the files involved if we may
// block (timeout not zero). Once we find a file that has a non-zero
// result, we stop registering for events but still go through all files
// to get their ready masks.
state := make([]pollState, len(pfd))
defer releaseState(t, state)
n := uintptr(0)
for i := range pfd {
if err := initReadiness(t, &pfd[i], &state[i], ch); err != nil {
return timeout, 0, err
}
if pfd[i].REvents != 0 {
n++
ch = nil
}
}
if timeout == 0 {
return timeout, n, nil
}
haveTimeout := timeout >= 0
for n == 0 {
var err error
// Wait for a notification.
timeout, err = t.BlockWithTimeout(ch, haveTimeout, timeout)
if err != nil {
if linuxerr.Equals(linuxerr.ETIMEDOUT, err) {
err = nil
}
return timeout, 0, err
}
// We got notified, count how many files are ready. If none,
// then this was a spurious notification, and we just go back
// to sleep with the remaining timeout.
for i := range state {
if state[i].file == nil {
continue
}
r := state[i].file.Readiness(waiter.EventMaskFromLinux(uint32(pfd[i].Events)))
rl := int16(r.ToLinux()) & pfd[i].Events
if rl != 0 {
pfd[i].REvents = rl
n++
}
}
}
return timeout, n, nil
}
// CopyInPollFDs copies an array of struct pollfd unless nfds exceeds the max.
func CopyInPollFDs(t *kernel.Task, addr hostarch.Addr, nfds uint) ([]linux.PollFD, error) {
if uint64(nfds) > t.ThreadGroup().Limits().GetCapped(limits.NumberOfFiles, fileCap) {
return nil, linuxerr.EINVAL
}
pfd := make([]linux.PollFD, nfds)
if nfds > 0 {
if _, err := linux.CopyPollFDSliceIn(t, addr, pfd); err != nil {
return nil, err
}
}
return pfd, nil
}
func doPoll(t *kernel.Task, addr hostarch.Addr, nfds uint, timeout time.Duration) (time.Duration, uintptr, error) {
pfd, err := CopyInPollFDs(t, addr, nfds)
if err != nil {
return timeout, 0, err
}
// Compatibility warning: Linux adds POLLHUP and POLLERR just before
// polling, in fs/select.c:do_pollfd(). Since pfd is copied out after
// polling, changing event masks here is an application-visible difference.
// (Linux also doesn't copy out event masks at all, only revents.)
for i := range pfd {
pfd[i].Events |= linux.POLLHUP | linux.POLLERR
}
remainingTimeout, n, err := pollBlock(t, pfd, timeout)
err = linuxerr.ConvertIntr(err, linuxerr.EINTR)
// The poll entries are copied out regardless of whether
// any are set or not. This aligns with the Linux behavior.
if nfds > 0 && err == nil {
if _, err := linux.CopyPollFDSliceOut(t, addr, pfd); err != nil {
return remainingTimeout, 0, err
}
}
return remainingTimeout, n, err
}
// CopyInFDSet copies an fd set from select(2)/pselect(2).
func CopyInFDSet(t *kernel.Task, addr hostarch.Addr, nBytes, nBitsInLastPartialByte int) ([]byte, error) {
set := make([]byte, nBytes)
if addr != 0 {
if _, err := t.CopyInBytes(addr, set); err != nil {
return nil, err
}
// If we only use part of the last byte, mask out the extraneous bits.
//
// N.B. This only works on little-endian architectures.
if nBitsInLastPartialByte != 0 {
set[nBytes-1] &^= byte(0xff) << nBitsInLastPartialByte
}
}
return set, nil
}
func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs hostarch.Addr, timeout time.Duration) (uintptr, error) {
if nfds < 0 || nfds > fileCap {
return 0, linuxerr.EINVAL
}
// Calculate the size of the fd sets (one bit per fd).
nBytes := (nfds + 7) / 8
nBitsInLastPartialByte := nfds % 8
// Capture all the provided input vectors.
r, err := CopyInFDSet(t, readFDs, nBytes, nBitsInLastPartialByte)
if err != nil {
return 0, err
}
w, err := CopyInFDSet(t, writeFDs, nBytes, nBitsInLastPartialByte)
if err != nil {
return 0, err
}
e, err := CopyInFDSet(t, exceptFDs, nBytes, nBitsInLastPartialByte)
if err != nil {
return 0, err
}
// Count how many FDs are actually being requested so that we can build
// a PollFD array.
fdCount := 0
for i := 0; i < nBytes; i++ {
v := r[i] | w[i] | e[i]
for v != 0 {
v &= (v - 1)
fdCount++
}
}
// Build the PollFD array.
pfd := make([]linux.PollFD, 0, fdCount)
var fd int32
for i := 0; i < nBytes; i++ {
rV, wV, eV := r[i], w[i], e[i]
v := rV | wV | eV
m := byte(1)
for j := 0; j < 8; j++ {
if (v & m) != 0 {
// Make sure the fd is valid and decrement the reference
// immediately to ensure we don't leak. Note, another thread
// might be about to close fd. This is racy, but that's
// OK. Linux is racy in the same way.
file := t.GetFile(fd)
if file == nil {
return 0, linuxerr.EBADF
}
file.DecRef(t)
var mask int16
if (rV & m) != 0 {
mask |= selectReadEvents
}
if (wV & m) != 0 {
mask |= selectWriteEvents
}
if (eV & m) != 0 {
mask |= selectExceptEvents
}
pfd = append(pfd, linux.PollFD{
FD: fd,
Events: mask,
})
}
fd++
m <<= 1
}
}
// Do the syscall, then count the number of bits set.
if _, _, err = pollBlock(t, pfd, timeout); err != nil {
return 0, linuxerr.ConvertIntr(err, linuxerr.EINTR)
}
// r, w, and e are currently event mask bitsets; unset bits corresponding
// to events that *didn't* occur.
bitSetCount := uintptr(0)
for idx := range pfd {
events := pfd[idx].REvents
i, j := pfd[idx].FD/8, uint(pfd[idx].FD%8)
m := byte(1) << j
if r[i]&m != 0 {
if (events & selectReadEvents) != 0 {
bitSetCount++
} else {
r[i] &^= m
}
}
if w[i]&m != 0 {
if (events & selectWriteEvents) != 0 {
bitSetCount++
} else {
w[i] &^= m
}
}
if e[i]&m != 0 {
if (events & selectExceptEvents) != 0 {
bitSetCount++
} else {
e[i] &^= m
}
}
}
// Copy updated vectors back.
if readFDs != 0 {
if _, err := t.CopyOutBytes(readFDs, r); err != nil {
return 0, err
}
}
if writeFDs != 0 {
if _, err := t.CopyOutBytes(writeFDs, w); err != nil {
return 0, err
}
}
if exceptFDs != 0 {
if _, err := t.CopyOutBytes(exceptFDs, e); err != nil {
return 0, err
}
}
return bitSetCount, nil
}
// timeoutRemaining returns the amount of time remaining for the specified
// timeout or 0 if it has elapsed.
//
// startNs must be from CLOCK_MONOTONIC.
func timeoutRemaining(t *kernel.Task, startNs ktime.Time, timeout time.Duration) time.Duration {
now := t.Kernel().MonotonicClock().Now()
remaining := timeout - now.Sub(startNs)
if remaining < 0 {
remaining = 0
}
return remaining
}
// copyOutTimespecRemaining copies the time remaining in timeout to timespecAddr.
//
// startNs must be from CLOCK_MONOTONIC.
func copyOutTimespecRemaining(t *kernel.Task, startNs ktime.Time, timeout time.Duration, timespecAddr hostarch.Addr) error {
if timeout <= 0 {
return nil
}
remaining := timeoutRemaining(t, startNs, timeout)
tsRemaining := linux.NsecToTimespec(remaining.Nanoseconds())
_, err := tsRemaining.CopyOut(t, timespecAddr)
return err
}
// copyOutTimevalRemaining copies the time remaining in timeout to timevalAddr.
//
// startNs must be from CLOCK_MONOTONIC.
func copyOutTimevalRemaining(t *kernel.Task, startNs ktime.Time, timeout time.Duration, timevalAddr hostarch.Addr) error {
if timeout <= 0 {
return nil
}
remaining := timeoutRemaining(t, startNs, timeout)
tvRemaining := linux.NsecToTimeval(remaining.Nanoseconds())
_, err := tvRemaining.CopyOut(t, timevalAddr)
return err
}
// pollRestartBlock encapsulates the state required to restart poll(2) via
// restart_syscall(2).
//
// +stateify savable
type pollRestartBlock struct {
pfdAddr hostarch.Addr
nfds uint
timeout time.Duration
}
// Restart implements kernel.SyscallRestartBlock.Restart.
func (p *pollRestartBlock) Restart(t *kernel.Task) (uintptr, error) {
return poll(t, p.pfdAddr, p.nfds, p.timeout)
}
func poll(t *kernel.Task, pfdAddr hostarch.Addr, nfds uint, timeout time.Duration) (uintptr, error) {
remainingTimeout, n, err := doPoll(t, pfdAddr, nfds, timeout)
// On an interrupt poll(2) is restarted with the remaining timeout.
if linuxerr.Equals(linuxerr.EINTR, err) {
t.SetSyscallRestartBlock(&pollRestartBlock{
pfdAddr: pfdAddr,
nfds: nfds,
timeout: remainingTimeout,
})
return 0, linuxerr.ERESTART_RESTARTBLOCK
}
return n, err
}
// Poll implements linux syscall poll(2).
func Poll(t *kernel.Task, sysno uintptr, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
pfdAddr := args[0].Pointer()
nfds := uint(args[1].Uint()) // poll(2) uses unsigned long.
timeout := time.Duration(args[2].Int()) * time.Millisecond
n, err := poll(t, pfdAddr, nfds, timeout)
return n, nil, err
}
// Ppoll implements linux syscall ppoll(2).
func Ppoll(t *kernel.Task, sysno uintptr, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
pfdAddr := args[0].Pointer()
nfds := uint(args[1].Uint()) // poll(2) uses unsigned long.
timespecAddr := args[2].Pointer()
maskAddr := args[3].Pointer()
maskSize := uint(args[4].Uint())
timeout, err := copyTimespecInToDuration(t, timespecAddr)
if err != nil {
return 0, nil, err
}
var startNs ktime.Time
if timeout > 0 {
startNs = t.Kernel().MonotonicClock().Now()
}
if err := setTempSignalSet(t, maskAddr, maskSize); err != nil {
return 0, nil, err
}
_, n, err := doPoll(t, pfdAddr, nfds, timeout)
copyErr := copyOutTimespecRemaining(t, startNs, timeout, timespecAddr)
// doPoll returns EINTR if interrupted, but ppoll is normally restartable
// if interrupted by something other than a signal handled by the
// application (i.e. returns ERESTARTNOHAND). However, if
// copyOutTimespecRemaining failed, then the restarted ppoll would use the
// wrong timeout, so the error should be left as EINTR.
//
// Note that this means that if err is nil but copyErr is not, copyErr is
// ignored. This is consistent with Linux.
if linuxerr.Equals(linuxerr.EINTR, err) && copyErr == nil {
err = linuxerr.ERESTARTNOHAND
}
return n, nil, err
}
// Select implements linux syscall select(2).
func Select(t *kernel.Task, sysno uintptr, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
nfds := int(args[0].Int()) // select(2) uses an int.
readFDs := args[1].Pointer()
writeFDs := args[2].Pointer()
exceptFDs := args[3].Pointer()
timevalAddr := args[4].Pointer()
// Use a negative Duration to indicate "no timeout".
timeout := time.Duration(-1)
if timevalAddr != 0 {
var timeval linux.Timeval
if _, err := timeval.CopyIn(t, timevalAddr); err != nil {
return 0, nil, err
}
if timeval.Sec < 0 || timeval.Usec < 0 {
return 0, nil, linuxerr.EINVAL
}
timeout = time.Duration(timeval.ToNsecCapped())
}
startNs := t.Kernel().MonotonicClock().Now()
n, err := doSelect(t, nfds, readFDs, writeFDs, exceptFDs, timeout)
copyErr := copyOutTimevalRemaining(t, startNs, timeout, timevalAddr)
// See comment in Ppoll.
if linuxerr.Equals(linuxerr.EINTR, err) && copyErr == nil {
err = linuxerr.ERESTARTNOHAND
}
return n, nil, err
}
// +marshal
type sigSetWithSize struct {
sigsetAddr uint64
sizeofSigset uint64
}
// Pselect6 implements linux syscall pselect6(2).
func Pselect6(t *kernel.Task, sysno uintptr, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
nfds := int(args[0].Int()) // select(2) uses an int.
readFDs := args[1].Pointer()
writeFDs := args[2].Pointer()
exceptFDs := args[3].Pointer()
timespecAddr := args[4].Pointer()
maskWithSizeAddr := args[5].Pointer()
timeout, err := copyTimespecInToDuration(t, timespecAddr)
if err != nil {
return 0, nil, err
}
var startNs ktime.Time
if timeout > 0 {
startNs = t.Kernel().MonotonicClock().Now()
}
if maskWithSizeAddr != 0 {
if t.Arch().Width() != 8 {
panic(fmt.Sprintf("unsupported sizeof(void*): %d", t.Arch().Width()))
}
var maskStruct sigSetWithSize
if _, err := maskStruct.CopyIn(t, maskWithSizeAddr); err != nil {
return 0, nil, err
}
if err := setTempSignalSet(t, hostarch.Addr(maskStruct.sigsetAddr), uint(maskStruct.sizeofSigset)); err != nil {
return 0, nil, err
}
}
n, err := doSelect(t, nfds, readFDs, writeFDs, exceptFDs, timeout)
copyErr := copyOutTimespecRemaining(t, startNs, timeout, timespecAddr)
// See comment in Ppoll.
if linuxerr.Equals(linuxerr.EINTR, err) && copyErr == nil {
err = linuxerr.ERESTARTNOHAND
}
return n, nil, err
}
func setTempSignalSet(t *kernel.Task, maskAddr hostarch.Addr, maskSize uint) error {
if maskAddr == 0 {
return nil
}
if maskSize != linux.SignalSetSize {
return linuxerr.EINVAL
}
var mask linux.SignalSet
if _, err := mask.CopyIn(t, maskAddr); err != nil {
return err
}
mask &^= kernel.UnblockableSignals
oldmask := t.SignalMask()
t.SetSignalMask(mask)
t.SetSavedSignalMask(oldmask)
return nil
}
|
package iqiyiv2
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"videocrawler/clients"
"videocrawler/common/util"
"videocrawler/crawler"
"videocrawler/crawler/iqiyi"
"github.com/buger/jsonparser"
"github.com/fatih/color"
)
type Iqiyi2 struct {
*iqiyi.IqiyiT
}
func (this *Iqiyi2) GetVideoInfo(url string) (crawler.VideoDetail, error) {
this.GetVideoId(url)
d := color.New(color.FgBlue, color.Bold)
d.Printf("视频标题: %s \n", this.Title)
c := color.New(color.FgCyan).Add(color.Underline)
c.Println("=========================================================")
if this.VideoId == "" || this.Tvid == "" {
return crawler.VideoDetail{}, errors.New("not found vid")
}
err := this.parseVideo()
if err != nil {
return crawler.VideoDetail{}, err
}
vDetail := crawler.VideoDetail{
Title: this.Title,
Streams: this.Streams,
}
return vDetail, nil
}
func (this *Iqiyi2) parseVideo() error {
body := this.getRawData()
content := string(body)
content = strings.TrimLeft(content, "var tvInfoJs=")
body = []byte(content)
code, _ := jsonparser.GetString(body, "code")
if code != "A00000" {
return errors.New("json data format error")
}
data, _, _, _ := jsonparser.Get(body, "data")
jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
_, e := jsonparser.GetString(value, "m3utx")
if e != nil {
return
}
vd, _ := jsonparser.GetString(value, "vd")
vdInt, err := strconv.ParseInt(vd, 10, 64)
m3u8, _ := jsonparser.GetString(value, "m3utx")
streamId := iqiyi.Vd2Id[vdInt]
videoProfile := iqiyi.Id2Profile[streamId]
fmt.Println(streamId)
fmt.Println("m3u8: " + m3u8)
c := color.New(color.FgCyan).Add(color.Underline)
c.Println("=========================================================")
this.Streams[streamId] = crawler.StreamInfo{
VideoProfile: videoProfile,
Container: "m3u8",
Src: m3u8,
Width: 0,
Height: 0,
Flv: make([]crawler.FlvInfo, 0),
}
}, "vidl")
return nil
}
func (this *Iqiyi2) getRawData() []byte {
currentTime := time.Now().UnixNano() / int64(time.Millisecond)
timeStr := fmt.Sprintf("%d", currentTime)
key := "d5fb4bd9d50c4be6948c97edd7254b0e"
sc := util.Md5(timeStr + key + this.Tvid)
reqUrl := fmt.Sprintf("http://cache.m.iqiyi.com/jp/tmts/%s/%s/", this.Tvid, this.VideoId)
var params = map[string]string{
"tvid": this.Tvid,
"vid": this.VideoId,
"src": "76f90cbd92f94a2e925d83e8ccd22cb7",
"sc": sc,
"t": timeStr,
}
reqUrl = reqUrl + "?" + util.HttpBuildQuery(params)
body, _ := this.Client.GetUrlContent(reqUrl)
return body
}
func (this *Iqiyi2) GetVideoId(url string) (string, string) {
body, err := this.Client.GetUrlContent(url)
if err != nil {
return "", ""
}
r, _ := regexp.Compile("data-player-videoid=\"(.+?)\"")
matches := r.FindStringSubmatch(string(body))
if matches != nil {
this.VideoId = matches[1]
}
r, _ = regexp.Compile("data-player-tvid=\"(.+?)\"")
matches = r.FindStringSubmatch(string(body))
if matches != nil {
this.Tvid = matches[1]
}
r, _ = regexp.Compile("<title>([^<]+)")
matches = r.FindStringSubmatch(string(body))
this.Title = matches[1]
return this.VideoId, this.Tvid
}
func NewIqiyi2() *Iqiyi2 {
fmt.Println("init iqiyi###############################################")
iqy := &Iqiyi2{
&iqiyi.IqiyiT{
&crawler.CrawlerNet{},
clients.NewClient("http://iqiyi.com", map[string]string{}),
make(crawler.StreamSet), "", "", "",
},
}
return iqy
}
|
package util
import (
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/util"
"github.com/devspace-cloud/devspace/pkg/util/kubeconfig"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
func NewClientByContext(context, namespace string, switchContext bool, kubeLoader kubeconfig.Loader) (clientcmd.ClientConfig, string, string, error) {
// Load new raw config
kubeConfigOriginal, err := kubeLoader.LoadRawConfig()
if err != nil {
return nil, "", "", err
}
// We clone the config here to avoid changing the single loaded config
kubeConfig := clientcmdapi.Config{}
err = util.Convert(&kubeConfigOriginal, &kubeConfig)
if err != nil {
return nil, "", "", err
}
if len(kubeConfig.Clusters) == 0 {
return nil, "", "", errors.Errorf("kube config is invalid: please make sure you have an existing valid kube config")
}
// If we should use a certain kube context use that
var (
activeContext = kubeConfig.CurrentContext
activeNamespace = metav1.NamespaceDefault
saveConfig = false
)
// Set active context
if context != "" && activeContext != context {
activeContext = context
if switchContext {
kubeConfig.CurrentContext = activeContext
saveConfig = true
}
}
// Set active namespace
if kubeConfig.Contexts[activeContext] != nil {
if kubeConfig.Contexts[activeContext].Namespace != "" {
activeNamespace = kubeConfig.Contexts[activeContext].Namespace
}
if namespace != "" && activeNamespace != namespace {
activeNamespace = namespace
kubeConfig.Contexts[activeContext].Namespace = activeNamespace
if switchContext {
saveConfig = true
}
}
}
// Should we save the kube config?
if saveConfig {
err = kubeLoader.SaveConfig(&kubeConfig)
if err != nil {
return nil, "", "", errors.Errorf("Error saving kube config: %v", err)
}
}
clientConfig := clientcmd.NewNonInteractiveClientConfig(kubeConfig, activeContext, &clientcmd.ConfigOverrides{}, clientcmd.NewDefaultClientConfigLoadingRules())
if kubeConfig.Contexts[activeContext] == nil {
return nil, "", "", errors.Errorf("Error loading kube config, context '%s' doesn't exist", activeContext)
}
return clientConfig, activeContext, activeNamespace, nil
}
|
package main
import (
"fmt"
"io/ioutil"
"os"
"path"
"sync"
// bytesize "github.com/inhies/go-bytesize"
)
func du(filepath string, fileSize chan<- int64, n *sync.WaitGroup) {
defer n.Done()
for _, file := range readDir(filepath) {
if file.IsDir() {
n.Add(1)
go du(path.Join(filepath, file.Name()), fileSize, n)
} else {
fileSize <- file.Size()
}
}
}
var sema = make(chan struct{}, 20)
func readDir(filepath string) []os.FileInfo {
sema <- struct{}{}
files, err := ioutil.ReadDir(filepath)
if err != nil {
fmt.Println(err)
return nil
}
<-sema
return files
}
func du2(filepath string) int64 {
files, err := ioutil.ReadDir(filepath)
if err != nil {
fmt.Println(err)
return 0
}
var size int64
for _, file := range files {
if file.IsDir() {
size += du2(path.Join(filepath, file.Name()))
} else {
size += file.Size()
}
}
// fmt.Printf("%s, %s \n", filepath, bytesize.New(float64(size)))
return size
}
|
package main
import (
"time"
"net/http"
"encoding/json"
)
type Routes struct {
staticDir string
apiKey string
apiSecret string
}
// Route: Data
type Data struct {
Query string `json:"query"`
Datetime string `json:"datetime"`
}
// /api/data
func (r Routes) apiDataRoute(resp http.ResponseWriter, req *http.Request) {
var data Data
// TODO(zooraze): actually grab data contents
data.Query = "This is not the data you're looking for..."
// TODO(zooraze): the time should not update every five seconds
datetime := time.Now().Format("Mon Aug 5 10:17:08 EST 2019")
data.Datetime = datetime
// Reformat data as JSON
result, err := json.Marshal(data)
if err != nil {
http.Error(resp, err.Error(), http.StatusInternalServerError)
return
}
resp.Header().Set("Content-Type", "application/json")
resp.Write(result)
}
|
package main
import "encoding/json"
type Result map[string]map[string][]string
func (r Result) Add(f *Footprint) {
if _, ok := r[f.Hash]; ok == false {
r[f.Hash] = make(map[string][]string)
r[f.Hash][f.Title] = []string{}
}
r[f.Hash][f.Title] = append(r[f.Hash][f.Title], f.Url)
}
func process(c <-chan *Footprint) ([]byte, error) {
r := Result{}
for f := range c {
r.Add(f)
}
return json.Marshal(r)
}
|
package main
// Leetcode 739. (medium)
func dailyTemperatures(T []int) []int {
res := make([]int, len(T))
stack := make([]int, 1)
stack[0] = 0
for i := 1; i < len(T); i++ {
for len(stack) > 0 && T[stack[len(stack)-1]] < T[i] {
res[stack[len(stack)-1]] = i - stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
stack = append(stack, i)
}
return res
}
|
package main
import "testing"
func TestXxx(t *testing.T) {
a := NewAuthor()
id, name := NewAuthorIDs()
if a.ID != id {
t.Error("Expected author ID to be `whoami` but was nil")
}
if a.Name != name {
t.Error("Expected author name to be 'Your Name' but was ", a.Name)
}
if a.URL != "https://author.example.com" {
t.Error(
"Expected author URL to be 'https://author.example.com' but was ",
a.URL,
)
}
}
|
package basic
import "testing"
func TestEmployment(t *testing.T) {
employment := AccountabilityType(1)
company := Organization{}
smith := Person{}
period := TimePeriod{}
// companyはsmithに対して雇用(employment)の責任関係を持つ
t.Log(Accountability{employment, period, &Party(company), &Party(smith)})
}
func TestManager(t *testing.T) {
manager := AccountabilityType(2)
serviceTeam := Organization{}
smith := Person{}
period := TimePeriod{}
// smithはservice teamのmanager
// service teamはsmithに対してmanagerの責任関係を持つ
t.Log(Accountability{manager, period, &Party(serviceTeam), &Party(smith)})
}
func TestContract(t *testing.T) {
contract := AccountabilityType(3)
service := Organization{}
smith := Person{}
period := TimePeriod{}
// smithはserviceの契約をした
// serviceはsmithに対してcontractの責任関係を持つ
t.Log(Accountability{contract, period, &Party(service), &Party(smith)})
}
func TestRegion(t *testing.T) {
contract := AccountabilityType(3)
service := Organization{}
smith := Person{}
period := TimePeriod{}
// smithはserviceの契約をした
// serviceはsmithに対してcontractの責任関係を持つ
t.Log(Accountability{contract, period, &Party(service), &Party(smith)})
}
|
package odoo
import (
"fmt"
)
// HrDepartment represents hr.department model.
type HrDepartment struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
AbsenceOfToday *Int `xmlrpc:"absence_of_today,omptempty"`
Active *Bool `xmlrpc:"active,omptempty"`
AllocationToApproveCount *Int `xmlrpc:"allocation_to_approve_count,omptempty"`
ChildIds *Relation `xmlrpc:"child_ids,omptempty"`
Color *Int `xmlrpc:"color,omptempty"`
CompanyId *Many2One `xmlrpc:"company_id,omptempty"`
CompleteName *String `xmlrpc:"complete_name,omptempty"`
CreateDate *Time `xmlrpc:"create_date,omptempty"`
CreateUid *Many2One `xmlrpc:"create_uid,omptempty"`
DisplayName *String `xmlrpc:"display_name,omptempty"`
Id *Int `xmlrpc:"id,omptempty"`
JobsIds *Relation `xmlrpc:"jobs_ids,omptempty"`
LeaveToApproveCount *Int `xmlrpc:"leave_to_approve_count,omptempty"`
ManagerId *Many2One `xmlrpc:"manager_id,omptempty"`
MemberIds *Relation `xmlrpc:"member_ids,omptempty"`
MessageChannelIds *Relation `xmlrpc:"message_channel_ids,omptempty"`
MessageFollowerIds *Relation `xmlrpc:"message_follower_ids,omptempty"`
MessageIds *Relation `xmlrpc:"message_ids,omptempty"`
MessageIsFollower *Bool `xmlrpc:"message_is_follower,omptempty"`
MessageLastPost *Time `xmlrpc:"message_last_post,omptempty"`
MessageNeedaction *Bool `xmlrpc:"message_needaction,omptempty"`
MessageNeedactionCounter *Int `xmlrpc:"message_needaction_counter,omptempty"`
MessagePartnerIds *Relation `xmlrpc:"message_partner_ids,omptempty"`
MessageUnread *Bool `xmlrpc:"message_unread,omptempty"`
MessageUnreadCounter *Int `xmlrpc:"message_unread_counter,omptempty"`
Name *String `xmlrpc:"name,omptempty"`
Note *String `xmlrpc:"note,omptempty"`
ParentId *Many2One `xmlrpc:"parent_id,omptempty"`
TotalEmployee *Int `xmlrpc:"total_employee,omptempty"`
WebsiteMessageIds *Relation `xmlrpc:"website_message_ids,omptempty"`
WriteDate *Time `xmlrpc:"write_date,omptempty"`
WriteUid *Many2One `xmlrpc:"write_uid,omptempty"`
}
// HrDepartments represents array of hr.department model.
type HrDepartments []HrDepartment
// HrDepartmentModel is the odoo model name.
const HrDepartmentModel = "hr.department"
// Many2One convert HrDepartment to *Many2One.
func (hd *HrDepartment) Many2One() *Many2One {
return NewMany2One(hd.Id.Get(), "")
}
// CreateHrDepartment creates a new hr.department model and returns its id.
func (c *Client) CreateHrDepartment(hd *HrDepartment) (int64, error) {
ids, err := c.CreateHrDepartments([]*HrDepartment{hd})
if err != nil {
return -1, err
}
if len(ids) == 0 {
return -1, nil
}
return ids[0], nil
}
// CreateHrDepartment creates a new hr.department model and returns its id.
func (c *Client) CreateHrDepartments(hds []*HrDepartment) ([]int64, error) {
var vv []interface{}
for _, v := range hds {
vv = append(vv, v)
}
return c.Create(HrDepartmentModel, vv)
}
// UpdateHrDepartment updates an existing hr.department record.
func (c *Client) UpdateHrDepartment(hd *HrDepartment) error {
return c.UpdateHrDepartments([]int64{hd.Id.Get()}, hd)
}
// UpdateHrDepartments updates existing hr.department records.
// All records (represented by ids) will be updated by hd values.
func (c *Client) UpdateHrDepartments(ids []int64, hd *HrDepartment) error {
return c.Update(HrDepartmentModel, ids, hd)
}
// DeleteHrDepartment deletes an existing hr.department record.
func (c *Client) DeleteHrDepartment(id int64) error {
return c.DeleteHrDepartments([]int64{id})
}
// DeleteHrDepartments deletes existing hr.department records.
func (c *Client) DeleteHrDepartments(ids []int64) error {
return c.Delete(HrDepartmentModel, ids)
}
// GetHrDepartment gets hr.department existing record.
func (c *Client) GetHrDepartment(id int64) (*HrDepartment, error) {
hds, err := c.GetHrDepartments([]int64{id})
if err != nil {
return nil, err
}
if hds != nil && len(*hds) > 0 {
return &((*hds)[0]), nil
}
return nil, fmt.Errorf("id %v of hr.department not found", id)
}
// GetHrDepartments gets hr.department existing records.
func (c *Client) GetHrDepartments(ids []int64) (*HrDepartments, error) {
hds := &HrDepartments{}
if err := c.Read(HrDepartmentModel, ids, nil, hds); err != nil {
return nil, err
}
return hds, nil
}
// FindHrDepartment finds hr.department record by querying it with criteria.
func (c *Client) FindHrDepartment(criteria *Criteria) (*HrDepartment, error) {
hds := &HrDepartments{}
if err := c.SearchRead(HrDepartmentModel, criteria, NewOptions().Limit(1), hds); err != nil {
return nil, err
}
if hds != nil && len(*hds) > 0 {
return &((*hds)[0]), nil
}
return nil, fmt.Errorf("hr.department was not found with criteria %v", criteria)
}
// FindHrDepartments finds hr.department records by querying it
// and filtering it with criteria and options.
func (c *Client) FindHrDepartments(criteria *Criteria, options *Options) (*HrDepartments, error) {
hds := &HrDepartments{}
if err := c.SearchRead(HrDepartmentModel, criteria, options, hds); err != nil {
return nil, err
}
return hds, nil
}
// FindHrDepartmentIds finds records ids by querying it
// and filtering it with criteria and options.
func (c *Client) FindHrDepartmentIds(criteria *Criteria, options *Options) ([]int64, error) {
ids, err := c.Search(HrDepartmentModel, criteria, options)
if err != nil {
return []int64{}, err
}
return ids, nil
}
// FindHrDepartmentId finds record id by querying it with criteria.
func (c *Client) FindHrDepartmentId(criteria *Criteria, options *Options) (int64, error) {
ids, err := c.Search(HrDepartmentModel, criteria, options)
if err != nil {
return -1, err
}
if len(ids) > 0 {
return ids[0], nil
}
return -1, fmt.Errorf("hr.department was not found with criteria %v and options %v", criteria, options)
}
|
package main
import "strings"
func main() {
// var a = 13
// var b uint = 15
println(len(`"hello
dddddd
go!"`))
println(strings.Compare("b", "c"))
}
|
package zap_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/shanexu/logn/common"
"github.com/shanexu/logn/core/zap"
_ "github.com/shanexu/logn/includes"
)
func TestNew(t *testing.T) {
rawConfig, err := common.NewConfigFrom(`
appenders:
console:
- name: CONSOLE
target: stdout
encoder:
json:
file:
- name: FILE
file_name: /tmp/app.log
encoder:
json:
- name: METRICS
file_name: /tmp/metrics.log
encoder:
json:
loggers:
root:
level: info
appender_refs:
- CONSOLE
logger:
- name: helloworld
appender_refs:
- CONSOLE
- FILE
level: debug
`)
if err != nil {
t.Fatal(err)
}
c, err := zap.New(rawConfig)
assert.NotNil(t, c)
assert.Nil(t, err)
hello := c.GetLogger("hello")
hello.Info("hello")
world := c.GetLogger("world")
world.Debug("world")
helloworld := c.GetLogger("helloworld")
helloworld.Info("hello world")
c.Sync()
}
|
package gitlabClient
import (
"github.com/xanzy/go-gitlab"
)
func (git *GitLab) ListGroup() ([]*gitlab.Group, error) {
opt := &gitlab.ListGroupsOptions{
ListOptions: gitlab.ListOptions{
PerPage: 100,
Page: 1,
},
}
for {
// Get the first page with projects.
groups, resp, err := git.Client.Groups.ListGroups(opt)
if err != nil {
return groups, err
}
// List all the projects we've found so far.
//for _, g := range groups {
// fmt.Printf("Found groups: %s", g.Name)
//}
// Exit the loop when we've seen all pages.
if resp.CurrentPage >= resp.TotalPages {
return groups, err
}
// Update the page number to get the next page.
opt.Page = resp.NextPage
}
}
func (git *GitLab) CreateGroupLabel(projectId interface{}, label gitlab.Label) error {
// Create new label
l := &gitlab.CreateGroupLabelOptions{
Name: &label.Name,
Color: &label.Color,
}
_, _, err := git.Client.GroupLabels.CreateGroupLabel(projectId, l)
if err != nil {
return err
}
return nil
}
|
package shell
import (
"yunion.io/x/onecloud/pkg/multicloud/jdcloud"
"yunion.io/x/onecloud/pkg/util/shellutils"
)
func init() {
type DescribeMetricDataOptions struct {
/* 监控项英文标识(id) */
Metric string `help:"metric name"json:"metric"`
TimeInterval string `help:"time interval" choices:"1h|6h|12h|1d|3d|7d|14d" json:"timeInterval"`
ServiceCode string `help:"resource code" choices:"vm" json:"serviceCode"`
ResourceId string `help:"resource id" json:"resourceId"`
}
shellutils.R(&DescribeMetricDataOptions{}, "metric-list", "list metric", func(cli *jdcloud.SRegion,
args *DescribeMetricDataOptions) error {
request := jdcloud.NewDescribeMetricDataRequestWithAllParams(cli.GetId(),
args.Metric, nil, nil, &args.TimeInterval, &args.ServiceCode, args.ResourceId)
response, err := cli.GetMetricsData(request)
if err != nil {
return err
}
printList(response.Result.MetricDatas, 0, 0, 0, nil)
return nil
})
}
|
/*
1 fizzbuzz.go
Output the numbers from 1 to 100, one per line. However, if the number is divisible by 3 output 'Fizz', if the number is divisible output 'Buzz' and if the number is divisible by both 3 and 5 output 'FizzBuzz'
Author: tatu.kairi@gmail.com
*/
package main
import (
"fmt"
"strconv"
)
func main() {
for i := 1; i <= 100; i++ {
result := ""
if i % 3 == 0 {
result += "Fizz"
}
if i % 5 == 0 {
result += "Buzz"
}
if result == "" {
result += strconv.Itoa(i)
}
fmt.Printf("%s\n", result)
}
}
|
package model
// LightMeasuredPayload is a Schema defined in the AsyncAPI specification
// TODO: Support custom tags
type LightMeasuredPayload struct {
// Lumens is a property defined in the AsyncAPI specification
Lumens *int64 `json:"lumens"`
// SentAt is a property defined in the AsyncAPI specification
SentAt *SentAt `json:"sentAt"`
}
func NewLightMeasuredPayload() *LightMeasuredPayload {
return new(LightMeasuredPayload)
} |
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
arr := make([]int, n)
for i := range arr {
fmt.Scan(&arr[i])
}
sorted := insertionSort(arr)
// printArray(sorted)
}
func insertionSort(arr []int) []int {
var x, j int
shiftsNumber := 0
for i := 1; i < len(arr); i++ {
x = arr[i]
j = i
for (j > 0) && (arr[j-1] > x) {
shiftsNumber = shiftsNumber + 1
arr[j] = arr[j-1]
j = j - 1
}
arr[j] = x
}
fmt.Printf("%d", shiftsNumber)
return arr
}
func printArray(arr []int) {
for i := range arr {
fmt.Printf("%d ", arr[i])
}
fmt.Println()
}
|
package migrations
import (
"github.com/Focinfi/sakura/app/models"
"github.com/Focinfi/sakura/db"
)
func init() {
migrate(
&models.User{},
&models.ActivityNote{},
&models.Tag{},
&models.ActivityNoteTag{},
&models.ActivityCategory{},
&models.ActivityNoteCategory{},
&models.Feeling{},
&models.UserFeeling{},
&models.Tip{},
)
}
func migrate(tables ...interface{}) {
for _, table := range tables {
db.DB.DropTableIfExists(table)
db.DB.AutoMigrate(table)
}
}
|
package persistent
import (
"fmt"
"github.com/EventStore/EventStore-Client-Go/position"
"github.com/EventStore/EventStore-Client-Go/protos/persistent"
"github.com/EventStore/EventStore-Client-Go/protos/shared"
)
func updateRequestStreamProto(config SubscriptionStreamConfig) *persistent.UpdateReq {
return &persistent.UpdateReq{
Options: updateSubscriptionStreamConfigProto(config),
}
}
func UpdateRequestAllOptionsProto(
config SubscriptionUpdateAllOptionConfig,
) *persistent.UpdateReq {
options := updateRequestAllOptionsSettingsProto(config.Position)
return &persistent.UpdateReq{
Options: &persistent.UpdateReq_Options{
StreamOption: options,
GroupName: config.GroupName,
Settings: updateSubscriptionSettingsProto(config.Settings),
},
}
}
func updateRequestAllOptionsSettingsProto(
pos position.Position,
) *persistent.UpdateReq_Options_All {
options := &persistent.UpdateReq_Options_All{
All: &persistent.UpdateReq_AllOptions{
AllOption: nil,
},
}
if pos == position.StartPosition {
options.All.AllOption = &persistent.UpdateReq_AllOptions_Start{
Start: &shared.Empty{},
}
} else if pos == position.EndPosition {
options.All.AllOption = &persistent.UpdateReq_AllOptions_End{
End: &shared.Empty{},
}
} else {
options.All.AllOption = toUpdateRequestAllOptionsFromPosition(pos)
}
return options
}
func updateSubscriptionStreamConfigProto(config SubscriptionStreamConfig) *persistent.UpdateReq_Options {
return &persistent.UpdateReq_Options{
StreamOption: updateSubscriptionStreamSettingsProto(config.StreamOption),
// backward compatibility
StreamIdentifier: &shared.StreamIdentifier{
StreamName: config.StreamOption.StreamName,
},
GroupName: config.GroupName,
Settings: updateSubscriptionSettingsProto(config.Settings),
}
}
func updateSubscriptionStreamSettingsProto(
streamConfig StreamSettings,
) *persistent.UpdateReq_Options_Stream {
streamOption := &persistent.UpdateReq_Options_Stream{
Stream: &persistent.UpdateReq_StreamOptions{
StreamIdentifier: &shared.StreamIdentifier{
StreamName: streamConfig.StreamName,
},
RevisionOption: nil,
},
}
if streamConfig.Revision == Revision_Start {
streamOption.Stream.RevisionOption = &persistent.UpdateReq_StreamOptions_Start{
Start: &shared.Empty{},
}
} else if streamConfig.Revision == Revision_End {
streamOption.Stream.RevisionOption = &persistent.UpdateReq_StreamOptions_End{
End: &shared.Empty{},
}
} else {
streamOption.Stream.RevisionOption = &persistent.UpdateReq_StreamOptions_Revision{
Revision: uint64(streamConfig.Revision),
}
}
return streamOption
}
func updateSubscriptionSettingsProto(
settings SubscriptionSettings,
) *persistent.UpdateReq_Settings {
return &persistent.UpdateReq_Settings{
ResolveLinks: settings.ResolveLinks,
ExtraStatistics: settings.ExtraStatistics,
MaxRetryCount: settings.MaxRetryCount,
MinCheckpointCount: settings.MinCheckpointCount,
MaxCheckpointCount: settings.MaxCheckpointCount,
MaxSubscriberCount: settings.MaxSubscriberCount,
LiveBufferSize: settings.LiveBufferSize,
ReadBatchSize: settings.ReadBatchSize,
HistoryBufferSize: settings.HistoryBufferSize,
NamedConsumerStrategy: updateRequestConsumerStrategyProto(settings.NamedConsumerStrategy),
MessageTimeout: updateRequestMessageTimeOutInMsProto(settings.MessageTimeoutInMs),
CheckpointAfter: updateRequestCheckpointAfterMsProto(settings.CheckpointAfterInMs),
}
}
func updateRequestConsumerStrategyProto(
strategy ConsumerStrategy,
) persistent.UpdateReq_ConsumerStrategy {
switch strategy {
case ConsumerStrategy_DispatchToSingle:
return persistent.UpdateReq_DispatchToSingle
case ConsumerStrategy_Pinned:
return persistent.UpdateReq_Pinned
case ConsumerStrategy_RoundRobin:
return persistent.UpdateReq_RoundRobin
default:
panic(fmt.Sprintf("Could not map strategy %v to proto", strategy))
}
}
func updateRequestMessageTimeOutInMsProto(
timeout int32,
) *persistent.UpdateReq_Settings_MessageTimeoutMs {
return &persistent.UpdateReq_Settings_MessageTimeoutMs{
MessageTimeoutMs: timeout,
}
}
func updateRequestCheckpointAfterMsProto(
checkpointAfterMs int32,
) *persistent.UpdateReq_Settings_CheckpointAfterMs {
return &persistent.UpdateReq_Settings_CheckpointAfterMs{
CheckpointAfterMs: checkpointAfterMs,
}
}
// toUpdateRequestAllOptionsFromPosition ...
func toUpdateRequestAllOptionsFromPosition(position position.Position) *persistent.UpdateReq_AllOptions_Position {
return &persistent.UpdateReq_AllOptions_Position{
Position: &persistent.UpdateReq_Position{
PreparePosition: position.Prepare,
CommitPosition: position.Commit,
},
}
}
|
package customsearch
type (
apiKey string
)
func (a apiKey) Get() (string, string) {
return "key", string(a)
}
|
package main
import (
"context"
"fmt"
)
type User struct {
Name string
IsLoggedIn bool
}
type userKeyType int
var userKey userKeyType
func contextWithUser(ctx context.Context, user *User) context.Context {
return context.WithValue(ctx, userKey, user)
}
func getUserFromContext(ctx context.Context) *User {
fmt.Printf("%#v\n", userKey)
user, ok := ctx.Value(userKey).(*User)
if !ok {
return nil
}
return user
}
func printUser(ctx context.Context) {
user := getUserFromContext(ctx)
fmt.Printf("%#v\n", user)
}
func main() {
user := &User{
Name: "john",
IsLoggedIn: false,
}
ctx := contextWithUser(context.Background(), user)
printUser(ctx)
ctxa := context.WithValue(context.Background(), "a", "a")
ctxb := context.WithValue(ctxa, "b", "b")
val := ctxb.Value("a")
fmt.Println(val)
}
|
package main
// Microservice
// Test Handler
// Copyright © 2016 Eduard Sesigin. All rights reserved. Contacts: <claygod@yandex.ru>
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHandlerHelloWorld(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
conf, err := NewTuner("config.toml")
if err != nil {
panic(err)
}
hr := NewHandler(conf)
hr.HelloWorld(w, req)
if req.Header.Get("Test") != "Test" {
t.Error("Error Handler in the `HelloWorld`")
}
}
|
/*
Copyright © 2021 Damien Coraboeuf <damien.coraboeuf@nemerosa.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"fmt"
"ontrack-cli/client"
"ontrack-cli/config"
"strings"
"github.com/spf13/cobra"
)
// buildChangelogExportCmd represents the buildChangelog command
var buildChangelogExportCmd = &cobra.Command{
Use: "export",
Aliases: []string{"format"},
Short: "Formats the change log between two builds",
Long: `Formats the change log between two builds.
For example:
ontrack-cli build changelog --from 1 --to 2
Additional options are available for the formatting:
ontrack-cli build changelog --from 1 --to 2 \
--format markdown \
--grouping "Bugs=bug|Features=features" \
--alt-group "Misc" \
--exclude delivery
The change log is available directly in the standard output.
`,
RunE: func(cmd *cobra.Command, args []string) error {
// Boundaries
from, err := cmd.Flags().GetInt("from")
if err != nil {
return err
}
to, err := cmd.Flags().GetInt("to")
if err != nil {
return err
}
// Format options
format, err := cmd.Flags().GetString("format")
if err != nil {
return err
}
grouping, err := cmd.Flags().GetString("grouping")
if err != nil {
return err
}
altGroup, err := cmd.Flags().GetString("alt-group")
if err != nil {
return err
}
exclude, err := cmd.Flags().GetString("exclude")
if err != nil {
return err
}
// Query
query := `
query ExportChangeLog(
$from: Int!,
$to: Int!,
$request: IssueChangeLogExportRequest!
) {
gitChangeLog(from: $from, to: $to) {
export(request: $request)
}
}
`
// Request
request := make(map[string]interface{})
if format != "" {
request["format"] = format
}
if grouping != "" {
request["grouping"] = grouping
}
if altGroup != "" {
request["altGroup"] = altGroup
}
if exclude != "" {
request["exclude"] = exclude
}
// Data
var data struct {
GitChangeLog struct {
Export string
}
}
// Getting the configuration
cfg, err := config.GetSelectedConfiguration()
if err != nil {
return err
}
// Call
if err := client.GraphQLCall(cfg, query, map[string]interface{}{
"from": from,
"to": to,
"request": request,
}, &data); err != nil {
return err
}
// Print the exported change log
fmt.Println(strings.TrimSpace(data.GitChangeLog.Export))
// OK
return nil
},
}
func init() {
buildChangelogCmd.AddCommand(buildChangelogExportCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// buildChangelogExportCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// buildChangelogExportCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
buildChangelogExportCmd.Flags().String("format", "", "Format of the changelog: text (default), markdown or html")
buildChangelogExportCmd.Flags().String("grouping", "", "Grouping specification (see Ontrack doc)")
buildChangelogExportCmd.Flags().String("alt-group", "", "Name of the group for unclassified issues")
buildChangelogExportCmd.Flags().String("exclude", "", "Comma separated list of issue types to ignore")
}
|
// Copyright 2018 The go-Dacchain Authors
// This file is part of the go-Dacchain library.
//
// The go-Dacchain 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-Dacchain 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-Dacchain library. If not, see <http://www.gnu.org/licenses/>.
package state
import (
"bytes"
"fmt"
"github.com/Dacchain/go-Dacchain/common"
"github.com/Dacchain/go-Dacchain/core/types"
"github.com/Dacchain/go-Dacchain/crypto"
"github.com/Dacchain/go-Dacchain/rlp"
"github.com/Dacchain/go-Dacchain/trie"
"io"
"math/big"
)
var emptyCodeHash = crypto.Keccak256(nil)
type Code []byte
func (self Code) String() string {
return string(self) //strings.Join(Disassemble(self), " ")
}
type Storage map[common.Hash]common.Hash
func (self Storage) String() (str string) {
for key, value := range self {
str += fmt.Sprintf("%X : %X\n", key, value)
}
return
}
func (self Storage) Copy() Storage {
cpy := make(Storage)
for key, value := range self {
cpy[key] = value
}
return cpy
}
// stateObject represents an Davinci account which is being modified.
//
// The usage pattern is as follows:
// First you need to obtain a state object.
// Account values can be accessed and modified through the object.
// Finally, call CommitTrie to write the modified storage trie into a database.
type stateObject struct {
address common.Address
addrHash common.Hash // hash of davinci address of the account
data Account
db *StateDB
// DB error.
// State objects are used by the consensus core and VM which are
// unable to deal with database-level errors. Any error that occurs
// during a database read is memoized here and will eventually be returned
// by StateDB.Commit.
dbErr error
// Write caches.
trie Trie // storage trie, which becomes non-nil on first access
code Code // contract bytecode, which gets set when code is loaded
abi string // contract abi, can be "".
assetData []byte //asset data, only when the account is a assetAccount that this data has values.
cachedStorage Storage // Storage entry cache to avoid duplicate reads
dirtyStorage Storage // Storage entries that need to be flushed to disk
// Cache flags.
// When an object is marked suicided it will be delete from the trie
// during the "update" phase of the state transition.
dirtyCode bool // true if the code was updated
suicided bool
touched bool
deleted bool
dirtyAssetData bool
onDirty func(addr common.Address) // Callback method to mark a state object newly dirty
}
// empty returns whether the account is considered empty.
func (s *stateObject) empty() bool {
return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash) && s.data.AssetList.IsEmpty()
}
// Account is the Davinci consensus representation of accounts.
// These objects are stored in the main account trie.
type Account struct {
Nonce uint64
Balance *big.Int
Root common.Hash // merkle root of the storage trie
CodeHash []byte
LockBalance *big.Int // lock vote balance
VoteList []common.Address // vote list
AssetList *types.Assets // ascending alphabet ordered Assets.
AssetHash []byte
}
// newObject creates a state object.
func newObject(db *StateDB, address common.Address, data Account, onDirty func(addr common.Address)) *stateObject {
if data.Balance == nil {
data.Balance = new(big.Int)
}
if data.CodeHash == nil {
data.CodeHash = emptyCodeHash
}
if data.AssetList == nil {
data.AssetList = types.NewAssets()
}
return &stateObject{
db: db,
address: address,
addrHash: crypto.Keccak256Hash(address[:]),
data: data,
cachedStorage: make(Storage),
dirtyStorage: make(Storage),
onDirty: onDirty,
}
}
// EncodeRLP implements rlp.Encoder.
func (c *stateObject) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, c.data)
}
// setError remembers the first non-nil error it is called with.
func (self *stateObject) setError(err error) {
if self.dbErr == nil {
self.dbErr = err
}
}
//tryMarkDirty trying to mark this object as dirty, at most once.
func (self *stateObject) tryMarkDirty() {
if self.onDirty != nil {
self.onDirty(self.Address())
self.onDirty = nil
}
}
func (self *stateObject) markSuicided() {
self.suicided = true
self.tryMarkDirty()
}
func (self *stateObject) touch() {
self.db.journal = append(self.db.journal, touchChange{
account: &self.address,
prev: self.touched,
prevDirty: self.onDirty == nil,
})
self.tryMarkDirty()
self.touched = true
}
func (c *stateObject) getTrie(db Database) Trie {
if c.trie == nil {
var err error
c.trie, err = db.OpenStorageTrie(c.addrHash, c.data.Root)
if err != nil {
c.trie, _ = db.OpenStorageTrie(c.addrHash, common.Hash{})
c.setError(fmt.Errorf("can't create storage trie: %v", err))
}
}
return c.trie
}
// GetState returns a value in account storage.
func (self *stateObject) GetState(db Database, key common.Hash) common.Hash {
value, exists := self.cachedStorage[key]
if exists {
return value
}
// Load from DB in case it is missing.
enc, err := self.getTrie(db).TryGet(key[:])
if err != nil {
self.setError(err)
return common.Hash{}
}
if len(enc) > 0 {
_, content, _, err := rlp.Split(enc)
if err != nil {
self.setError(err)
}
value.SetBytes(content)
}
if (value != common.Hash{}) {
self.cachedStorage[key] = value
}
return value
}
// SetState updates a value in account storage.
func (self *stateObject) SetState(db Database, key, value common.Hash) {
self.db.journal = append(self.db.journal, storageChange{
account: &self.address,
key: key,
prevalue: self.GetState(db, key),
})
self.setState(key, value)
}
func (self *stateObject) setState(key, value common.Hash) {
self.cachedStorage[key] = value
self.dirtyStorage[key] = value
self.tryMarkDirty()
}
// updateTrie writes cached storage modifications into the object's storage trie.
func (self *stateObject) updateTrie(db Database) Trie {
tr := self.getTrie(db)
for key, value := range self.dirtyStorage {
delete(self.dirtyStorage, key)
if (value == common.Hash{}) {
self.setError(tr.TryDelete(key[:]))
continue
}
// Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
self.setError(tr.TryUpdate(key[:], v))
}
return tr
}
// UpdateRoot sets the trie root to the current root hash of
func (self *stateObject) updateRoot(db Database) {
self.updateTrie(db)
self.data.Root = self.trie.Hash()
}
// CommitTrie the storage trie of the object to dwb.
// This updates the trie root.
func (self *stateObject) CommitTrie(db Database, dbw trie.DatabaseWriter) error {
self.updateTrie(db)
if self.dbErr != nil {
return self.dbErr
}
root, err := self.trie.CommitTo(dbw)
if err == nil {
self.data.Root = root
}
return err
}
// AddBalance removes amount from c's balance.
// It is used to add funds to the destination account of a transfer.
func (c *stateObject) AddBalance(amount *big.Int) {
// EIP158: We must check emptiness for the objects such that the account
// clearing (0,0,0 objects) can take effect.
if amount.Sign() == 0 {
if c.empty() {
c.touch()
}
return
}
c.SetBalance(new(big.Int).Add(c.Balance(), amount))
}
// SubBalance removes amount from c's balance.
// It is used to remove funds from the origin account of a transfer.
func (c *stateObject) SubBalance(amount *big.Int) {
if amount.Sign() == 0 {
return
}
c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
}
func (self *stateObject) SetBalance(amount *big.Int) {
self.db.journal = append(self.db.journal, balanceChange{
account: &self.address,
prev: new(big.Int).Set(self.data.Balance),
})
self.setBalance(amount)
}
func (self *stateObject) setBalance(amount *big.Int) {
self.data.Balance = amount
self.tryMarkDirty()
}
func (self *stateObject) AddLockBalance(amount *big.Int) {
if amount.Sign() == 0 {
if self.empty() {
self.touch()
}
return
}
self.SetLockBalance(new(big.Int).Add(self.LockBalance(), amount))
}
func (self *stateObject) SubLockBalance(amount *big.Int) {
if amount.Sign() == 0 {
return
}
self.SetLockBalance(new(big.Int).Sub(self.LockBalance(), amount))
}
func (self *stateObject) SetLockBalance(amount *big.Int) {
self.db.journal = append(self.db.journal, lockBalanceChange{
account: &self.address,
prev: new(big.Int).Set(self.data.LockBalance),
})
self.setLockBalance(amount)
}
func (self *stateObject) setLockBalance(amount *big.Int) {
self.data.LockBalance = amount
self.tryMarkDirty()
}
// Return the gas back to the origin. Used by the Virtual machine or Closures
func (c *stateObject) ReturnGas(gas *big.Int) {}
func (self *stateObject) deepCopy(db *StateDB, onDirty func(addr common.Address)) *stateObject {
stateObject := newObject(db, self.address, self.data, onDirty)
if self.trie != nil {
stateObject.trie = db.db.CopyTrie(self.trie)
}
stateObject.code = self.code
stateObject.dirtyStorage = self.dirtyStorage.Copy()
stateObject.cachedStorage = self.dirtyStorage.Copy()
stateObject.suicided = self.suicided
stateObject.dirtyCode = self.dirtyCode
stateObject.deleted = self.deleted
return stateObject
}
//
// Attribute accessors
//
// Returns the address of the contract/account
func (c *stateObject) Address() common.Address {
return c.address
}
// Code returns the contract code associated with this object, if any.
func (self *stateObject) Code(db Database) []byte {
if self.code != nil {
return self.code
}
if bytes.Equal(self.CodeHash(), emptyCodeHash) {
return nil
}
code, err := db.ContractCode(self.addrHash, common.BytesToHash(self.CodeHash()))
if err != nil {
self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
}
self.code = code
return code
}
func (self *stateObject) Abi(db Database) string {
if len(self.abi) > 0 {
return self.abi
}
if bytes.Equal(self.CodeHash(), emptyCodeHash) {
return ""
}
abi, err := db.ContractAbi(self.addrHash, common.BytesToHash(self.CodeHash()))
if err != nil {
self.setError(fmt.Errorf("can't load abi. code hash %x: %v", self.CodeHash(), err))
}
self.abi = abi
return abi
}
func (self *stateObject) SetCode(codeHash common.Hash, code []byte) {
prevcode := self.Code(self.db.db)
self.db.journal = append(self.db.journal, codeChange{
account: &self.address,
prevhash: self.CodeHash(),
prevcode: prevcode,
})
self.setCode(codeHash, code)
}
func (self *stateObject) setCode(codeHash common.Hash, code []byte) {
self.code = code
self.data.CodeHash = codeHash[:]
self.dirtyCode = true
self.tryMarkDirty()
}
func (self *stateObject) SetAbi(abi string) {
self.abi = abi
}
func (self *stateObject) SetNonce(nonce uint64) {
self.db.journal = append(self.db.journal, nonceChange{
account: &self.address,
prev: self.data.Nonce,
})
self.setNonce(nonce)
}
func (self *stateObject) setNonce(nonce uint64) {
self.data.Nonce = nonce
self.tryMarkDirty()
}
func (self *stateObject) SetVoteList(voteList []common.Address) {
self.db.journal = append(self.db.journal, voteListChange{
account: &self.address,
prev: self.data.VoteList,
})
self.setVoteList(voteList)
}
func (self *stateObject) setVoteList(voteList []common.Address) {
self.data.VoteList = voteList
self.tryMarkDirty()
}
func (self *stateObject) CodeHash() []byte {
return self.data.CodeHash
}
func (self *stateObject) Balance() *big.Int {
return self.data.Balance
}
func (self *stateObject) Nonce() uint64 {
return self.data.Nonce
}
// Never called, but must be present to allow stateObject to be used
// as a vm.Account interface that also satisfies the vm.ContractRef
// interface. Interfaces are awesome.
func (self *stateObject) Value() *big.Int {
panic("Value on stateObject should never be called")
}
// Get vote list
func (self *stateObject) LockBalance() *big.Int {
return self.data.LockBalance
}
// Get vote list
func (self *stateObject) VoteList() []common.Address {
return self.data.VoteList
}
func (self *stateObject) BalanceOf(asset common.Address) *big.Int {
return self.data.AssetList.BalanceOf(asset)
}
func (self *stateObject) SubAssetBalance(asset common.Address, amount *big.Int) bool {
var a = types.Asset{ID: asset, Balance: new(big.Int).Set(amount)}
isOk := self.data.AssetList.SubAsset(a)
if isOk {
self.db.journal = append(self.db.journal, assetBalanceChange{
account: &self.address,
asset: types.Asset{ID: asset, Balance: new(big.Int).Set(amount)},
preOpIsAdd: false,
})
self.tryMarkDirty()
}
return isOk
}
func (self *stateObject) AddAssetBalance(asset common.Address, amount *big.Int) {
self.db.journal = append(self.db.journal, assetBalanceChange{
account: &self.address,
asset: types.Asset{ID: asset, Balance: new(big.Int).Set(amount)},
preOpIsAdd: true,
})
var a = types.Asset{ID: asset, Balance: new(big.Int).Set(amount)}
self.data.AssetList.AddAsset(a)
self.tryMarkDirty()
}
func (self *stateObject) revertAssetBalance(asset types.Asset, preOpIsAdd bool) {
if preOpIsAdd {
self.data.AssetList.SubAsset(asset)
} else {
self.data.AssetList.AddAsset(asset)
}
self.tryMarkDirty()
}
func (self *stateObject) GetAssets() []types.Asset {
return self.data.AssetList.GetAssets()
}
func (self *stateObject) SetAssetData(hash common.Hash, data []byte) error {
if len(self.assetData) > 0 {
return fmt.Errorf("assetData already exist, can not be updated")
}
self.assetData = append(self.assetData, data...)
self.data.AssetHash = hash[:]
self.dirtyAssetData = true
self.tryMarkDirty()
return nil
}
func (self *stateObject) AssetHash() []byte {
return self.data.AssetHash
}
// AssetData returns the Asset data associated with this object, if any.
func (self *stateObject) AssetData(db Database) ([]byte, error) {
if self.assetData != nil {
return self.assetData, nil
}
if !self.IsAssetAccount() {
return nil, nil
}
assetdata, err := db.AssetData(self.addrHash, common.BytesToHash(self.data.AssetHash))
self.assetData = assetdata
return assetdata, err
}
func (self *stateObject) IsAssetAccount() bool {
if len(self.data.AssetHash) == 0 || bytes.Equal(self.data.AssetHash, emptyCodeHash) {
return false
}
return true
}
|
package chart
import (
"fmt"
"github.com/go-echarts/go-echarts/v2/charts"
"github.com/go-echarts/go-echarts/v2/opts"
// "github.com/go-echarts/go-echarts/v2/types"
)
//多重柱状图
func BarMulti(table *Table) *charts.Bar {
bar := charts.NewBar()
bar.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{
Title: table.Title,
Subtitle: table.Subtitle,
}),
charts.WithInitializationOpts(opts.Initialization{
Theme: "shine",
Width: "1400px",
Height: "550px",
}),
charts.WithTooltipOpts(opts.Tooltip{Show: true}), //滑动
charts.WithYAxisOpts(opts.YAxis{
SplitLine: &opts.SplitLine{
Show: true,
},
}), //展示具体值
//可以放大====
// charts.WithXAxisOpts(opts.XAxis{
// SplitNumber: 20,
// }),
// charts.WithYAxisOpts(opts.YAxis{
// Scale: true,
// }),
// charts.WithDataZoomOpts(opts.DataZoom{
// Type: "inside",
// Start: 50,
// End: 100,
// XAxisIndex: []int{0},
// }),
//可以放大====
)
bar.SetXAxis(table.DimValue)
for i, field := range table.Field {
if i == 0 {
continue
}
bar.AddSeries(field, generateBarItems(table, field))
}
//展示悬停值
bar.SetSeriesOptions(
charts.WithLabelOpts(opts.Label{
Show: true,
Position: "top",
}))
return bar
}
// generate random data for line chart
func generateBarItems(table *Table, field string) []opts.BarData {
fmt.Println(field)
values := table.Value[field]
fmt.Println(values)
lens := len(table.DimValue)
fmt.Println(lens)
items := make([]opts.BarData, 0)
for i := 0; i < lens; i++ {
items = append(items, opts.BarData{Value: values[i]})
}
return items
}
|
package main
import (
"fmt"
"encoding/json"
//"reflect"
)
type Book struct {
Title string
Author string
Pages int
}
// JSON.Marshal(): Takes Struct and returns a byte array.
func (b Book) ToJSON() []byte { // No need to pass object as method is attached to Book struct anyway.
byte_array, err := json.Marshal(b)
if (err != nil){
panic(err)
}
return (byte_array)
}
func main() {
b := []Book{
Book{Title: "Python", Author: "Ro", Pages:500},
Book{Title: "Golang", Author: "RoT", Pages: 400}, // Notice the "," in the end. This is not JSON but a struct.
}
//b := Book{Title: "Python", Author: "Ro", Pages:500}
// result := reflect.TypeOf(b) -> []uint8 (Because its a Byte array of integers)
fmt.Println(string(b[1].ToJSON()))
}
|
package organization
type Invitation struct {
Created Date `json:"created"`
Role string `json:"role"`
User string `json:"user"`
}
|
// Package testhelper provides some useful helpers for testing in github.com/768bit/promethium/lib/images/diskfs subpackages
package testhelper
|
package game
import (
"encoding/csv"
"fmt"
"io"
"strings"
)
type Game struct {
Grid1, Grid2 Grid
Move1, Move2 Moves
M, S, T int
// private fields
p1score, p2score int
p1ShipCount, p2ShipCount int
}
type Move struct {
X, Y int
}
type Moves []Move
// populate is a unexported function which populates player moves read from input.
func (m Moves) populate(line string) {
csvreader := csv.NewReader(strings.NewReader(line))
csvreader.Comma = ':'
records, _ := csvreader.ReadAll()
for i := range records[0] {
var x, y int
fmt.Sscanf(records[0][i], "%d,%d", &x, &y)
m[i] = Move{x, y}
}
}
type Grid [][]byte
// String method useful to represent an Player Grid as per problem statement.
func (g Grid) String() string {
// TODO(kaviraj): Fix extra space and newline edge case
var s string
for i := 0; i < len(g); i++ {
for j := 0; j < len(g[0]); j++ {
s += fmt.Sprintf("%c ", g[i][j])
}
s += fmt.Sprintf("\n")
}
return s
}
// populate unexported function used to populate player grid from input.
func (g Grid) populate(line string) {
csvreader := csv.NewReader(strings.NewReader(line))
records, _ := csvreader.ReadAll()
for i := range records[0] {
var x, y int
fmt.Sscanf(records[0][i], "%d:%d", &x, &y)
g[x][y] = 'B'
}
}
// New creates a new BattleGame instance by reading input from io.Reader.
func New(r io.Reader) *Game {
var g Game
fmt.Fscanln(r, &g.M)
fmt.Fscanln(r, &g.S)
// Get Player1 positions
g.Grid1 = make([][]byte, g.M)
for i := 0; i < g.M; i++ {
g.Grid1[i] = make([]byte, g.M)
for j := 0; j < g.M; j++ {
g.Grid1[i][j] = '_'
}
}
var line string
fmt.Fscanln(r, &line)
g.Grid1.populate(line)
// Get Player2 positions
g.Grid2 = make([][]byte, g.M)
for i := 0; i < g.M; i++ {
g.Grid2[i] = make([]byte, g.M)
for j := 0; j < g.M; j++ {
g.Grid2[i][j] = '_'
}
}
fmt.Fscanln(r, &line)
g.Grid2.populate(line)
fmt.Fscanln(r, &g.T)
fmt.Fscanln(r, &line)
g.Move1 = make([]Move, g.T)
g.Move1.populate(line)
fmt.Fscanln(r, &line)
g.Move2 = make([]Move, g.T)
g.Move2.populate(line)
g.p1ShipCount = g.S
g.p2ShipCount = g.S
return &g
}
// Play is real simulation based on input moves of both the player.
// It calculates the player score using the moves from the input
func (g *Game) Play() {
// NOTE(kaviraj):
// 1. Make all the moves (first Player1 then Player2 sequentially)
// 2. Calculate the score and update the grid
// 3. End the game once done with all the moves
for i := 0; i < len(g.Move1); i++ {
x, y := g.Move1[i].X, g.Move1[i].Y
if g.p1ShipCount != 0 && g.Grid2[x][y] == 'B' {
g.Grid2[x][y] = 'X'
g.p1score++
g.p2ShipCount--
} else {
g.Grid2[x][y] = 'O'
}
x, y = g.Move2[i].X, g.Move2[i].Y
if g.p2ShipCount != 0 && g.Grid1[x][y] == 'B' {
g.Grid1[x][y] = 'X'
g.p2score++
g.p1ShipCount--
} else {
g.Grid1[x][y] = 'O'
}
}
}
// P1Score should be called after invoking Play().
// Gives the Player1 score
func (g *Game) P1Score() int {
return g.p1score
}
// P2Score should be called after invoking Play().
// Gives the Player2 score
func (g *Game) P2Score() int {
return g.p2score
}
func (g *Game) Result() string {
p1Score := g.P1Score()
p2Score := g.P2Score()
var r string
switch {
case p1Score > p2Score:
r = "Player 1 wins"
case p1Score < p2Score:
r = "Player 2 wins"
default:
r = "It is a draw"
}
return r
}
|
package util
type Comparable interface {
Equal(Comparable) bool
}
func IsStringSliceEqual(arr1 []string, arr2 []string) bool {
if len(arr1) == len(arr2) {
var i int
var c1, c2 string
for i, c1 = range arr1 {
c2 = arr2[i]
if c1 != c2 {
return false
}
}
return true
} else {
return false
}
}
func IsSliceEqual(arr1 []Comparable, arr2 []Comparable) bool {
if len(arr1) == len(arr2) {
var i int
var c1, c2 Comparable
for i, c1 = range arr1 {
c2 = arr2[i]
if !c1.Equal(c2) {
return false
}
}
return true
} else {
return false
}
}
|
package main
import (
"context"
"fmt"
"time"
"github.com/mongodb/mongo-go-driver/mongo"
"github.com/mongodb/mongo-go-driver/mongo/options"
)
//时间点
type TimePoint struct {
StartTime int64 `bson:"starttime"`
EndTime int64 `bson:"endtime"`
}
//日志结构
type LogRecord struct {
JobName string `bson:"jobname"`
Command string `bson:"command`
Err string `bson:"err"`
Content string `bson:"content"`
TimePoint TimePoint `bson:"timepoint"`
}
//查询条件结构体
type FindByJobName struct {
JobName string `bson:"jobname"`
}
func main() {
opts := &options.ClientOptions{}
opts.SetConnectTimeout(5 * time.Second)
cli, err := mongo.Connect(context.TODO(), "mongodb://192.168.56.11:27017")
if err != nil {
fmt.Println(err)
}
db := cli.Database("cron")
coll := db.Collection("log")
//创建查询条件
filter := &FindByJobName{
JobName: "job10",
}
//查询
cursor, err := coll.Find(context.TODO(), filter, options.Find().SetSkip(0), options.Find().SetLimit(10))
if err != nil {
fmt.Println(err)
return
}
defer cursor.Close(context.TODO())
//遍历结果集
for cursor.Next(context.TODO()) {
record := &LogRecord{}
//反序列化结果
err := cursor.Decode(record)
if err != nil {
fmt.Println(err)
return
}
//打印结果
fmt.Println(*record)
}
}
|
// Copyright (C) 2018-Present Pivotal Software, Inc. All rights reserved.
// This program and the accompanying materials are made available under the terms of the 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 broker
import (
"log"
"github.com/pivotal-cf/on-demand-service-broker/boshdirector"
)
//counterfeiter:generate -o fakes/fake_manifest_secrets_manager.go . ManifestSecretManager
type ManifestSecretManager interface {
ResolveManifestSecrets(manifest []byte, deploymentVariables []boshdirector.Variable, logger *log.Logger) (map[string]string, error)
DeleteSecretsForInstance(instanceID string, logger *log.Logger) error
}
|
//
// June 2016, cisco
//
// Copyright (c) 2016 by cisco Systems, Inc.
// All rights reserved.
//
//
package main
import (
"github.com/dlintw/goconf"
"testing"
"time"
)
func TestMetricsConfigureNegative(t *testing.T) {
var nc nodeConfig
mod := metricsOutputModuleNew()
cfg, err := goconf.ReadConfigFile("pipeline_test_bad.conf")
nc.config = cfg
badsections := []string{
"metricsbad_missingfilename",
"metricsbad_missingfile",
"metricsbad_badjson",
"metricsbad_missingoutput",
"metricsbad_unsupportedoutput",
"metricsbad_missingpushgw",
}
for _, section := range badsections {
err, _, _ = mod.configure(section, nc)
if err == nil {
t.Errorf("metrics section section [%v] should fail\n", section)
}
}
}
func TestMetricsConfigure(t *testing.T) {
var nc nodeConfig
var codecJSONTestSource testSource
mod := metricsOutputModuleNew()
cfg, err := goconf.ReadConfigFile("pipeline_test.conf")
nc.config = cfg
err, dChan, cChan := mod.configure("mymetrics", nc)
err, p := getNewCodecJSON("JSON CODEC TEST")
if err != nil {
t.Errorf("Failed to get JSON codec [%v]", err)
return
}
testJSONMsg := []byte(`{"Name":"Alice","Body":"Hello","Test":1294706395881547000}`)
err, dMs := p.blockToDataMsgs(&codecJSONTestSource, testJSONMsg)
if err != nil {
t.Errorf("Failed to get messages from JSON stream [%v]", err)
return
}
dM := dMs[0]
dChan <- dM
time.Sleep(1 * time.Second)
//
// Send shutdown message
respChan := make(chan *ctrlMsg)
request := &ctrlMsg{
id: SHUTDOWN,
respChan: respChan,
}
cChan <- request
// Wait for ACK
ack := <-respChan
if ack.id != ACK {
t.Error("failed to recieve acknowledgement indicating shutdown complete")
}
}
|
package requirements
import "fmt"
import "math"
/**
Calculate a triangle area based on Heron's formula:
Area = √p(p−a)(p−b)(p−c)
where p = (a + b + c) / 2
*/
func getTriangleArea(len1 int, len2 int, len3 int) float64 {
if !isValidTriangle(len1, len2, len3) {
panic(fmt.Sprintf("InvalidTriangleException"))
}
var p = float64(len1+len2+len3) / 2 // perimeter
var areaPower = p * (p - float64(len1)) * (p - float64(len2)) * (p - float64(len3))
return math.Sqrt(areaPower)
}
/**
Returns true if the lengths provided can make a triangle, false otherwise
*/
func isValidTriangle(len1 int, len2 int, len3 int) bool {
if len1 < 0 || len2 < 0 || len3 < 0 {
return false
}
if len1+len2 <= len3 || len1+len3 <= len2 || len3+len2 <= len1 {
return false
}
return true
}
|
package pushserver
import (
"BakatoraPushServer/src/pushserver/db"
"BakatoraPushServer/src/rabbitmq"
"BakatoraPushServer/src/util"
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-netty/go-netty"
"log"
"strconv"
"sync"
)
type Producer struct {
ServerName string
Exchange *rabbitmq.Exchange
Desc string
Events map[string]*Event
}
type PushServer struct {
prodRwMu sync.RWMutex
consRwMu sync.RWMutex
cfg Config
mq *rabbitmq.RabbitMq
prods map[string]*Producer
consumers map[string]*Consumer
logger *log.Logger
etps *EventTransportServer
ge *gin.Engine
db *db.DB
}
/************************************** public *********************************************/
/*
1. 连接amqp
2. 监听http,设置处理程序
3. 监听socket,设置处理程序
*/
func (ps *PushServer) Start(config Config) {
ps.cfg = config
ps.logger = util.CreateLogger("[PushServer] ", ps.cfg.Logfile)
ps.db = db.New(ps.cfg.DbUser, ps.cfg.DbPwd, ps.cfg.DbHost, ps.cfg.DbPort, ps.cfg.DbName)
ps.mq = rabbitmq.New(ps.cfg.MqConnId, ps.cfg.MqUser, ps.cfg.MqPwd, ps.cfg.MqHost, ps.cfg.Logfile)
etpConfig := EtpConfig{port: ps.cfg.EtpListenPort, server: ps}
ps.etps = NewEtpServer(etpConfig)
ps.etps.Start()
ps.prods = map[string]*Producer{}
ps.consumers = map[string]*Consumer{}
ps.ge = gin.Default()
SetupInnerEngine(ps)
ps.ge.Run(":" + strconv.Itoa(ps.cfg.HttpListenPort))
}
func (ps *PushServer) RegisterProducer(args *RegisterServerArgs) (res *RegisterServerRes) {
res = new(RegisterServerRes)
serverName := args.ServerName
var err error
ps.prodRwMu.Lock()
defer ps.prodRwMu.Unlock()
producer := ps.getProducer(serverName)
if producer == nil {
producer, err = ps.createProducer(serverName, args.Desc)
if err != nil {
ps.logger.Printf("Create producer failed. ServerName: %s,err: %s", serverName, err)
res.Success = false
res.Msg = err.Error()
return res
}
}
ps.setProducer(producer)
res.Success = true
return res
}
func (ps *PushServer) RegisterEvent(args *RegisterEventArgs) (res *RegisterEventRes) {
res = new(RegisterEventRes)
ps.prodRwMu.Lock()
defer ps.prodRwMu.Unlock()
event, err := ps.getEvent(args.ServerName, args.EventName)
if err != nil {
res.Success = false
res.Msg = err.Error()
return res
}
if event == nil {
event, err = ps.createEvent(args.ServerName, args.EventName, args.EventDesc, args.EventType, args.Fields)
if err != nil {
ps.logger.Printf("create event failed.ServerName EventName: %s,event EventName: %s,err: %s", args.ServerName, args.EventName, err)
res.Success = false
res.Msg = err.Error()
return res
}
ps.getProducer(args.ServerName).Events[args.EventName] = event
}
res.Success = true
res.RouterKey = event.q.Name
return res
}
func (ps *PushServer) PushEvent(args *PushEventArgs) (res * PushEventRes){
res = new(PushEventRes)
producer := ps.getProducer(args.ServerName)
if producer == nil {
res.Success = false
res.Msg = fmt.Sprintf("Get producer %s failed: producer not exist", args.ServerName)
return
}
event, err := ps.getEvent(args.ServerName, args.EventName)
if err != nil {
res.Success = false
res.Msg = fmt.Sprintf("Get event %s.%s failed: %v", args.ServerName, args.EventName, err)
return
}
entry, err := json.Marshal(args.Entry)
if err != nil {
res.Success = false
res.Msg = fmt.Sprintf("Invalid entry %s.%s failed: %v", args.ServerName, args.EventName, err)
return
}
err = ps.mq.Publish(producer.Exchange.Name, event.q.Name, string(entry), args.TTL)
if err != nil {
res.Success = false
res.Msg = fmt.Sprintf("Publish event %s.%s failed: %v", args.ServerName, args.EventName, err)
return
}
res.Success = true
return res
}
func (ps *PushServer) CancelEvent(args *CancelEventArgs) (res *CancelEventRes) {
res = new(CancelEventRes)
event, err := ps.getEvent(args.ServerName, args.EventName)
if err != nil {
res.Success = false
res.Msg = err.Error()
return
}
ps.deleteEvent(event)
event.Cancel()
res.Success = true
return res
}
func (ps *PushServer) Subscribe(args *SubscribeArgs) *SubscribeRes {
res := new(SubscribeRes)
ps.prodRwMu.RLock()
event, err := ps.getEvent(args.ServerName, args.EventName)
ps.prodRwMu.RUnlock()
if err != nil {
res.Success = false
res.Msg = fmt.Sprintf("event %s.%s not exist", args.ServerName, args.ServerName)
return res
}
ps.consRwMu.Lock()
defer ps.consRwMu.Unlock()
consumer := ps.getConsumer(args.ClientId)
if consumer == nil {
res.Success = false
res.Msg = fmt.Sprintf("client id %s not exist", args.ClientId)
return res
}
consumer.AddEvent(event)
event.AddConsumer(consumer)
res.Success = true
return res
}
func (ps *PushServer) Unsubscribe(args *UnsubscribeArgs) (res *UnsubscribeRes) {
res = new(UnsubscribeRes)
consumer := ps.getConsumer(args.ClientId)
if consumer == nil {
res.Success = false
res.Msg = fmt.Sprintf("client id %s not exist", args.ClientId)
return res
}
event, err := ps.getEvent(args.ServerName, args.EventName)
if err != nil {
res.Success = false
res.Msg = fmt.Sprintf("event %s.%s not exist", args.ServerName, args.ServerName)
return res
}
event.DeleteConsumer(consumer)
res.Success = true
return res
}
func (ps *PushServer) GetServerList(args *GetServerListArgs) (res *GetServerListRes) {
ps.prodRwMu.RLock()
defer ps.prodRwMu.RUnlock()
i := 0
res = new(GetServerListRes)
lenMap := len(ps.prods)
res.List = make([]ServerListEle, lenMap)
for k, v := range ps.prods {
res.List[i] = ServerListEle{
ServerName: k,
ServerDesc: v.Desc,
}
}
res.Count = lenMap
res.Success = true
return res
}
func (ps *PushServer) GetEventList(args *GetEventListArgs) (res *GetEventListRes) {
ps.prodRwMu.RLock()
defer ps.prodRwMu.RUnlock()
res = new(GetEventListRes)
producer := ps.getProducer(args.ServerName)
if producer == nil {
res.Msg = fmt.Sprintf("server %s not exist.", args.ServerName)
return res
}
lenMap := len(producer.Events)
res.List = make([]EventListEle, lenMap)
i := 0
for k, v := range producer.Events {
res.List[i] = EventListEle{
EventName: k,
ServerName: args.ServerName,
EventDesc: v.Desc,
EventType: v.Type,
Fields: v.Fields,
}
i++
}
res.Count = lenMap
res.Success = true
return res
}
func (ps *PushServer) ClientLogIn(args *ClientLogInArgs) (res *ClientLogInRes) {
res = new(ClientLogInRes)
client, err := ps.db.Client.FindByClientName(args.ClientName)
if err != nil {
ps.logger.Printf("find client by name %s faile: %v", args.ClientName, err)
res.Msg = err.Error()
res.Success = false
return
}
if args.ClientName == client.ClientName && args.Password == client.Password {
res.ClientId = client.ClientId
res.Success = true
} else {
res.Msg = "账号不存在或者密码错误"
res.Success = false
}
return res
}
func (ps *PushServer) ClientConn(clientId string, ctx netty.InboundContext) *Consumer {
ps.consRwMu.Lock()
defer ps.consRwMu.Unlock()
consumer := ps.getConsumer(clientId)
if consumer == nil {
consumer = ps.createConsumer(clientId, ctx)
ps.consumers[clientId] = consumer
} else {
consumer.Conn = ctx
}
return consumer
}
func (ps *PushServer) ClientDisconnect(clientId string) {
ps.consRwMu.Lock()
defer ps.consRwMu.Unlock()
delete(ps.consumers, clientId)
}
/************************************** private *********************************************/
func (ps *PushServer) createProducer(serverName, desc string) (producer *Producer, err error) {
exchangeName := ps.generateExchangeName(serverName)
ex, err := ps.mq.CreateExchange(exchangeName, "direct", false, false)
if err != nil {
return nil, err
}
producer = new(Producer)
producer.Exchange = ex
producer.Events = map[string]*Event{}
producer.ServerName = serverName
producer.Desc = desc
return producer, nil
}
func (ps *PushServer) generateExchangeName(serverName string) string {
return fmt.Sprintf("producer.%s", serverName)
}
func (ps *PushServer) getProducer(serverName string) *Producer {
return ps.prods[serverName]
}
func (ps *PushServer) setProducer(producer *Producer) {
ps.prods[producer.ServerName] = producer
}
func (ps *PushServer) getEvent(serverName, eventName string) (*Event, error) {
producer := ps.getProducer(serverName)
if producer == nil {
return nil, errors.New(fmt.Sprintf("Server %s do not exist\n", serverName))
}
return producer.Events[eventName], nil
}
func (ps *PushServer) createEvent(serverName, eventName, desc string, eventType EventType, fields []Field) (event *Event, err error) {
interQueueName := ps.generateInterQueueName(serverName, eventName)
exchangeName := ps.getProducer(serverName).Exchange.Name
//also need create queue
q, err := ps.mq.CreateQueue(interQueueName, interQueueName, exchangeName, true, false)
if err != nil {
return nil, err
} else {
event = new(Event)
event.init(serverName, eventName, desc, eventType, fields, q, ps.cfg.Logfile)
return event, err
}
}
func (ps *PushServer) deleteEvent(event *Event) {
events := &(ps.getProducer(event.ServerName).Events)
delete(*events, event.EventName)
}
func (ps *PushServer) generateInterQueueName(serverName, eventName string) string {
return fmt.Sprintf("event.%s.%s", serverName, eventName)
}
func (ps *PushServer) getConsumer(clientId string) *Consumer {
return ps.consumers[clientId]
}
func (ps *PushServer) createConsumer(clientId string, ctx netty.InboundContext) *Consumer {
consumer := new(Consumer)
consumer.ClientId = clientId
consumer.Conn = ctx
consumer.SubscribeEvents = make([]*Event, 0, 3)
consumer.Enable = true
consumer.ps = ps
return consumer
}
|
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package f16
import "unsafe"
// Number represents a 16-bit floating point number, containing a single sign bit, 5 exponent bits
// and 10 fractional bits. This corresponds to IEEE 754-2008 binary16 (or half precision float) type.
//
// MSB LSB
// ╔════╦════╤════╤════╤════╤════╦════╤════╤════╤════╤════╤════╤════╤════╤════╤════╗
// ║Sign║ E₄ │ E₃ │ E₂ │ E₁ │ E₀ ║ F₉ │ F₈ │ F₇ │ F₆ │ F₅ │ F₄ │ F₃ │ F₂ │ F₁ │ F₀ ║
// ╚════╩════╧════╧════╧════╧════╩════╧════╧════╧════╧════╧════╧════╧════╧════╧════╝
// Where E is the exponent bits and F is the fractional bits.
type Number uint16
const (
float16ExpMask Number = 0x7c00
float16ExpBias uint32 = 0xf
float16ExpShift uint32 = 10
float16FracMask Number = 0x03ff
float16SignMask Number = 0x8000
float32ExpMask uint32 = 0x7f800000
float32ExpBias uint32 = 0x7f
float32ExpShift uint32 = 23
float32FracMask uint32 = 0x007fffff
)
// Float32 returns the Number value expanded to a float32. Infinities and NaNs are expanded as
// such.
func (f Number) Float32() float32 {
u32 := expandF16ToF32(f)
ptr := unsafe.Pointer(&u32)
f32 := *(*float32)(ptr)
return f32
}
// IsNaN reports whether f is an “not-a-number” value.
func (f Number) IsNaN() bool { return (f&float16ExpMask == float16ExpMask) && (f&float16FracMask != 0) }
// IsInf reports whether f is an infinity, according to sign. If sign > 0, IsInf reports whether
// f is positive infinity. If sign < 0, IsInf reports whether f is negative infinity. If sign ==
// 0, IsInf reports whether f is either infinity.
func (f Number) IsInf(sign int) bool {
return ((f == float16ExpMask) && sign >= 0) ||
(f == (float16SignMask|float16ExpMask) && sign <= 0)
}
// NaN returns an “not-a-number” value.
func NaN() Number { return float16ExpMask | float16FracMask }
// Inf returns positive infinity if sign >= 0, negative infinity if sign < 0.
func Inf(sign int) Number {
if sign >= 0 {
return float16ExpMask
} else {
return float16SignMask | float16ExpMask
}
}
// From returns a Number encoding of a 32-bit floating point number. Infinities and NaNs
// are encoded as such. Very large and very small numbers get rounded to infinity and zero
// respectively.
func From(f32 float32) Number {
ptr := unsafe.Pointer(&f32)
u32 := *(*uint32)(ptr)
sign := Number(u32>>16) & float16SignMask
exp := (u32 & float32ExpMask) >> float32ExpShift
frac := u32 & 0x7fffff
if exp == 0xff {
// NaN or Infinity
if frac != 0 { // NaN
frac = 0x3f
}
return sign | float16ExpMask | Number(frac)
}
if exp+float16ExpBias <= float32ExpBias {
// Exponent is too small to represent in a Number (or a zero). We need to output
// denormalized numbers (possibly rounding very small numbers to zero).
denorm := float32ExpBias - exp - 1
frac += 1 << float32ExpShift
frac >>= denorm
return sign | Number(frac)
}
if exp > float32ExpBias+float16ExpBias {
// Number too large to represent in a Number => round to Infinity.
return sign | float16ExpMask
}
// General case.
return sign | Number(((exp+float16ExpBias-float32ExpBias)<<float16ExpShift)|(frac>>13))
}
func expandF16ToF32(in Number) uint32 {
sign := uint32(in&float16SignMask) << 16
frac := uint32(in&float16FracMask) << 13
exp := uint32(in&float16ExpMask) >> float16ExpShift
if exp == 0x1f {
// NaN of Infinity
return sign | float32ExpMask | frac
}
if exp == 0 {
if frac == 0 {
// Zero
return sign
}
// Denormalized number. In a float32 it must be stored in a normalized form, so
// we normalize it.
exp++
for frac&float32ExpMask == 0 {
frac <<= 1
exp--
}
frac &= float32FracMask
}
exp += (float32ExpBias - float16ExpBias)
return sign | (exp << float32ExpShift) | frac
}
|
/*
Copyright The containerd 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.
*/
// Copyright 2018 CNI 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 integration
import (
"context"
"crypto/rand"
"fmt"
"os"
"path"
"runtime"
"sync"
"syscall"
"testing"
"github.com/containerd/continuity/fs"
"github.com/containerd/continuity/testutil"
"github.com/containerd/go-cni"
"github.com/stretchr/testify/assert"
)
var (
baseNetNSDir = "/var/run/netns/"
defaultCNIPluginDir = "/opt/cni/bin/"
cniBridgePluginCfg = `
{
"cniVersion": "1.0.0",
"name": "gocni-test",
"plugins": [
{
"type":"bridge",
"bridge":"gocni-test0",
"isGateway":true,
"ipMasq":true,
"promiscMode":true,
"ipam":{
"type":"host-local",
"ranges":[
[{
"subnet":"10.88.0.0/16"
}],
[{
"subnet":"2001:4860:4860::/64"
}]
],
"routes":[
{"dst":"0.0.0.0/0"},
{"dst":"::/0"}
]
}
},
{
"type":"portmap",
"capabilities":{
"portMappings":true
}
}
]
}
`
cniBridgePluginCfgWithoutVersion = `
{
"name": "gocni-test",
"plugins": [
{
"type":"bridge",
"bridge":"gocni-test0",
"isGateway":true,
"ipMasq":true,
"promiscMode":true,
"ipam":{
"type":"host-local",
"ranges":[
[{
"subnet":"10.88.0.0/16"
}],
[{
"subnet":"2001:4860:4860::/64"
}]
],
"routes":[
{"dst":"0.0.0.0/0"},
{"dst":"::/0"}
]
}
},
{
"type":"portmap",
"capabilities":{
"portMappings":true
}
}
]
}
`
)
// TestBasicSetupAndRemove tests the cni.Setup/Remove with real bridge and
// loopback CNI plugins.
//
// NOTE:
//
// 1. It required that the both bridge and loopback CNI plugins are installed
// in /opt/cni/bin.
//
// 2. Since #76 enables parallel mode, we should enable -race option for this.
func TestBasicSetupAndRemove(t *testing.T) {
testutil.RequiresRoot(t)
// setup config dir
tmpPluginConfDir, err := os.MkdirTemp("", t.Name()+"-conf")
assert.NoError(t, err, "create temp dir for plugin conf dir")
defer os.RemoveAll(tmpPluginConfDir)
assert.NoError(t,
os.WriteFile(
path.Join(tmpPluginConfDir, "10-gocni-test-net.conflist"),
[]byte(cniBridgePluginCfg),
0600,
),
"init cni config",
)
// copy plugins from /opt/cni/bin
tmpPluginDir, err := os.MkdirTemp("", t.Name()+"-bin")
assert.NoError(t, err, "create temp dir for plugin bin dir")
defer os.RemoveAll(tmpPluginDir)
assert.NoError(t,
fs.CopyDir(tmpPluginDir, defaultCNIPluginDir),
"copy %v into %v", defaultCNIPluginDir, tmpPluginDir)
nsPath, done, err := createNetNS()
assert.NoError(t, err, "create temp netns")
defer func() {
assert.NoError(t, done(), "cleanup temp netns")
}()
defaultIfName := "eth0"
ctx := context.Background()
id := t.Name()
for idx, opts := range [][]cni.Opt{
// Use default plugin dir
{
cni.WithMinNetworkCount(2),
cni.WithPluginConfDir(tmpPluginConfDir),
},
// Use customize plugin dir
{
cni.WithMinNetworkCount(2),
cni.WithPluginConfDir(tmpPluginConfDir),
cni.WithPluginDir([]string{
tmpPluginDir,
}),
},
} {
l, err := cni.New(opts...)
assert.NoError(t, err, "[%v] initialize cni library", idx)
assert.NoError(t,
l.Load(cni.WithLoNetwork, cni.WithDefaultConf),
"[%v] load cni configuration", idx,
)
// Setup network
result, err := l.Setup(ctx, id, nsPath)
assert.NoError(t, err, "[%v] setup network interfaces for namespace in parallel %v", idx, nsPath)
ip := result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
t.Logf("[%v] ip is %v", idx, ip)
assert.NoError(t,
l.Remove(ctx, id, nsPath),
"[%v] teardown network interfaces for namespace %v", idx, nsPath,
)
// Setup network serially
result, err = l.SetupSerially(ctx, id, nsPath)
assert.NoError(t, err, "[%v] setup network interfaces for namespace serially%v", idx, nsPath)
ip = result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
t.Logf("[%v] ip is %v", idx, ip)
assert.NoError(t,
l.Remove(ctx, id, nsPath),
"[%v] teardown network interfaces for namespace %v", idx, nsPath,
)
}
}
func TestBasicSetupAndRemovePluginWithoutVersion(t *testing.T) {
testutil.RequiresRoot(t)
// setup config dir
tmpPluginConfDir, err := os.MkdirTemp("", t.Name()+"-conf")
assert.NoError(t, err, "create temp dir for plugin conf dir")
defer os.RemoveAll(tmpPluginConfDir)
assert.NoError(t,
os.WriteFile(
path.Join(tmpPluginConfDir, "10-gocni-test-net.conflist"),
[]byte(cniBridgePluginCfgWithoutVersion),
0600,
),
"init cni config",
)
// copy plugins from /opt/cni/bin
tmpPluginDir, err := os.MkdirTemp("", t.Name()+"-bin")
assert.NoError(t, err, "create temp dir for plugin bin dir")
defer os.RemoveAll(tmpPluginDir)
assert.NoError(t,
fs.CopyDir(tmpPluginDir, defaultCNIPluginDir),
"copy %v into %v", defaultCNIPluginDir, tmpPluginDir)
nsPath, done, err := createNetNS()
assert.NoError(t, err, "create temp netns")
defer func() {
assert.NoError(t, done(), "cleanup temp netns")
}()
defaultIfName := "eth0"
ctx := context.Background()
id := t.Name()
for idx, opts := range [][]cni.Opt{
// Use default plugin dir
{
cni.WithMinNetworkCount(2),
cni.WithPluginConfDir(tmpPluginConfDir),
},
// Use customize plugin dir
{
cni.WithMinNetworkCount(2),
cni.WithPluginConfDir(tmpPluginConfDir),
cni.WithPluginDir([]string{
tmpPluginDir,
}),
},
} {
l, err := cni.New(opts...)
assert.NoError(t, err, "[%v] initialize cni library", idx)
assert.NoError(t,
l.Load(cni.WithLoNetwork, cni.WithDefaultConf),
"[%v] load cni configuration", idx,
)
// Setup network
result, err := l.Setup(ctx, id, nsPath)
assert.NoError(t, err, "[%v] setup network interfaces for namespace in parallel %v", idx, nsPath)
ip := result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
t.Logf("[%v] ip is %v", idx, ip)
assert.NoError(t,
l.Remove(ctx, id, nsPath),
"[%v] teardown network interfaces for namespace %v", idx, nsPath,
)
// Setup network serially
result, err = l.SetupSerially(ctx, id, nsPath)
assert.NoError(t, err, "[%v] setup network interfaces for namespace serially%v", idx, nsPath)
ip = result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
t.Logf("[%v] ip is %v", idx, ip)
assert.NoError(t,
l.Remove(ctx, id, nsPath),
"[%v] teardown network interfaces for namespace %v", idx, nsPath,
)
}
}
// createNetNS returns temp netns path.
//
// NOTE: It is based on https://github.com/containernetworking/plugins/blob/v1.0.1/pkg/testutils/netns_linux.go.
// That can prevent from introducing unnessary dependencies in go.mod.
func createNetNS() (_ string, _ func() error, retErr error) {
b := make([]byte, 16)
if _, err := rand.Reader.Read(b); err != nil {
return "", nil, fmt.Errorf("failed to generate random netns name: %w", err)
}
// Create the directory for mounting network namespaces
// This needs to be a shared mountpoint in case it is mounted in to
// other namespaces (containers)
if err := os.MkdirAll(baseNetNSDir, 0755); err != nil {
return "", nil, fmt.Errorf("failed to init base netns dir %s: %v", baseNetNSDir, err)
}
// create an empty file at the mount point
nsName := fmt.Sprintf("gocni-test-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
nsPath := path.Join(baseNetNSDir, nsName)
mountPointFd, err := os.Create(nsPath)
if err != nil {
return "", nil, fmt.Errorf("failed to create temp nspath %s: %v", nsPath, err)
}
mountPointFd.Close()
defer func() {
if retErr != nil {
_ = os.RemoveAll(nsPath)
}
}()
var wg sync.WaitGroup
wg.Add(1)
// do namespace work in a dedicated goroutine, so that we can safely
// Lock/Unlock OSThread without upsetting the lock/unlock state of
// the caller of this function
go (func() {
defer wg.Done()
// Don't unlock. By not unlocking, golang will kill the OS thread
// when the goroutine is done (>= go1.10). Since <= go1.10 has
// been deprecated, we don't need to get current net ns and
// reset.
runtime.LockOSThread()
// create a new netns on the current thread
if err = syscall.Unshare(syscall.CLONE_NEWNET); err != nil {
return
}
// bind mount the netns from the current thread (from /proc) onto the
// mount point. This causes the namespace to persist, even when there
// are no threads in the ns.
err = syscall.Mount(getCurrentThreadNetNSPath(), nsPath, "none", syscall.MS_BIND, "")
if err != nil {
err = fmt.Errorf("failed to bind mount ns at %s: %w", nsPath, err)
}
})()
wg.Wait()
if err != nil {
return "", nil, fmt.Errorf("failed to create net namespace: %w", err)
}
return nsPath, func() error {
if err := syscall.Unmount(nsPath, 0); err != nil {
return fmt.Errorf("failed to unmount netns: at %s: %v", nsPath, err)
}
if err := os.Remove(nsPath); err != nil {
return fmt.Errorf("failed to remove nspath %s: %v", nsPath, err)
}
return nil
}, nil
}
// getCurrentThreadNetNSPath copied from pkg/ns
//
// NOTE: It is from https://github.com/containernetworking/plugins/blob/v1.0.1/pkg/testutils/netns_linux.go.
func getCurrentThreadNetNSPath() string {
// /proc/self/ns/net returns the namespace of the main thread, not
// of whatever thread this goroutine is running on. Make sure we
// use the thread's net namespace since the thread is switching around
return fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), syscall.Gettid())
}
|
package services
import (
"fmt"
"net"
"net/http"
"net/http/pprof"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
type Pprof struct {
host string
port int
ln net.Listener
}
const (
pprofHostFlag = "pprof-host"
pprofPortFlag = "pprof-port"
)
func RegisterPprofFlags(f []cli.Flag) []cli.Flag {
return append(f,
cli.StringFlag{
Name: pprofHostFlag,
Usage: "pprof listening host",
Value: "",
},
cli.IntFlag{
Name: pprofPortFlag,
Usage: "pprof listening port",
Value: 8082,
},
)
}
func NewPprof(c *cli.Context) *Pprof {
return &Pprof{host: c.String(pprofHostFlag), port: c.Int(pprofPortFlag)}
}
func (s *Pprof) Serve() error {
addr := fmt.Sprintf("%s:%d", s.host, s.port)
ln, err := net.Listen("tcp", addr)
if err != nil {
return errors.Wrap(err, "failed to probe listen to tcp connection")
}
mux := http.NewServeMux()
mux.HandleFunc("/", pprof.Index)
mux.HandleFunc("/cmdline", pprof.Cmdline)
mux.HandleFunc("/profile", pprof.Profile)
mux.HandleFunc("/symbol", pprof.Symbol)
mux.HandleFunc("/trace", pprof.Trace)
mux.Handle("/goroutine", pprof.Handler("goroutine"))
mux.Handle("/heap", pprof.Handler("heap"))
mux.Handle("/threadcreate", pprof.Handler("threadcreate"))
mux.Handle("/block", pprof.Handler("block"))
log.Infof("serving pprof at %v", addr)
return http.Serve(ln, mux)
}
func (s *Pprof) Close() {
if s.ln != nil {
s.ln.Close()
}
}
|
package main
import (
"fmt"
)
func countBits(num int) []int {
res := make([]int, num+1)
for i := 1; i <= num; i = i + 1 {
if i&1 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[i/2] + 1
}
}
return res
}
func main() {
input := 5
fmt.Println(countBits(input))
}
|
package orchestra
import (
//"fmt"
"github.com/aws/aws-sdk-go/aws/session"
)
func CreateSession() (*session.Session, error) {
sess, err := session.NewSession()
if err != nil {
return nil, err
}
if _, err := sess.Config.Credentials.Get(); err != nil {
return nil, err
}
return sess, nil
}
|
package symlink
import "os"
// Replace will replace existing symlink
func Replace(filePath string, symlinkPath string) error {
return replaceSymlink(filePath, symlinkPath)
}
// Delete will remove symlink
func Delete(symlinkPath string) error {
return deleteSymlink(symlinkPath)
}
// Exists check symlink is exists or not
func Exists(symlinkPath string) bool {
return existsSymlink(symlinkPath)
}
// Create will create new symlink
func Create(filePath string, symlinkPath string) error {
return createSymlink(filePath, symlinkPath)
}
func replaceSymlink(filePath string, symlinkPath string) error {
deleteSymlink(symlinkPath)
return createSymlink(filePath, symlinkPath)
}
func deleteSymlink(symlinkPath string) error {
if existsSymlink(symlinkPath) {
return os.Remove(symlinkPath)
}
return nil
}
func existsSymlink(symlinkPath string) bool {
info, err := os.Lstat(symlinkPath)
if err != nil {
return false
}
return info.Mode()&os.ModeSymlink == os.ModeSymlink
}
func createSymlink(filePath string, symlinkPath string) error {
err := os.Symlink(filePath, symlinkPath)
return err
}
|
package ranges
import "github.com/adamluzsi/frameless/ports/iterators"
func Int(begin, end int) iterators.Iterator[int] {
return &intRange{Begin: begin, End: end}
}
type intRange struct {
Begin, End int
nextIndex int
closed bool
}
func (ir *intRange) Close() error {
ir.closed = true
return nil
}
func (ir *intRange) Err() error {
return nil
}
func (ir *intRange) Next() bool {
if ir.closed {
return false
}
if ir.End < ir.Begin+ir.nextIndex {
return false
}
ir.nextIndex++
return true
}
func (ir *intRange) Value() int {
return ir.Begin + ir.nextIndex - 1
}
|
package main
import (
"flag"
"fmt"
"io"
"net/http"
"sync"
"time"
)
var sess_cookie http.Cookie
var resp string
type ConnectionCount struct {
mu sync.Mutex
cur_conn int
max_conn int
total_conn int
}
var scoreboard ConnectionCount
func (cc *ConnectionCount) open() {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.cur_conn++
cc.total_conn++
}
func (cc *ConnectionCount) close() {
cc.mu.Lock()
defer cc.mu.Unlock()
if cc.cur_conn > cc.max_conn {
cc.max_conn = cc.cur_conn
}
cc.cur_conn--
}
func (cc *ConnectionCount) stats() (int, int) {
cc.mu.Lock()
defer cc.mu.Unlock()
return cc.max_conn, cc.total_conn
}
func (cc *ConnectionCount) reset() {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.max_conn = 0
cc.total_conn = 0
}
func root_handler(w http.ResponseWriter, r *http.Request) {
scoreboard.open()
defer scoreboard.close()
http.SetCookie(w, &sess_cookie)
io.WriteString(w, resp)
}
func slow_handler(w http.ResponseWriter, r *http.Request) {
scoreboard.open()
defer scoreboard.close()
delay, err := time.ParseDuration(r.URL.Query().Get("delay"))
if err != nil {
delay = 3 * time.Second
}
time.Sleep(delay)
http.SetCookie(w, &sess_cookie)
io.WriteString(w, resp)
}
func stats_handler(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &sess_cookie)
max_conn, total_conn := scoreboard.stats()
fmt.Fprintf(w, "max_conn=%d\ntotal_conn=%d\n", max_conn, total_conn)
}
func reset_handler(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &sess_cookie)
scoreboard.reset()
fmt.Fprintf(w, "reset\n")
}
func main() {
portPtr := flag.Int("port", 8080, "TCP port to listen on")
idPtr := flag.String("id", "1", "Server ID")
flag.Parse()
resp = fmt.Sprintf("%s", *idPtr)
sess_cookie.Name = "JSESSIONID"
sess_cookie.Value = *idPtr
http.HandleFunc("/", root_handler)
http.HandleFunc("/slow", slow_handler)
http.HandleFunc("/stats", stats_handler)
http.HandleFunc("/reset", reset_handler)
portStr := fmt.Sprintf(":%d", *portPtr)
http.ListenAndServe(portStr, nil)
}
|
package sa
import "github.com/jinzhu/gorm"
type (
Shop struct {
Shop_Id int `json:"shop_id"`
Address_id int `json:"address_id"`
Size int `json:"size"`
Workers int `json:"workers"`
}
Address struct {
gorm.Model
City string `json:"city"`
Street string `json:"street"`
Number string `json:"number"`
}
)
|
package main
import (
"sync"
"errors"
pb "../protobuf/go"
"container/list"
"github.com/op/go-logging"
)
type AccountState struct {
lock sync.RWMutex
data map[string]int32
}
func (self *AccountState) add(key string, value int32) (int32, error) {
self.lock.Lock()
defer self.lock.Unlock()
return self.add_nosync(key, value)
}
func (self *AccountState) add_nosync(key string, value int32) (int32, error) {
_, success := self.data[key]
if !success {
self.data[key] = initBalance
}
if self.data[key]+value >= 0 {
self.data[key] += value
return self.data[key], nil
} else {
return 0, errors.New("Not enough money")
}
}
func (self *AccountState) check_nosync(key string) int32 {
value, success := self.data[key]
if !success {
return initBalance
} else {
return value
}
}
func (self *AccountState) afford_nosync(key string, value int32) bool {
_, success := self.data[key]
if !success {
return initBalance >= value
} else {
return self.data[key] >= value
}
}
func (self *AccountState) filterTxArray(input []*pb.Transaction, limit int, log *logging.Logger) []*pb.Transaction {
self.lock.RLock()
tmpdata := AccountState{
data: make(map[string]int32),
}
selfplag := make(map[string]bool)
for key, value := range self.data {
tmpdata.data[key] = value
}
self.lock.RUnlock()
answer := make([]*pb.Transaction,0, int(limit/8))
for _, tx := range input {
//log.Debugf("From: %s, Value: %d, tx value: %d", tx.FromID, tmpdata.data[tx.FromID], tx.Value)
if _, suc := selfplag[tx.UUID]; tmpdata.afford_nosync(tx.FromID, tx.Value) && !suc{
//log.Debug("So, append")
selfplag[tx.UUID] = true
answer = append(answer, tx)
if len(answer) == limit {
return answer
}
tmpdata.add_nosync(tx.FromID, -tx.Value)
tmpdata.add_nosync(tx.ToID, tx.Value - tx.MiningFee)
}
}
//log.Debug(len(answer))
return answer
}
func (self *AccountState) filterPendingTx() {
self.lock.RLock()
tmpdata := AccountState{
data: make(map[string]int32),
}
for key, value := range self.data {
tmpdata.data[key] = value
}
self.lock.RUnlock()
var nextE *list.Element
for e := pendingTxs.data.Front(); e != nil ; e = nextE {
nextE = e.Next()
tx , success := e.Value.(*pb.Transaction)
if !success {
panic("you code has bug")
}
if tmpdata.afford_nosync(tx.FromID, tx.Value){
tmpdata.add_nosync(tx.FromID, -tx.Value)
tmpdata.add_nosync(tx.ToID, tx.Value - tx.MiningFee)
} else {
pendingTxs.data.Remove(e)
delete(pendingTxs.uuidmap, tx.UUID)
}
}
} |
package config
import (
"github.com/kelseyhightower/envconfig"
"go.uber.org/zap"
)
// Config - server configuration structure
type Config struct {
Env string `envconfig:"ENV" default:"development"`
Port int `envconfig:"PORT" default:"8080"`
DBHost string `envconfig:"DB_HOST"`
DBPort int `envconfig:"DB_PORT"`
DBName string `envconfig:"DB_NAME"`
DBUser string `envconfig:"DB_USER"`
DBPass string `envconfig:"DB_PASS"`
}
type serviceCfg struct {
}
// New - Get server configurations
func New() *Config {
var cfg Config
// Process config.
err := envconfig.Process("", &cfg)
if err != nil {
zap.S().Fatalf("Error decoding environment variables: %v", err)
return nil
}
return &cfg
}
|
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package jdbg provides a simpler interface to the jdwp package, offering
// simple type resolving and method invoking functions.
package jdbg
import (
"fmt"
"strings"
"github.com/google/gapid/core/java/jdwp"
)
type cache struct {
arrays map[string]*Array
classes map[string]*Class
idToSig map[jdwp.ReferenceTypeID]string
objTy *Class
stringTy *Class
numberTy *Class
boolObjTy *Class
byteObjTy *Class
charObjTy *Class
shortObjTy *Class
intObjTy *Class
longObjTy *Class
floatObjTy *Class
doubleObjTy *Class
boolTy *Simple
byteTy *Simple
charTy *Simple
shortTy *Simple
intTy *Simple
longTy *Simple
floatTy *Simple
doubleTy *Simple
voidTy *Simple
}
// JDbg is a wrapper around a JDWP connection that provides an easier interface
// for usage.
type JDbg struct {
conn *jdwp.Connection
thread jdwp.ThreadID
cache cache
objects []jdwp.ObjectID // Objects created that have GC disabled
}
// Do calls f with a JDbg instance, returning the error returned by f.
// If any JDWP errors are raised during the call to f, then execution of f is
// immediately terminated, and the JDWP error is returned.
func Do(conn *jdwp.Connection, thread jdwp.ThreadID, f func(jdbg *JDbg) error) error {
j := &JDbg{
conn: conn,
thread: thread,
cache: cache{
arrays: map[string]*Array{},
classes: map[string]*Class{},
idToSig: map[jdwp.ReferenceTypeID]string{},
},
}
defer func() {
// Reenable GC for all objects used during the call to f()
for _, o := range j.objects {
conn.EnableGC(o)
}
}()
return Try(func() error {
// Prime the cache with basic types.
j.cache.voidTy = &Simple{j: j, ty: jdwp.TagVoid}
j.cache.boolTy = &Simple{j: j, ty: jdwp.TagBoolean}
j.cache.byteTy = &Simple{j: j, ty: jdwp.TagByte}
j.cache.charTy = &Simple{j: j, ty: jdwp.TagChar}
j.cache.shortTy = &Simple{j: j, ty: jdwp.TagShort}
j.cache.intTy = &Simple{j: j, ty: jdwp.TagInt}
j.cache.longTy = &Simple{j: j, ty: jdwp.TagLong}
j.cache.floatTy = &Simple{j: j, ty: jdwp.TagFloat}
j.cache.doubleTy = &Simple{j: j, ty: jdwp.TagDouble}
j.cache.objTy = j.Class("java.lang.Object")
j.cache.stringTy = j.Class("java.lang.String")
j.cache.numberTy = j.Class("java.lang.Number")
j.cache.boolObjTy = j.Class("java.lang.Boolean")
j.cache.byteObjTy = j.Class("java.lang.Byte")
j.cache.charObjTy = j.Class("java.lang.Character")
j.cache.shortObjTy = j.Class("java.lang.Short")
j.cache.intObjTy = j.Class("java.lang.Integer")
j.cache.longObjTy = j.Class("java.lang.Long")
j.cache.floatObjTy = j.Class("java.lang.Float")
j.cache.doubleObjTy = j.Class("java.lang.Double")
// Call f
return f(j)
})
}
// Connection returns the JDWP connection.
func (j *JDbg) Connection() *jdwp.Connection { return j.conn }
// ObjectType returns the Java java.lang.Object type.
func (j *JDbg) ObjectType() *Class { return j.cache.objTy }
// StringType returns the Java java.lang.String type.
func (j *JDbg) StringType() *Class { return j.cache.stringTy }
// NumberType returns the Java java.lang.Number type.
func (j *JDbg) NumberType() *Class { return j.cache.numberTy }
// BoolObjectType returns the Java java.lang.Boolean type.
func (j *JDbg) BoolObjectType() *Class { return j.cache.boolObjTy }
// ByteObjectType returns the Java java.lang.Byte type.
func (j *JDbg) ByteObjectType() *Class { return j.cache.byteObjTy }
// CharObjectType returns the Java java.lang.Character type.
func (j *JDbg) CharObjectType() *Class { return j.cache.charObjTy }
// ShortObjectType returns the Java java.lang.Short type.
func (j *JDbg) ShortObjectType() *Class { return j.cache.shortObjTy }
// IntObjectType returns the Java java.lang.Integer type.
func (j *JDbg) IntObjectType() *Class { return j.cache.intObjTy }
// LongObjectType returns the Java java.lang.Long type.
func (j *JDbg) LongObjectType() *Class { return j.cache.longObjTy }
// FloatObjectType returns the Java java.lang.Float type.
func (j *JDbg) FloatObjectType() *Class { return j.cache.floatObjTy }
// DoubleObjectType returns the Java java.lang.Double type.
func (j *JDbg) DoubleObjectType() *Class { return j.cache.doubleObjTy }
// BoolType returns the Java java.lang.Boolean type.
func (j *JDbg) BoolType() *Simple { return j.cache.boolTy }
// ByteType returns the Java byte type.
func (j *JDbg) ByteType() *Simple { return j.cache.byteTy }
// CharType returns the Java char type.
func (j *JDbg) CharType() *Simple { return j.cache.charTy }
// ShortType returns the Java short type.
func (j *JDbg) ShortType() *Simple { return j.cache.shortTy }
// IntType returns the Java int type.
func (j *JDbg) IntType() *Simple { return j.cache.intTy }
// LongType returns the Java long type.
func (j *JDbg) LongType() *Simple { return j.cache.longTy }
// FloatType returns the Java float type.
func (j *JDbg) FloatType() *Simple { return j.cache.floatTy }
// DoubleType returns the Java double type.
func (j *JDbg) DoubleType() *Simple { return j.cache.doubleTy }
// Type looks up the specified type by signature.
// For example: "Ljava/io/File;"
func (j *JDbg) Type(sig string) Type {
offset := 0
ty, err := j.parseSignature(sig, &offset)
if err != nil {
j.fail("Failed to parse signature: %v", err)
}
return ty
}
// Class looks up the specified class by name.
// For example: "java.io.File"
func (j *JDbg) Class(name string) *Class {
ty := j.Type(fmt.Sprintf("L%s;", strings.Replace(name, ".", "/", -1)))
if class, ok := ty.(*Class); ok {
return class
}
j.fail("Resolved type was not array but %T", ty)
return nil
}
// AllClasses returns all the loaded classes.
func (j *JDbg) AllClasses() []*Class {
classes, err := j.conn.GetAllClasses()
if err != nil {
j.fail("Couldn't get all classes: %v", err)
}
out := []*Class{}
for _, class := range classes {
c, err := j.class(class)
if err != nil {
j.fail("Couldn't get class '%v': %v", class.Signature, err)
}
out = append(out, c)
}
return out
}
// ArrayOf returns the type of the array with specified element type.
func (j *JDbg) ArrayOf(elTy Type) *Array {
ty := j.Type("[" + elTy.Signature())
if array, ok := ty.(*Array); ok {
return array
}
j.fail("Resolved type was not array but %T", ty)
return nil
}
// classFromSig looks up the specified class type by signature.
func (j *JDbg) classFromSig(sig string) (*Class, error) {
if class, ok := j.cache.classes[sig]; ok {
return class, nil
}
class, err := j.conn.GetClassBySignature(sig)
if err != nil {
return nil, err
}
return j.class(class)
}
func (j *JDbg) class(class jdwp.ClassInfo) (*Class, error) {
sig := class.Signature
if cached, ok := j.cache.classes[class.Signature]; ok {
return cached, nil
}
name := strings.Replace(strings.TrimRight(strings.TrimLeft(sig, "[L"), ";"), "/", ".", -1)
ty := &Class{j: j, signature: sig, name: name, class: class}
j.cache.classes[sig] = ty
j.cache.idToSig[class.TypeID] = sig
superid, err := j.conn.GetSuperClass(class.ClassID())
if err != nil {
return nil, err
}
if superid != 0 {
ty.super = j.typeFromID(jdwp.ReferenceTypeID(superid)).(*Class)
}
implementsids, err := j.conn.GetImplemented(class.TypeID)
if err != nil {
return nil, err
}
ty.implements = make([]*Class, len(implementsids))
for i, id := range implementsids {
ty.implements[i] = j.typeFromID(jdwp.ReferenceTypeID(id)).(*Class)
}
ty.fields, err = j.conn.GetFields(class.TypeID)
if err != nil {
return nil, err
}
return ty, nil
}
func (j *JDbg) typeFromID(id jdwp.ReferenceTypeID) Type {
sig, ok := j.cache.idToSig[id]
if !ok {
var err error
sig, err = j.conn.GetTypeSignature(id)
if err != nil {
j.fail("GetTypeSignature() returned: %v", err)
}
j.cache.idToSig[id] = sig
}
return j.Type(sig)
}
// This returns the this object for the current stack frame.
func (j *JDbg) This() Value {
frames, err := j.conn.GetFrames(j.thread, 0, 1)
if err != nil {
j.fail("GetFrames() returned: %v", err)
}
this, err := j.conn.GetThisObject(j.thread, frames[0].Frame)
if err != nil {
j.fail("GetThisObject() returned: %v", err)
}
return j.object(this.Object)
}
func (j *JDbg) String(val string) Value {
str, err := j.conn.CreateString(val)
if err != nil {
j.fail("CreateString() returned: %v", err)
}
return j.object(str)
}
// findArg finds the argument with the given name/index in the given frame
func (j *JDbg) findArg(name string, index int, frame jdwp.FrameInfo) jdwp.VariableRequest {
table, err := j.conn.VariableTable(
jdwp.ReferenceTypeID(frame.Location.Class),
frame.Location.Method)
if err != nil {
j.fail("VariableTable returned: %v", err)
}
variable := jdwp.VariableRequest{-1, 0}
for _, slot := range table.Slots {
if name == slot.Name {
variable.Index = slot.Slot
variable.Tag = slot.Signature[0]
}
}
if variable.Index != -1 {
return variable
}
// Fallback to looking for the argument by index.
slots := table.ArgumentSlots()
// Find the "this" argument. It is always labeled and the first argument slot.
thisSlot := -1
for i, slot := range slots {
if slot.Name == "this" {
thisSlot = i
break
}
}
if thisSlot < 0 {
j.fail("Could not find argument with name %s (no 'this' found)", name)
}
if thisSlot+1+index >= len(slots) {
j.fail("Could not find argument with name %s (not enough slots)", name)
}
variable.Index = slots[thisSlot+1+index].Slot
variable.Tag = slots[thisSlot+1+index].Signature[0]
return variable
}
// GetArgument returns the method argument of the given name and index. First,
// this attempts to retrieve the argument by name, but falls back to looking for
// the argument by index (e.g. in the case the names have been stripped from the
// debug info).
func (j *JDbg) GetArgument(name string, index int) Variable {
frames, err := j.conn.GetFrames(j.thread, 0, 1)
if err != nil {
j.fail("GetFrames() returned: %v", err)
}
variable := j.findArg(name, index, frames[0])
values, err := j.conn.GetValues(j.thread, frames[0].Frame, []jdwp.VariableRequest{variable})
if err != nil {
j.fail("GetValues() returned: %v", err)
}
return Variable{j.value(values[0]), variable}
}
// SetVariable sets the value of the given variable.
func (j *JDbg) SetVariable(variable Variable, val Value) {
frames, err := j.conn.GetFrames(j.thread, 0, 1)
if err != nil {
j.fail("GetFrames() returned: %v", err)
}
v := val.val.(jdwp.Value)
assign := jdwp.VariableAssignmentRequest{variable.variable.Index, v}
err = j.conn.SetValues(j.thread, frames[0].Frame, []jdwp.VariableAssignmentRequest{assign})
if err != nil {
j.fail("GetValues() returned: %v", err)
}
}
func (j *JDbg) object(id jdwp.Object) Value {
tyID, err := j.conn.GetObjectType(id.ID())
if err != nil {
j.fail("GetObjectType() returned: %v", err)
}
ty := j.typeFromID(tyID.Type)
return newValue(ty, id)
}
func (j *JDbg) value(o interface{}) Value {
switch v := o.(type) {
case jdwp.Object:
return j.object(v)
default:
j.fail("Unhandled variable type %T", o)
return Value{}
}
}
|
package inventory
import (
"github.com/astaxie/beego/orm"
)
// ProductCategories holds information about erp products
type ProductCategories struct {
// Common fields
ID int `orm:"auto;column(ID)"`
Title string `orm:"size(100);column(Title)"`
}
// TableName specifies actual name of table in database
func (a *ProductCategories) TableName() string {
return "category"
}
//
func GetCategories() []ProductCategories {
o := orm.NewOrm()
p := new(ProductCategories)
qs := o.QueryTable(p)
var categories []ProductCategories
qs.All(&categories)
return categories
}
|
// Copyright 2018 cloudy itcloudy@qq.com. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package tools
import (
"fmt"
"github.com/pkg/errors"
"github.com/spf13/viper"
"os"
"os/exec"
"strconv"
"strings"
)
// IntToStr converts integer to string
func IntToStr(num int) string {
return strconv.Itoa(num)
}
// StrToInt64 converts string to int64
func StrToInt64(s string) int64 {
int64, _ := strconv.ParseInt(s, 10, 64)
return int64
}
// BytesToInt64 converts []bytes to int64
func BytesToInt64(s []byte) int64 {
int64, _ := strconv.ParseInt(string(s), 10, 64)
return int64
}
// StrToUint64 converts string to the unsinged int64
func StrToUint64(s string) uint64 {
ret, _ := strconv.ParseUint(s, 10, 64)
return ret
}
// Float64ToStr converts float64 to string
func Float64ToStr(f float64, prec ...string) string {
return strconv.FormatFloat(f, 'f', 13, 64)
}
// StrToInt converts string to integer
func StrToInt(s string) int {
i, _ := strconv.Atoi(s)
return i
}
func StringToIntDefault(str string, defVal int) int {
if in, err := strconv.Atoi(str); err != nil {
return defVal
} else {
return in
}
}
// StrToFloat64 converts string to float64
func StrToFloat64(s string) float64 {
Float64, _ := strconv.ParseFloat(s, 64)
return Float64
}
// BytesToFloat64 converts []byte to float64
func BytesToFloat64(s []byte) float64 {
Float64, _ := strconv.ParseFloat(string(s), 64)
return Float64
}
// BytesToInt converts []byte to integer
func BytesToInt(s []byte) int {
i, _ := strconv.Atoi(string(s))
return i
}
func StrToBool(s string) bool {
if s == "0" || s == "false" {
return false
}
return true
}
//SnakeString 蛇形转换 string, XxYy to xx_yy
func SnakeString(s string) string {
data := make([]byte, 0, len(s)*2)
j := false
num := len(s)
for i := 0; i < num; i++ {
d := s[i]
if i > 0 && d >= 'A' && d <= 'Z' && j {
data = append(data, '_')
}
if d != '_' {
j = true
}
data = append(data, d)
}
return strings.ToLower(string(data[:]))
}
//CamelString 驼峰转换 string , xx_yy to XxYy
func CamelString(s string) string {
data := make([]byte, 0, len(s))
j := false
k := false
num := len(s) - 1
for i := 0; i <= num; i++ {
d := s[i]
if !k && d >= 'A' && d <= 'Z' {
k = true
}
if d >= 'a' && d <= 'z' && (j || !k) {
d = d - 32
j = false
k = true
}
if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
j = true
continue
}
data = append(data, d)
}
return string(data[:])
}
// camelCase 驼峰转换 string,converts a _ delimited string to camel case
// e.g. very_important_person => VeryImportantPerson
func CamelCase(in string) string {
tokens := strings.Split(in, "_")
for i := range tokens {
tokens[i] = strings.Title(strings.Trim(tokens[i], " "))
}
return strings.Join(tokens, "")
}
// formatSourceCode formats source files
func FormatSourceCode(filename string) {
cmd := exec.Command("gofmt", "-w", filename)
cmd.Run()
}
// TypeInt 断言获取int或int64为int,其他类型为0
func TypeInt(num interface{}) int {
n32, ok := num.(int)
if !ok {
n64, ok := num.(int64)
if ok {
n32 = int(n64)
} else {
n32 = 0
}
}
return n32
}
// TypeInt64 断言获取int或int64为int64,其他类型为0
func TypeInt64(num interface{}) int64 {
n64, ok := num.(int64)
if !ok {
n32, ok := num.(int)
if ok {
n64 = int64(n32)
} else {
n64 = int64(0)
}
}
return n64
}
// Capitalize 字符首字母大写
func Capitalize(str string) string {
var upperStr string
vv := []rune(str) // 后文有介绍
for i := 0; i < len(vv); i++ {
if i == 0 {
if vv[i] >= 97 && vv[i] <= 122 { // 后文有介绍
vv[i] -= 32 // string的码表相差32位
upperStr += string(vv[i])
} else {
fmt.Println("Not begins with lowercase letter,")
return str
}
} else {
upperStr += string(vv[i])
}
}
return upperStr
}
// GetConfigFromPath read config from path and returns struct
func GetConfigFromPath(path string, vs interface{}) (err error) {
//log.WithFields(log.Fields{"path": path}).Info("Loading config")
_, err = os.Stat(path)
if os.IsNotExist(err) {
return errors.Errorf("Unable to load config file %s", path)
}
viper.SetConfigFile(path)
err = viper.ReadInConfig()
if err != nil {
return errors.Wrapf(err, "reading config")
}
//c := new(interface{})
err = viper.Unmarshal(vs)
if err != nil {
err = errors.Wrapf(err, "marshalling config to global struct variable")
}
return
}
|
// +build integration
package repository_test
import (
"context"
"fmt"
"io/ioutil"
"testing"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2"
"github.com/darren-west/app/user-service/models"
"github.com/darren-west/app/user-service/repository/testutils/container"
"github.com/darren-west/app/user-service/repository"
"github.com/stretchr/testify/suite"
)
func TestRepositorySuite(t *testing.T) {
suite.Run(t, &RepositorySuite{})
}
type RepositorySuite struct {
suite.Suite
repo repository.MongoUserRepository
manager *container.Manager
session *mgo.Session
}
func (rs *RepositorySuite) SetupTest() {
manager, err := container.NewManager(
container.WithPortMapping(container.PortMapping{}.With("27017/tcp", "27017/tcp")),
container.WithImage("mongo:latest"),
container.WithWriter(ioutil.Discard),
)
rs.Require().NoError(err)
rs.manager = manager
rs.Require().NoError(rs.manager.Start(context.Background()))
repo, err := repository.NewMongoUserRepository(
repository.WithConnectionString("mongodb://127.0.0.1:27017"),
repository.WithDatabaseName("test"),
repository.WithCollectionName("users"),
)
rs.Require().NoError(err)
rs.repo = repo
rs.session, err = mgo.Dial("mongodb://127.0.0.1:27017")
rs.Require().NoError(err)
}
func (rs *RepositorySuite) TearDownTest() {
rs.session.Close()
rs.Require().NoError(rs.manager.Stop(context.Background()))
}
func (rs *RepositorySuite) TestFindUser() {
expectedUser := models.UserInfo{ID: "1234", FirstName: "foo", LastName: "bar", Email: "foo@email.com"}
rs.collection().Insert(&expectedUser)
user, err := rs.repo.FindUser(repository.NewMatcher().WithID("1234"))
rs.Require().NoError(err)
rs.Assert().Equal(expectedUser, user)
}
func (rs *RepositorySuite) TestFindUserNotFound() {
user, err := rs.repo.FindUser(repository.NewMatcher().WithID("1234"))
rs.Assert().True(repository.IsErrUserNotFound(err))
rs.Assert().Zero(user)
}
func (rs *RepositorySuite) collection() *mgo.Collection {
return rs.session.DB(rs.repo.Options().DatabaseName).C(rs.repo.Options().CollectionName)
}
func (rs *RepositorySuite) TestCreateUser() {
expectedUser := models.UserInfo{ID: "123", FirstName: "foo", LastName: "bar", Email: "foo@email.com"}
rs.Require().NoError(rs.repo.CreateUser(expectedUser))
user := models.UserInfo{}
rs.Require().NoError(rs.collection().Find(bson.M{"id": "123"}).One(&user))
rs.Assert().Equal(expectedUser, user)
}
func (rs *RepositorySuite) TestRemoveUser() {
expectedUser := models.UserInfo{ID: "1234", FirstName: "foo", LastName: "bar", Email: "foo@email.com"}
rs.Require().NoError(rs.collection().Insert(&expectedUser))
rs.Require().NoError(rs.repo.RemoveUser(repository.NewMatcher().WithID("1234")))
count, err := rs.collection().Find(bson.M{"id": "1234"}).Count()
rs.Require().NoError(err)
rs.Assert().Equal(count, 0)
}
func (rs *RepositorySuite) TestUpdateUser() {
user := models.UserInfo{ID: "12345", FirstName: "foo", LastName: "bar", Email: "foo@email.com"}
rs.Require().NoError(rs.collection().Insert(user))
user.FirstName = "bar"
user.LastName = "foo"
user.Email = "foo@email.com"
rs.Assert().NoError(rs.repo.UpdateUser(user))
rs.Assert().Equal(models.UserInfo{ID: "12345", FirstName: "bar", LastName: "foo", Email: "foo@email.com"}, user)
}
func (rs *RepositorySuite) TestUpdateUserNotFound() {
user := models.UserInfo{ID: "12345", FirstName: "foo", LastName: "bar", Email: "foo@email.com"}
rs.Assert().True(repository.IsErrUserNotFound(rs.repo.UpdateUser(user)))
}
func (rs *RepositorySuite) TestRemoveUserNotFound() {
err := rs.repo.RemoveUser(repository.NewMatcher().WithID("1234"))
rs.Assert().True(repository.IsErrUserNotFound(err))
}
func (rs *RepositorySuite) TestListUser() {
for i := 0; i < 100; i++ {
rs.Require().NoError(rs.collection().Insert(&models.UserInfo{ID: fmt.Sprintf("%d", i), FirstName: "foo", LastName: "bar", Email: "foo@email.com"}))
}
users, err := rs.repo.ListUsers(repository.EmptyMatcher)
rs.Require().NoError(err)
rs.Len(users, 100)
}
func (rs *RepositorySuite) TestListUserMatcher() {
for i := 0; i < 50; i++ {
rs.Require().NoError(rs.collection().Insert(&models.UserInfo{ID: fmt.Sprintf("%d", i), FirstName: "foo", LastName: "bar", Email: "foo@email.com"}))
}
users, err := rs.repo.ListUsers(repository.NewMatcher().WithID("1"))
rs.Require().NoError(err)
rs.Len(users, 1)
}
func (rs *RepositorySuite) TestListUsersNone() {
users, err := rs.repo.ListUsers(repository.EmptyMatcher)
rs.Assert().NoError(err)
rs.Assert().Len(users, 0)
}
func (rs *RepositorySuite) TestIndexCreated() {
indexs, err := rs.collection().Indexes()
rs.Require().NoError(err)
rs.Require().Len(indexs, 2)
rs.Assert().Len(indexs[1].Key, 1)
rs.Assert().Equal("id", indexs[1].Key[0])
rs.Assert().Equal(true, indexs[1].Unique)
}
|
package utils
import (
"fmt"
"io"
"math/big"
"github.com/zhaohaijun/matrixchain/common"
"github.com/zhaohaijun/matrixchain/common/serialization"
"github.com/zhaohaijun/matrixchain/vm/neovm/types"
)
func WriteVarUint(w io.Writer, value uint64) error {
if err := serialization.WriteVarBytes(w, types.BigIntToBytes(big.NewInt(int64(value)))); err != nil {
return fmt.Errorf("serialize value error:%v", err)
}
return nil
}
func ReadVarUint(r io.Reader) (uint64, error) {
value, err := serialization.ReadVarBytes(r)
if err != nil {
return 0, fmt.Errorf("deserialize value error:%v", err)
}
v := types.BigIntFromBytes(value)
if v.Cmp(big.NewInt(0)) < 0 {
return 0, fmt.Errorf("%s", "value should not be a negative number.")
}
return v.Uint64(), nil
}
func WriteAddress(w io.Writer, address common.Address) error {
if err := serialization.WriteVarBytes(w, address[:]); err != nil {
return fmt.Errorf("serialize value error:%v", err)
}
return nil
}
func ReadAddress(r io.Reader) (common.Address, error) {
from, err := serialization.ReadVarBytes(r)
if err != nil {
return common.Address{}, fmt.Errorf("[State] deserialize from error:%v", err)
}
return common.AddressParseFromBytes(from)
}
func EncodeAddress(sink *common.ZeroCopySink, addr common.Address) (size uint64) {
return sink.WriteVarBytes(addr[:])
}
func EncodeVarUint(sink *common.ZeroCopySink, value uint64) (size uint64) {
return sink.WriteVarBytes(types.BigIntToBytes(big.NewInt(int64(value))))
}
func DecodeVarUint(source *common.ZeroCopySource) (uint64, error) {
value, _, irregular, eof := source.NextVarBytes()
if eof {
return 0, io.ErrUnexpectedEOF
}
if irregular {
return 0, common.ErrIrregularData
}
v := types.BigIntFromBytes(value)
if v.Cmp(big.NewInt(0)) < 0 {
return 0, fmt.Errorf("%s", "value should not be a negative number.")
}
return v.Uint64(), nil
}
func DecodeAddress(source *common.ZeroCopySource) (common.Address, error) {
from, _, irregular, eof := source.NextVarBytes()
if eof {
return common.Address{}, io.ErrUnexpectedEOF
}
if irregular {
return common.Address{}, common.ErrIrregularData
}
return common.AddressParseFromBytes(from)
}
|
package main
import (
"context"
"flag"
"fmt"
"github.com/zacharychang/go-study/grpc/proto/echo"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"io"
"log"
"net"
"os"
)
var (
port = flag.Int("port", 1200, "the port to listen")
)
type server struct{}
func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) {
return nil, status.Error(codes.Unimplemented, "todo")
}
func (s *server) ServerStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error {
return status.Error(codes.Unimplemented, "todo")
}
func (s *server) ClientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error {
return status.Error(codes.Unimplemented, "todo")
}
func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
for {
in, err := stream.Recv()
if err != nil {
log.Printf("server: error receiving from stream: %v\n", err)
if err == io.EOF {
return nil
}
return err
}
log.Printf("echo message: %q\n", in.Message)
err = stream.Send(&pb.EchoResponse{
Message: in.Message,
})
if err != nil {
log.Printf("server: error sending to stream: %v\n", err)
return err
}
}
}
func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
os.Exit(1)
}
log.Printf("server listening at port %v\n", lis.Addr())
s := grpc.NewServer()
pb.RegisterEchoServer(s, &server{})
if err = s.Serve(lis); err != nil {
log.Printf("server failed to start: %v\n", lis.Addr())
}
}
|
package main
import (
"net/http"
"strconv"
"io/ioutil"
"encoding/json"
"log"
)
// This variable hold in memory storage
// It seems that go doesn't support thread global variable
// Have to get around it using a hack. Use dictionary to store data for each http service
var in_memory_storage map[string][]KeyValueContainer
// This method saves the data segments from client
func server_set(w http.ResponseWriter, r *http.Request) {
// receive data
body, _ := ioutil.ReadAll(r.Body)
var data KeyValueContainer
json.Unmarshal(body, &data)
log.Printf("[Server] %s : Recived data:%s (size:%d)\n", r.Host, data.Value, len(data.Value))
_, ok := in_memory_storage[r.Host]
if ok {
in_memory_storage[r.Host] = append(in_memory_storage[r.Host], data)
} else {
in_memory_storage[r.Host] = []KeyValueContainer{data}
}
}
// This method returns data found in the in memory storage
func server_get(w http.ResponseWriter, r *http.Request) {
// receive key
body, _ := ioutil.ReadAll(r.Body)
var data map[string]string
json.Unmarshal(body, &data)
//search for key and return
server_data := in_memory_storage[r.Host]
for index := range server_data {
if server_data[index].Key == data["key"] {
jsonValue, _ := json.Marshal(server_data[index])
w.Write(jsonValue)
log.Printf("[Server]Received request for key: %s. Sending value : %s", data["key"], server_data[index].Value)
break
}
}
}
// This method starts server services
func start_server(server_port int) {
// initialize in memory database
in_memory_storage = make(map[string][]KeyValueContainer)
// new service. GO thing
server_service := http.NewServeMux()
server_service.HandleFunc("/server_get", server_get)
server_service.HandleFunc("/server_set", server_set)
http.ListenAndServe(":"+strconv.Itoa(server_port), server_service)
}
|
package store
import (
"testing"
"time"
)
func TestParameter(t *testing.T) {
// t.Run("New Parameter", func(t *testing.T) {
// p := NewParameter("foo", nil)
// if p == nil {
// t.Fatalf("Unable to create a new parameter")
// }
// if fmt.Sprintf("%T", p) != "*store.Parameter" {
// t.Fatalf("Returned the wrong type: %v", fmt.Sprintf("%T", p))
// }
// })
// t.Run("New Parameter With Opts", func(t *testing.T) {
// expiry := time.Second * 10
// p := NewParameter("foo", nil, ValueExpires(expiry))
// if p.Expires != true || expiry != p.Expiry {
// t.Fatalf("Expiry time isn't correct: %v", p.Expires)
// }
// })
// t.Run("Refresh Parameter", func(t *testing.T) {
// expiry := time.Second * 1
// p := NewParameter("foo", nil, ValueExpires(expiry), AutoRefreshValue(true))
// if p.Expires != true || expiry != p.Expiry {
// t.Fatalf("Expiry time isn't correct: %v", p.Expires)
// }
// })
// t.Run("String Value", func(t *testing.T) {
// value := "bar"
// p := NewParameter("foo", value)
// retValue, _ := p.StringValue()
// if retValue != value {
// t.Fatalf("Error getting the value")
// }
// })
// t.Run("String Array Value", func(t *testing.T) {
// value := []string{"foo", "bar"}
// p := NewParameter("foo", value)
// retValue, _ := p.StringListValue()
// if !reflect.DeepEqual(retValue, value) {
// t.Fatalf("Error getting the value")
// }
// })
t.Run("Check Expiry in Future", func(t *testing.T) {
now := time.Now()
future := now.Add(time.Hour)
p := NewParameter("foo", "test")
p.Expires = true
p.lastRefresh = future
if err := p.RefreshValue(); err != nil {
t.Fatal("Dates in the future should not error")
}
})
t.Run("Check Expiry in Past", func(t *testing.T) {
past, _ := time.Parse("Mon, 01/02/06, 03:04PM", "Thu, 05/19/11, 10:47PM")
p := NewParameter("foo", "test")
p.Expires = true
p.lastRefresh = past
if err := p.RefreshValue(); err == nil {
t.Fatal("Dates in the past should error")
}
})
t.Run("Check Autorefresh enabled, but with no func", func(t *testing.T) {
past, _ := time.Parse("Mon, 01/02/06, 03:04PM", "Thu, 05/19/11, 10:47PM")
p := NewParameter("foo", "test", AutoRefreshValue(true))
p.Expires = true
p.lastRefresh = past
if err := p.RefreshValue(); err != ErrNoRefreshFn {
t.Fatalf("Parameters that have no refresh function should fail when auto refresh is enabled: %v", err)
}
})
t.Run("Check Autorefresh enabled, with func", func(t *testing.T) {
past, _ := time.Parse("Mon, 01/02/06, 03:04PM", "Thu, 05/19/11, 10:47PM")
p := NewParameter("foo", "test", AutoRefreshValue(true))
p.RefreshFn = func(p *Parameter) (interface{}, error) {
return nil, nil
}
p.Expires = true
p.lastRefresh = past
if err := p.RefreshValue(); err != nil {
t.Fatal("Parameters that have no refresh function should fail when auto refresh is enabled")
}
})
}
|
package moxings
type Yinpinshanchujius struct {
Id int
Xuliehao string `gorm:"not null;DEFAULT:0"`
Yishanchu int64 `gorm:"not null;DEFAULT:0"`
Shanchubiaoji int64 `gorm:"not null;DEFAULT:0"`
}
func (Yinpinshanchujius) TableName() string {
return "Yinpinshanchujius"
}
|
/*
Copyright 2021 The Tekton 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 cloudevent
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"knative.dev/pkg/apis"
)
// myObjectWithCondition is an objectWithCondition that is not PipelineRUn or TaskRun
type myObjectWithCondition struct{}
func (mowc myObjectWithCondition) DeepCopyObject() runtime.Object { return nil }
func (mowc myObjectWithCondition) GetObjectKind() schema.ObjectKind { return nil }
func (mowc myObjectWithCondition) GetObjectMeta() metav1.Object { return nil }
func (mowc myObjectWithCondition) GetStatusCondition() apis.ConditionAccessor { return nil }
|
/*****************************************************************************
* file name : MemPool.go
* author : Wu Yinghao
* email : wyh817@gmail.com
*
* file description : 内存池
*
******************************************************************************/
package SparrowCache
import (
"fmt"
"time"
)
var MAX_NODE_COUNT int = 1000
type Node struct {
key string
value string
hash1 uint64
hash2 uint64
Next *Node
}
func NewNode() *Node {
node := &Node{hash1: 0, hash2: 0, Next: nil}
return node
}
// SMemPool 内存池对象
type SMemPool struct {
nodechanGet chan *Node
nodechanGiven chan *Node
nodeList []Node
freeList []*Node
}
func (pool *SMemPool) makeNodeList() error {
pool.nodeList = make([]Node, MAX_NODE_COUNT)
return nil
}
func NewMemPool() *SMemPool {
this := &SMemPool{nodechanGet: make(chan *Node, MAX_NODE_COUNT),
nodechanGiven: make(chan *Node, MAX_NODE_COUNT),
nodeList: make([]Node, MAX_NODE_COUNT),
freeList: make([]*Node, 0)}
return this
}
func (this *SMemPool) Alloc() *Node {
return <-this.nodechanGet
}
func (this *SMemPool) Free(node *Node) error {
this.nodechanGiven <- node
return nil
}
func (this *SMemPool) InitMemPool() error {
//初始化node
go func() {
//q := new(list.List)
q := make([]Node, MAX_NODE_COUNT)
for {
if len(q) == 0 {
q = append(q, make([]Node, MAX_NODE_COUNT)...)
}
e := q[0]
timeout := time.NewTimer(time.Second)
select {
case b := <-this.nodechanGiven:
timeout.Stop()
fmt.Printf("Free Buffer...\n")
//b=b[:MAX_DOCID_LEN]
q = append(q, *b)
case this.nodechanGet <- &e:
timeout.Stop()
q = q[1:]
//fmt.Printf("Alloc Buffer...\n")
//q.Remove(e)
case <-timeout.C:
fmt.Printf("remove Buffer...\n")
}
}
}()
return nil
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package camera
import (
"context"
"time"
"chromiumos/tast/common/media/caps"
"chromiumos/tast/remote/bundles/cros/camera/camerabox"
"chromiumos/tast/remote/bundles/cros/camera/pre"
"chromiumos/tast/rpc"
pb "chromiumos/tast/services/cros/camerabox"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: HAL3Remote,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Verifies camera HAL3 interface function on remote DUT",
Contacts: []string{"beckerh@chromium.org", "chromeos-camera-eng@google.com"},
Attr: []string{"group:camerabox"},
SoftwareDeps: []string{"arc", "arc_camera3", caps.BuiltinCamera},
ServiceDeps: []string{"tast.cros.camerabox.HAL3Service"},
Data: []string{pre.DataChartScene().DataPath()},
Vars: []string{"chart"},
Pre: pre.DataChartScene(),
// For extra params, reference corresponding tests in:
// src/platform/tast-tests/src/chromiumos/tast/local/bundles/cros/camera/hal3_*.go
Params: []testing.Param{
{
Name: "frame_back",
ExtraAttr: []string{"camerabox_facing_back"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_FRAME, Facing: pb.Facing_FACING_BACK},
Timeout: 15 * time.Minute,
},
{
Name: "frame_front",
ExtraAttr: []string{"camerabox_facing_front"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_FRAME, Facing: pb.Facing_FACING_FRONT},
Timeout: 15 * time.Minute,
},
{
Name: "perf_back",
ExtraAttr: []string{"camerabox_facing_back"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_PERF, Facing: pb.Facing_FACING_BACK},
},
{
Name: "perf_front",
ExtraAttr: []string{"camerabox_facing_front"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_PERF, Facing: pb.Facing_FACING_FRONT},
},
{
Name: "preview_back",
ExtraAttr: []string{"camerabox_facing_back"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_PREVIEW, Facing: pb.Facing_FACING_BACK},
},
{
Name: "preview_front",
ExtraAttr: []string{"camerabox_facing_front"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_PREVIEW, Facing: pb.Facing_FACING_FRONT},
},
{
Name: "recording_back",
ExtraAttr: []string{"camerabox_facing_back"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_RECORDING, Facing: pb.Facing_FACING_BACK},
},
{
Name: "recording_front",
ExtraAttr: []string{"camerabox_facing_front"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_RECORDING, Facing: pb.Facing_FACING_FRONT},
},
{
Name: "still_capture_back",
ExtraAttr: []string{"camerabox_facing_back"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_STILL_CAPTURE, Facing: pb.Facing_FACING_BACK},
Timeout: 6 * time.Minute,
},
{
Name: "still_capture_front",
ExtraAttr: []string{"camerabox_facing_front"},
Val: &pb.RunTestRequest{Test: pb.HAL3CameraTest_STILL_CAPTURE, Facing: pb.Facing_FACING_FRONT},
Timeout: 6 * time.Minute,
},
},
})
}
func HAL3Remote(ctx context.Context, s *testing.State) {
d := s.DUT()
runTestRequest := s.Param().(*pb.RunTestRequest)
if err := camerabox.LogTestScene(ctx, d, runTestRequest.Facing, s.OutDir()); err != nil {
s.Error("Failed to take a photo of test scene: ", err)
}
// Connect to the gRPC server on the DUT.
cl, err := rpc.Dial(ctx, d, s.RPCHint())
if err != nil {
s.Fatal("Failed to connect to the HAL3 service on the DUT: ", err)
}
defer cl.Close(ctx)
// Run remote test on DUT.
hal3Client := pb.NewHAL3ServiceClient(cl.Conn)
response, err := hal3Client.RunTest(ctx, runTestRequest)
if err != nil {
s.Fatal("Remote call RunTest() failed: ", err)
}
// Check test result.
switch response.Result {
case pb.TestResult_TEST_RESULT_PASSED:
case pb.TestResult_TEST_RESULT_FAILED:
s.Error("Remote test failed with error message:", response.Error)
case pb.TestResult_TEST_RESULT_UNSET:
s.Error("Remote test result is unset")
}
}
|
package main
import "fmt"
//map 数据类型
func main() {
//两种定义方式
//第一个string 是那种数据类型,第二个string 是返回值类型,可以换成结构体,后面会学到
//var mymap map[string]string
// //
// //fmt.Println(mymap)
// //
// //var mymaps= make(map[string]string)
// //mymaps["tim"]="gogos"
// //mymaps["zs"]="zsdf"
// //fmt.Println(mymaps)
//几种定义方式
//mymapss:=make(map[string]string)
//mymapss["Tim"] = "Good morning."
//mymapss["Jenny"] = "Bonjour."
//fmt.Println(mymapss)
//mymass:=map[string]string{}
//mymass["Tim"] = "Good morning."
//mymass["Jenny"] = "Bonjour."
//fmt.Println(mymass)
//初始化并赋值
/* mys:= map[string]string{
"tim":"zk",
"lk":"red",
}
fmt.Println(mys)
//添加字段
mys["zmbhs"]="howdy"
fmt.Println(mys)
//长度
fmt.Println(len(mys))
//更新操作
mys["Harleen"] = "Howdy"
fmt.Println(mys)
mys["Harleen"] = "Gidday"
fmt.Println(mys)
*/
//删除操作
/*myGreeting := map[string]string{
"zero": "Good morning!",
"one": "Bonjour!",
"two": "Buenos dias!",
"three": "Bongiorno!",
}
fmt.Println(myGreeting)
delete(myGreeting, "two")
fmt.Println(myGreeting)*/
//判断值是否存在
/*myGreeting := map[int]string{
0: "Good morning!",
1: "Bonjour!",
2: "Buenos dias!",
3: "Bongiorno!",
}
fmt.Println(myGreeting)
if val,exists:=myGreeting[4];exists{
fmt.Println("That value exists.")
fmt.Println("val: ", val)
fmt.Println("exists: ", exists)
}else {
fmt.Println("That value doesn't exist.")
fmt.Println("val: ", val)
fmt.Println("exists: ", exists)
}
fmt.Println(myGreeting)*/
//删除不存在的种子
//myGreeting := map[int]string{
// 0: "Good morning!",
// 1: "Bonjour!",
// 2: "Buenos dias!",
// 3: "Bongiorno!",
//}
//fmt.Println(myGreeting)
//delete(myGreeting, 7)
//fmt.Println(myGreeting)
//if val, exists := myGreeting[7]; exists {
// delete(myGreeting, 7)
// fmt.Println("val: ", val)
// fmt.Println("exists: ", exists)
//} else {
// fmt.Println("That value doesn't exist.")
// fmt.Println("val: ", val)
// fmt.Println("exists: ", exists)
//}
//
//fmt.Println(myGreeting)
//循环
myGreeting := map[int]string{
0: "Good morning!",
1: "Bonjour!",
2: "Buenos dias!",
3: "Bongiorno!",
}
for key, val := range myGreeting {
fmt.Println(key, " - ", val)
}
}
|
package api
import (
"github.com/pkg/errors"
"github.com/ssok8s/ssok8s/pkg/api/dtos"
"github.com/ssok8s/ssok8s/pkg/bus"
"github.com/ssok8s/ssok8s/pkg/components/simplejson"
m "github.com/ssok8s/ssok8s/pkg/models"
"regexp"
)
func createSrp(c *m.ReqContext, form dtos.CreateSrpForm) Response {
//todo check namespaceId ..
//todo check permission
policy := "^[\\w-]{1,64}$"
re := regexp.MustCompile(policy)
if !re.MatchString(form.Name) {
return Error(400, "SRP name does not meets the naming policy. The length limit is 64, and the symbol only allows dashes and underscores.", errors.New("SRP name does not meets the naming policy. The length limit is 64, and the symbol only allows dashes and underscores."))
}
srp := m.CreateSrpCommand{
Name: form.Name,
Workspace: form.WorkspaceId + "name",
WorkspaceId: form.WorkspaceId,
Namespace: form.NamespaceId + "name",
NamespaceId: form.NamespaceId,
ClusterId: form.ClusterId,
Cluster: form.ClusterId + "name",
Scope: form.Scopes,
SrpAppId: form.SrpAppId,
SrpAppName: form.SrpAppName,
}
if err := bus.Dispatch(&srp); err != nil {
if err == m.ErrSrpExists {
return Error(409, "SRP name already exists on namespace", err)
}
return Error(500, "Failed to create Srp", err)
}
return JSON(200, srp.Result)
}
func getSrpByIdOrName(c *m.ReqContext) Response {
srpId := c.Params(":srpIdOrName")
/*mode :=c.Query("mode")
if mode ==""{
mode ="name"
}
if mode =="name"{
}*/
srp := m.GetSrpByIdQuery{
SrpId: srpId,
}
if err := bus.Dispatch(&srp); err != nil {
if err == m.ErrSrpNotFound {
return Error(404, err.Error(), err)
}
return Error(500, "Failed to get srp", err)
}
return JSON(200, srp.Result)
}
func getSrps(c *m.ReqContext) Response {
srps := m.GetSrpQuery{}
if err := bus.Dispatch(&srps); err != nil {
return Error(500, err.Error(), err)
}
return JSON(200, srps.Result)
}
func deleteSrp(c *m.ReqContext) Response {
srpId := c.Params(":srpId")
srp := m.DeleteSrpByIdCommand{
SrpId: srpId,
}
if err := bus.Dispatch(&srp); err != nil {
return Error(500, err.Error(), err)
}
return Success("Srp deleted")
}
func updateSrp(c *m.ReqContext, form dtos.CreateSrpForm) Response {
srpId := c.Params(":srpId")
getsrp := m.GetSrpByIdQuery{
SrpId: srpId,
}
if err := bus.Dispatch(&getsrp); err != nil {
if err == m.ErrSrpNotFound {
return Error(404, "SRP ID does not exist", err)
}
return Error(500, "Failed to get srp", err)
}
getsrp.Result.Scope = form.Scopes
getsrp.Result.NamespaceId = form.NamespaceId
getsrp.Result.ClusterId = form.ClusterId
getsrp.Result.WorkspaceId = form.WorkspaceId
getsrp.Result.SrpAppId = form.SrpAppId
updateSrp := m.UpdateSrpCommand{
Srp: getsrp.Result,
}
if err := bus.Dispatch(&updateSrp); err != nil {
return Error(500, "Failed to update srp", err)
}
return Success("Update srp successd")
}
func listSrp(c *m.ReqContext) Response {
name := c.Query("name")
if name == "" {
return Error(400, "Parameter name can not be empty", nil)
}
page := c.QueryInt64("page")
if page == 0 {
page = 1
}
maxResults := c.QueryInt64("maxResults")
if maxResults == 0 {
maxResults = 100
}
direction := c.Query("direction")
if direction != "desc" {
direction = "asc"
}
property := c.Query("property")
if property == "" {
property = "name"
}
username := c.Username
if c.Role == "admin" {
username = ""
}
getsrpList := m.FuzzySrpListQuery{
Username: username,
Name: name,
Direction: direction,
Property: property,
MaxResults: maxResults,
Page: page,
}
if err := bus.Dispatch(&getsrpList); err != nil {
return Error(500, "Failed to get srp list", err)
}
srpListResp := simplejson.New()
srpListResp.Set("totle", len(getsrpList.SrpList))
srpListResp.Set("resource", getsrpList.SrpList)
return JSON(200, srpListResp)
}
|
// Copyright 2020 The LUCI 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 gerrit
import (
"context"
"google.golang.org/grpc"
"go.chromium.org/luci/common/errors"
gerritpb "go.chromium.org/luci/common/proto/gerrit"
)
// Client defines a subset of Gerrit API used by CV.
//
// It's a union of more specific interfaces such that small code chunks can be tested
// by faking or mocking only relevant methods.
type Client interface {
CLReaderClient
CLWriterClient
QueryClient
}
// Client must be a subset of gerritpb.Client.
var _ Client = (gerritpb.GerritClient)(nil)
var clientCtxKey = "go.chromium.org/luci/cv/internal/gerrit.Client"
// UseClientFactory puts a given ClientFactory into in the context.
func UseClientFactory(ctx context.Context, f ClientFactory) context.Context {
return context.WithValue(ctx, &clientCtxKey, f)
}
// UseProd puts a production ClientFactory into in the context.
func UseProd(ctx context.Context) (context.Context, error) {
f, err := newFactory(ctx)
if err != nil {
return nil, err
}
return UseClientFactory(ctx, f.makeClient), nil
}
// CurrentClient returns the Client in the context or an error.
func CurrentClient(ctx context.Context, gerritHost, luciProject string) (Client, error) {
f, _ := ctx.Value(&clientCtxKey).(ClientFactory)
if f == nil {
return nil, errors.New("not a valid Gerrit context, no ClientFactory available")
}
return f(ctx, gerritHost, luciProject)
}
// CLReaderClient defines a subset of Gerrit API used by CV to fetch CL details.
type CLReaderClient interface {
// Loads a change by id.
//
// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-change
GetChange(ctx context.Context, in *gerritpb.GetChangeRequest, opts ...grpc.CallOption) (*gerritpb.ChangeInfo, error)
// Retrieves related changes of a revision.
//
// Related changes are changes that either depend on, or are dependencies of
// the revision.
//
// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-related-changes
GetRelatedChanges(ctx context.Context, in *gerritpb.GetRelatedChangesRequest, opts ...grpc.CallOption) (*gerritpb.GetRelatedChangesResponse, error)
// Lists the files that were modified, added or deleted in a revision.
//
// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-files
ListFiles(ctx context.Context, in *gerritpb.ListFilesRequest, opts ...grpc.CallOption) (*gerritpb.ListFilesResponse, error)
}
// CLWriterClient defines a subset of Gerrit API used by CV to mutate CL.
type CLWriterClient interface {
// Set various review bits on a change.
//
// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-review
SetReview(ctx context.Context, in *gerritpb.SetReviewRequest, opts ...grpc.CallOption) (*gerritpb.ReviewResult, error)
// Submit a specific revision of a change.
//
// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-revision
SubmitRevision(ctx context.Context, in *gerritpb.SubmitRevisionRequest, opts ...grpc.CallOption) (*gerritpb.SubmitInfo, error)
}
// QueryClient defines a subset of Gerrit API used by CV to query for CLs.
type QueryClient interface {
// Lists changes that match a query.
//
// Note, although the Gerrit API supports multiple queries, for which
// it can return multiple lists of changes, this is not a foreseen use-case
// so this API just includes one query with one returned list of changes.
//
// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
ListChanges(ctx context.Context, in *gerritpb.ListChangesRequest, opts ...grpc.CallOption) (*gerritpb.ListChangesResponse, error)
}
// ClientFactory creates Client tied to Gerrit host and LUCI project.
//
// Gerrit host and LUCI project determine the authentication being used.
type ClientFactory func(ctx context.Context, gerritHost, luciProject string) (Client, error)
|
package storageos
import (
storagev1beta1 "k8s.io/api/storage/v1beta1"
kdiscovery "k8s.io/client-go/discovery"
"github.com/storageos/cluster-operator/internal/pkg/discovery"
k8sresource "github.com/storageos/cluster-operator/pkg/util/k8s/resource"
)
// createCSIDriver creates a StorageOS CSIDriver resource with the required
// attributes.
func (s *Deployment) createCSIDriver() error {
attachRequired := true
podInfoRequired := true
spec := &storagev1beta1.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoRequired,
}
return k8sresource.NewCSIDriver(s.client, StorageOSProvisionerName, nil, spec).Create()
}
// deleteCSIDriver deletes the StorageOS CSIDriver resource.
func (s Deployment) deleteCSIDriver() error {
return s.k8sResourceManager.CSIDriver(CSIProvisionerName, nil, nil).Delete()
}
// HasCSIDriverKind checks if CSIDriver built-in resource is supported in the
// k8s cluster.
func HasCSIDriverKind(dc kdiscovery.DiscoveryInterface) (bool, error) {
return discovery.HasResource(dc, k8sresource.APIstoragev1beta1, k8sresource.CSIDriverKind)
}
|
package db
import (
"github.com/truebluejason/p2e-background/internal/conf"
_ "github.com/go-sql-driver/mysql"
"database/sql"
)
type Content struct {
Id int
Type string
Author string
Payload string
}
var dataSource string = conf.Configs.DBUser + ":" + conf.Configs.DBPassword + "@tcp(" + conf.Configs.DBHost + ")/" + conf.Configs.DBName
func GetUsersFromTime(formattedTime string) ([]string, error) {
var userIDs []string
db, err := sql.Open("mysql", dataSource)
if err != nil {
return userIDs, err
}
defer db.Close()
err = db.Ping()
if err != nil {
return userIDs, err
}
rows, err := db.Query("SELECT UserID FROM UserTimes WHERE AdjustedStamp = ?", formattedTime)
if err != nil {
return userIDs, err
}
defer rows.Close()
for rows.Next() {
var userID string
if err := rows.Scan(&userID); err != nil {
return userIDs, err
}
userIDs = append(userIDs, userID)
}
err = rows.Err()
return userIDs, err
}
func GetRandomContent() (Content, error) {
var randContent Content = Content{}
var author sql.NullString
db, err := sql.Open("mysql", dataSource)
if err != nil {
return randContent, err
}
defer db.Close()
err = db.Ping()
if err != nil {
return randContent, err
}
rows, err := db.Query("SELECT ContentID, Type, Author, Content FROM Contents ORDER BY Rand() LIMIT 1")
if err != nil {
return randContent, err
}
defer rows.Close()
rows.Next()
if err := rows.Scan(&randContent.Id, &randContent.Type, &author, &randContent.Payload); err != nil {
return randContent, err
}
if author.Valid {
randContent.Author = author.String
} else {
randContent.Author = ""
}
err = rows.Err()
return randContent, err
}
|
// Copyright 2019 Ulisse Mini. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
log "github.com/UlisseMini/leetlog"
"github.com/go-yaml/yaml"
"github.com/gobuffalo/packd"
"github.com/gobuffalo/packr/v2"
"github.com/mitchellh/go-homedir"
)
// Only used on first program run, then unpacked to ~/.gocs
var box = packr.New("", "./gocs_default")
// Config file struct, will be stored in ~/.gocs/config.yaml
type Config struct {
Github string // Github username
Author string // Full name of the author
}
const (
templates = "templates" // for my sanity if i ever change this
defaultTmpl = "default" // default template in ~/.gocs/templates/
)
var (
home string // ~/
gocs string // ~/.gocs
configPath string // ~/.gocs/config.yaml
)
func init() {
var err error
home, err = homedir.Dir()
if err != nil {
log.Fatalf("getting home directory: %v", err)
}
gocs = filepath.Join(home, ".gocs")
configPath = filepath.Join(home, ".gocs/config.yaml")
}
func main() {
// manage flags
flag.Usage = usage
d := flag.Bool("d", false, "print debug logs")
flag.Parse()
// switch over flags
switch {
case *d:
log.DefaultLogger.Ldebug.SetOutput(os.Stderr)
}
// get the template dir to use
templateDir := flag.Arg(1)
if templateDir == "" {
templateDir = defaultTmpl
}
createDir() // create ~/.gocs if needed
conf := getConfig() // read ~/.gocs/config.yaml and create it if needed
proj := Project{
Config: conf,
Year: time.Now().Year(),
Project: flag.Arg(0),
}
if err := proj.Create(templateDir); err != nil {
log.Fatal(err)
}
}
// create the ~/.gocs directory if it does not exist.
func createDir() {
if _, err := os.Stat(gocs); err == nil {
return
}
// create ~/.gocs
if err := os.Mkdir(gocs, 0755); err != nil {
log.Fatal(err)
}
// unpack box into ~/.gocs
err := box.Walk(func(path string, file packd.File) error {
log.Debugf("walk: %s", path)
dst := filepath.Join(gocs, path)
// if it has a parent directory create it.
if err := createParents(dst); err != nil {
return fmt.Errorf("walk: createParents: %v", err)
}
b, err := box.Find(path)
if err != nil {
log.Debugf("walk: find %q: %v", path, err)
return err
}
return ioutil.WriteFile(dst, b, 0666)
})
if err != nil {
log.Fatal(err)
}
}
// getConfig gets the config file from ~/.gocs/config.yaml and returns it,
// if it does not exist it creates it.
func getConfig() (conf Config) {
// Read the config file
b, err := ioutil.ReadFile(configPath)
if err != nil {
// if it is not a path error then fatal
if _, ok := err.(*os.PathError); !ok {
log.Fatal(err)
}
// otherwise create a config
conf = createConfig(configPath)
}
if err := yaml.Unmarshal(b, &conf); err != nil {
log.Fatal(err)
}
return conf
}
// question the user and create a config file, return the config when done.
func createConfig(path string) (conf Config) {
s := bufio.NewScanner(os.Stdin)
conf.Author = input(s, "Full name or alias: ")
conf.Github = input(s, "Github username: ")
data, err := yaml.Marshal(conf)
if err != nil {
log.Fatal(err)
}
if err := ioutil.WriteFile(path, data, 0666); err != nil {
log.Fatal(err)
}
log.Infof("Written to %q", path)
return conf
}
// input helper
func input(s *bufio.Scanner, prompt string) string {
log.Print(prompt)
if !s.Scan() {
log.Fatal(s.Err())
}
return s.Text()
}
func usage() {
fmt.Fprintf(os.Stderr, "Usage of %s: <project> [template]\n", os.Args[0])
fmt.Fprintln(os.Stderr, "<project> is the Project's name")
fmt.Fprintln(os.Stderr, "[template] is looked for in ~/.gocs/")
flag.PrintDefaults()
}
// create parent directories for path.
func createParents(path string) error {
dir := filepath.Dir(path)
if dir == "" {
return nil
}
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("MkdirAll: %v", err)
}
return nil
}
|
/**
* @Author: DollarKiller
* @Description: Config
* @Github: https://github.com/dollarkillerx
* @Date: Create in 11:37 2019-10-24
*/
package config
import (
"github.com/dollarkillerx/easyutils"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"time"
)
type base struct {
App struct {
Host string `yaml:"host"`
Debug bool `yaml:"debug"`
OneDriveUrl string `yaml:"one_drive_url"`
}
Pgsql struct {
Dsn string `yaml:"dsn"`
MaxIdle int `yaml:"max_idle"`
MaxOpen int `yaml:"max_open"`
TimeOut time.Duration `yaml:"time_out"`
}
}
var (
MyConfig *base
)
func init() {
MyConfig = &base{}
b, i := easyutils.PathExists("./config.yml")
if i != nil || b == false {
// 如果配置文件不存在
createConfig()
}
bytes, e := ioutil.ReadFile("./config.yml")
if e != nil {
panic(e.Error())
}
e = yaml.Unmarshal(bytes, MyConfig)
if e != nil {
panic(e.Error())
}
if MyConfig.App.Debug {
log.Println(MyConfig)
}
}
func createConfig() {
err := ioutil.WriteFile("config.yml", []byte(conf), 00755)
if err != nil {
panic(err)
}
log.Fatalln("请填写配置文件!")
}
var conf = `
# 通用配置文件
app:
host: "0.0.0.0:8082"
debug: true
one_drive_url: "https://vipmail-my.sharepoint.cn" // OneDriveUrl (国内版本:https://vipmail-my.sharepoint.cn)
pgsql:
dsn: "host= user= dbname= sslmode=disable password="
max_idle: 10 # 最大闲置链接数
max_open: 100 # 最大链接数
time_out: 4 # 超时 Hour
`
|
package users
import (
"fmt"
"math"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync"
"testing"
"github.com/google/uuid"
"github.com/jrapoport/gothic/core/context"
"github.com/jrapoport/gothic/hosts/rest"
"github.com/jrapoport/gothic/models/types"
"github.com/jrapoport/gothic/models/types/key"
"github.com/jrapoport/gothic/models/types/provider"
"github.com/jrapoport/gothic/models/user"
"github.com/jrapoport/gothic/store"
"github.com/jrapoport/gothic/test/tconn"
"github.com/jrapoport/gothic/test/thttp"
"github.com/jrapoport/gothic/test/tsrv"
"github.com/jrapoport/gothic/test/tutils"
"github.com/jrapoport/gothic/utils"
"github.com/segmentio/encoding/json"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
type TestUsers struct {
uid uuid.UUID
provider provider.Name
role user.Role
email string
name string
data types.Map
}
var testBook = uuid.New().String()
func CreateTestUsers(t *testing.T, srv *usersServer) []TestUsers {
var cases = func() []TestUsers {
email := func() string { return tutils.RandomEmail() }
name := func() string { return utils.RandomUsername() }
p := srv.Provider()
ru := user.RoleUser
ra := user.RoleAdmin
var tests = []TestUsers{
{uuid.Nil, p, ru, email(), name(), nil},
{uuid.Nil, p, ru, email(), name(), nil},
{uuid.Nil, p, ru, email(), name(), nil},
{uuid.Nil, p, ru, email(), name(), nil},
{uuid.Nil, p, ru, email(), name(), nil},
{uuid.Nil, p, ru, email(), name(), nil},
{uuid.Nil, p, ru, email(), name(), nil},
{uuid.Nil, p, ra, email(), name(), nil},
{uuid.Nil, p, ra, email(), name(), nil},
}
for i, test := range tests {
ext := test
ext.email = email()
ext.provider = provider.Google
if i%2 == 0 {
ext.provider = provider.Amazon
}
tests = append(tests, ext)
}
var once sync.Once
var idx = 0
for i, bk := range []interface{}{
"thing2", testBook, uuid.New().String(),
} {
for x, test := range tests {
test.data = types.Map{
"dr_suess": "thing1",
"book": bk,
}
if idx < 50 {
test.data["sorted"] = "yes"
}
idx++
sld := fmt.Sprintf("salad-%d", x+i)
test.data["extra"] = sld
once.Do(func() {
test.data["pepper"] = "spicy"
})
test.email = email()
tests = append(tests, test)
}
}
return tests
}()
ctx := context.Background()
admin, _ := testUser(t, srv, true)
ctx.SetAdminID(admin.ID)
ctx.SetProvider(srv.Provider())
srv.Config().Signup.AutoConfirm = true
srv.Config().Signup.Default.Username = false
srv.Config().Signup.Default.Color = false
srv.Config().Mail.SpamProtection = false
conn := tconn.Conn(t, srv.Config())
err := conn.Transaction(func(tx *store.Connection) error {
for i, test := range cases {
u := user.NewUser(
test.provider,
test.role,
test.email,
test.name,
[]byte(testPass),
test.data,
nil)
err := tx.Save(u).Error
require.NoError(t, err)
cases[i].uid = u.ID
}
return nil
})
require.NoError(t, err)
return cases
}
type UserServerTestSuite struct {
suite.Suite
srv *usersServer
conn *store.Connection
tests []TestUsers
uid uuid.UUID
}
func TestUserServer_Search(t *testing.T) {
t.Parallel()
ts := &UserServerTestSuite{}
suite.Run(t, ts)
}
func (ts *UserServerTestSuite) SetupSuite() {
s, _ := tsrv.RESTServer(ts.T(), false)
ts.srv = newUserServer(s)
conn, err := store.Dial(ts.srv.Config(), nil)
ts.Require().NoError(err)
ts.conn = conn
ts.tests = CreateTestUsers(ts.T(), ts.srv)
}
func (ts *UserServerTestSuite) searchUsers(ep string, v url.Values) *httptest.ResponseRecorder {
r := thttp.Request(ts.T(), http.MethodGet, ep, "", v, nil)
w := httptest.NewRecorder()
ts.srv.SearchUsers(w, r)
return w
}
func (ts *UserServerTestSuite) TestErrors() {
// invalid req
r := thttp.Request(ts.T(), http.MethodGet, Users, "", nil, []byte("\n"))
w := httptest.NewRecorder()
ts.srv.SearchUsers(w, r)
ts.NotEqual(http.StatusOK, w.Code)
// bad paging (we handle this now)
r = thttp.Request(ts.T(), http.MethodGet, Users, "", url.Values{
key.Page: []string{"\n"},
}, nil)
w = httptest.NewRecorder()
ts.srv.SearchUsers(w, r)
ts.Equal(http.StatusOK, w.Code)
}
func (ts *UserServerTestSuite) TestPageHeaders() {
res := ts.searchUsers(Users, nil)
ts.Equal(http.StatusOK, res.Code)
var list []interface{}
err := json.NewDecoder(res.Body).Decode(&list)
ts.NoError(err)
ts.Len(list, store.MaxPageSize)
e := list[0].(map[string]interface{})
f := e[key.Data].(map[string]interface{})
uid := uuid.MustParse(e[key.ID].(string))
u, err := ts.srv.API.GetUser(uid)
ts.Require().NoError(err)
ts.Equal(uid, u.ID)
ts.Equal(f["dr_suess"], u.Data["dr_suess"])
pn := res.Header().Get(rest.PageNumber)
ts.Equal("1", pn)
pc := res.Header().Get(rest.PageCount)
cnt := int(math.Ceil(float64(len(ts.tests)) / float64(store.MaxPageSize)))
testCount := strconv.Itoa(cnt)
ts.Equal(testCount, pc)
sz := res.Header().Get(rest.PageSize)
testLen := strconv.Itoa(store.MaxPageSize)
ts.Equal(testLen, sz)
tot := res.Header().Get(rest.PageTotal)
// +1 because of audit.LogStartup
testTotal := strconv.Itoa(len(ts.tests) + 1)
ts.Equal(testTotal, tot)
}
func (ts *UserServerTestSuite) TestPageLinks() {
startLink := func() string {
return fmt.Sprintf("%s?%s=1&%s=%d",
Users, key.Page, key.PerPage, store.MaxPageSize)
}
var nextLink = startLink()
for {
if nextLink == "" {
break
}
u, err := url.Parse(nextLink)
ts.Require().NoError(err)
nextLink = ""
u.Scheme = ""
u.Host = ""
uri := u.String()
res := ts.searchUsers(uri, nil)
ts.Equal(http.StatusOK, res.Code)
var logs []interface{}
err = json.NewDecoder(res.Body).Decode(&logs)
ts.Require().NoError(err)
sz := res.Header().Get(rest.PageSize)
cnt, err := strconv.Atoi(sz)
ts.Require().NoError(err)
ts.Len(logs, cnt)
l := res.Header().Get(rest.Link)
links := strings.Split(l, ",")
if len(links) <= 0 {
break
}
for _, lnk := range links {
next := `rel="next"`
if strings.HasSuffix(lnk, next) {
nextLink = strings.ReplaceAll(lnk, next, "")
nextLink = strings.Trim(nextLink, " <>;")
break
}
}
}
}
func (ts *UserServerTestSuite) TestSearchFilters() {
tests := []struct {
v url.Values
comp func(e map[string]interface{})
}{
{
url.Values{
key.UserID: []string{ts.tests[0].uid.String()},
},
func(e map[string]interface{}) {
uid := e[key.ID].(string)
ts.Equal(ts.tests[0].uid.String(), uid)
},
},
{
url.Values{
key.ID: []string{ts.tests[0].uid.String()},
},
func(e map[string]interface{}) {
uid := e[key.ID].(string)
ts.Equal(ts.tests[0].uid.String(), uid)
},
},
{
url.Values{
key.Username: []string{ts.tests[0].name},
},
func(e map[string]interface{}) {
name := e[key.Username].(string)
ts.Equal(ts.tests[0].name, name)
},
},
{
url.Values{
key.Email: []string{ts.tests[0].email},
},
func(e map[string]interface{}) {
em := e[key.Email].(string)
ts.Equal(ts.tests[0].email, em)
},
},
{
url.Values{
key.Provider: []string{provider.Google.String()},
},
func(e map[string]interface{}) {
p := e[key.Provider].(string)
ts.Equal(provider.Google.String(), p)
},
},
{
url.Values{
key.Role: []string{user.RoleUser.String()},
},
func(e map[string]interface{}) {
r := e[key.Role].(string)
ts.Equal(user.RoleUser.String(), r)
},
},
{
url.Values{
"dr_suess": []string{"thing1"},
},
func(e map[string]interface{}) {
f := e[key.Data].(map[string]interface{})
ts.Equal("thing1", f["dr_suess"])
},
},
{
url.Values{
key.Role: []string{user.RoleUser.String()},
"dr_suess": []string{"thing1"},
},
func(e map[string]interface{}) {
r := e[key.Role].(string)
ts.Equal(user.RoleUser.String(), r)
f := e[key.Data].(map[string]interface{})
ts.Equal("thing1", f["dr_suess"])
},
},
{
url.Values{
"dr_suess": []string{"thing1"},
"book": []string{testBook},
},
func(e map[string]interface{}) {
f := e[key.Data].(map[string]interface{})
ts.Equal("thing1", f["dr_suess"])
ts.Equal(testBook, f["book"])
},
},
}
for _, test := range tests {
res := ts.searchUsers(Users, test.v)
ts.Equal(http.StatusOK, res.Code)
var list []interface{}
err := json.NewDecoder(res.Body).Decode(&list)
ts.NoError(err)
ts.Greater(len(list), 0)
for _, log := range list {
e := log.(map[string]interface{})
test.comp(e)
}
}
}
func (ts *UserServerTestSuite) TestSearchSort() {
// search Ascending
v := url.Values{
key.Sort: []string{store.Ascending.String()},
"dr_suess": []string{"thing1"},
"sorted": []string{"yes"},
}
var list []interface{}
res := ts.searchUsers(Users, v)
ts.Equal(http.StatusOK, res.Code)
err := json.NewDecoder(res.Body).Decode(&list)
ts.NoError(err)
ts.Greater(len(list), 0)
testIDs := make([]string, len(list))
for i, log := range list {
e := log.(map[string]interface{})
f := e[key.Data].(map[string]interface{})
ts.Equal("thing1", f["dr_suess"])
ts.Equal("yes", f["sorted"])
testIDs[i] = e[key.ID].(string)
}
// search Descending
v[key.Sort] = []string{store.Descending.String()}
res = ts.searchUsers(Users, v)
ts.Equal(http.StatusOK, res.Code)
err = json.NewDecoder(res.Body).Decode(&list)
ts.NoError(err)
ts.Greater(len(list), 0)
ts.Require().Len(list, len(testIDs))
descIDs := make([]string, len(list))
for i, log := range list {
e := log.(map[string]interface{})
f := e[key.Data].(map[string]interface{})
ts.Equal("thing1", f["dr_suess"])
ts.Equal("yes", f["sorted"])
descIDs[i] = e[key.ID].(string)
}
// reverse the ids
reverse := func(ids []string) {
for i, j := 0, len(ids)-1; i < j; i, j = i+1, j-1 {
ids[i], ids[j] = ids[j], ids[i]
}
}
reverse(descIDs)
ts.Equal(testIDs, descIDs)
}
|
package leetcode
func findSubstringInWraproundString(p string) int {
var count [26]int
var length int
for i := 0; i < len(p); i++ {
if 0 < i && (p[i-1]+1 == p[i] || p[i-1] == p[i]+25) {
length++
} else {
length = 1
}
b := p[i] - 'a'
count[b] = max(count[b], length)
}
var ans int
for i := 0; i < 26; i++ {
ans += count[i]
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
|
package shell
import (
"github.com/redhat-openshift-ecosystem/openshift-preflight/certification"
log "github.com/sirupsen/logrus"
)
type OperatorPkgNameIsUniqueCheck struct{}
func (p *OperatorPkgNameIsUniqueCheck) Validate(imgRef certification.ImageReference) (bool, error) {
mounted := true
result, err := podmanEngine.UnshareWithCheck("OperatorPackageNameIsUniqueMounted", imgRef.ImageURI, mounted)
if err != nil {
log.Trace("unable to execute preflight in the unshare env")
log.Debugf("Stdout: %s", result.Stdout)
log.Debugf("Stderr: %s", result.Stderr)
return false, err
}
return result.PassedOverall, nil
}
func (p *OperatorPkgNameIsUniqueCheck) Name() string {
return "OperatorPackageNameIsUnique"
}
func (p *OperatorPkgNameIsUniqueCheck) Metadata() certification.Metadata {
return certification.Metadata{
Description: "Validating Bundle image package name uniqueness",
Level: "best",
KnowledgeBaseURL: "https://connect.redhat.com/zones/containers/container-certification-policy-guide",
CheckURL: "https://connect.redhat.com/zones/containers/container-certification-policy-guide",
}
}
func (p *OperatorPkgNameIsUniqueCheck) Help() certification.HelpText {
return certification.HelpText{
Message: "Check encountered an error. It is possible that the bundle package name already exist in the RedHat Catalog registry.",
Suggestion: "Bundle package name must be unique meaning that it doesn't already exist in the RedHat Catalog registry",
}
}
|
package model
import "sync"
type Loginer interface {
Vaild() error
GetServer() (interface{} ,error)
}
type CommonLoginParam struct {
Package int `json:"package" form:"package"`
Channel string `json:"channel" form:"channel"`
UserId string `json:"userId" form:"userId"`
Account string `json:"account"`
}
var ServerCommonLoginParamPool = sync.Pool{
New: func() interface{} {
return new(CommonLoginParam)
}}
// 把对象放回缓冲池,减少GC
func reseCommonLoginParamtPool(CommonLoginParam *CommonLoginParam) {
ServerCommonLoginParamPool.Put(CommonLoginParam)
}
func Login(loginer Loginer) (interface{} ,error) {
if err:=loginer.Vaild();err !=nil {
return nil,err
}
return loginer.GetServer()
}
|
package main
import (
"bank.explorer/service/icbc"
"bank.explorer/util/dates"
"bank.explorer/common"
"strconv"
"bank.explorer/model"
"bank.explorer/config"
"bank.explorer/exception"
"bank.explorer/service"
)
func main() {
service.ConfigInit()
defer exception.Handle(true)
id ,_ := strconv.Atoi(config.JobList)
job := model.FindTask(id)
actId := job.GetAttrString("product_id")
cookie := job.GetAttrString("user_key")
common.Wait(job.GetAttrFloat("time_point"))
gift := icbc.InitG(cookie, actId)
i := 0
for i < 100 {
result := gift.RUN()
if result {
model.UpdateTask(job.GetAttrInt("id"), map[string]string {
"status": "3",
"result": "success",
})
break
}
dates.SleepSecond(5)
i++
}
model.UpdateTask(job.GetAttrInt("id"), map[string]string {
"status": "2",
"result": "failed",
})
}
|
package main
import (
"bufio"
"bytes"
"crypto/md5"
"io"
"math"
"os"
"sort"
"strconv"
"strings"
"time"
)
const (
// Number of records will reside in buffer memory until the next flush
BufferedRecordsLimit = 20
// Number of records log file can sustain
LogFileRecordLimit = BufferedRecordsLimit * 10
// Number of records in lsm base
LsmRecordLimitBase = LogFileRecordLimit * 10
KeyLength int = 16
IntLength int = 4
Int64Length int = 8
MBSize = 1024 * 1024
CopyBufferSize = 32 * 1024 // 32 Kb
MaxLevel = 7
WriteBufferSize = 4 * 1024 // 4 Kb
)
type (
metricKey string
// Write Format
// Column oriented records sorted by, key_name > time_stamp
// Header: [start_time][end_time][record_count][key_count]
// [key1][key2][key3]...
// [record_count(key1)][record_count(key2)][record_count(key3)]...
// [ts_k1_r1][ts_k1_r2][ts_k1_rn][ts_k2_r1][ts_k2_r2][ts_k2_rn]....
// [k1_r1_ln][k1_r2_ln][k1_rn_ln][k2_r1_ln][k2_r2_ln][k2_rn_ln]
// [k1_r1][k1_r2][k1_rn][k2_r1][k2_r2][k2_rn]
lsmFile struct {
metaInfo lsmMetaInfo
file interface {
io.ReadWriteCloser
io.Seeker
}
}
// Write Format
// [start_time][end_time][number_of_records]
lsmMetaInfo struct {
start, end int64
totalRecords int
keycount int
}
// Write Format
// [timestamp][key][length_of_value][value_bytes]
record struct {
ts int64
name string
value string
}
db struct {
logFile *os.File
logWriter bufio.Writer
lsmFiles, younglsmFiles []lsmFile
loggedBufferedRecords, logFileRecords int
manifest manifest
}
records []record
preSortedRecords [][]record
manifest struct {
levels int
compacting bool
}
)
func (m manifest) WriteTo(w io.Writer) {
if m.compacting {
m.levels &= 1
}
w.Write(intToBytes(m.levels))
}
func (m *manifest) ReadFrom(r io.Reader) {
var b = make([]byte, IntLength)
r.Read(b)
m.levels = bytesToint(b)
if m.levels&1 == 1 {
m.compacting = true
}
m.levels = (m.levels >> 1) << 1
}
func (m manifest) levelExists(level int) bool {
x := 1 << level
return m.levels&x == x
}
func (m *manifest) setLevel(level int) {
m.levels |= 1 << level
}
func (m *manifest) unsetLevel(level int) {
x := 1 << level
m.levels &= ^x
}
func (r records) Len() int {
return len(r)
}
func (r records) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
func (r records) Less(i, j int) bool {
return r[i].ts < r[j].ts
}
func (p preSortedRecords) Len() int {
return len(p)
}
func (r preSortedRecords) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
func (p preSortedRecords) Less(i, j int) bool {
return strings.Compare(p[i][0].name, p[j][0].name) == -1
}
func (m *lsmMetaInfo) ReadFrom(r io.Reader) {
var b [24]byte
_, err := r.Read(b[:])
if err != nil {
// Handling gracefully
}
m.start = bytesToint64(b[:8])
m.end = bytesToint64(b[8:16])
m.totalRecords = bytesToint(b[16:20])
m.keycount = bytesToint(b[20:])
}
func (m lsmMetaInfo) WriteTo(w io.Writer) {
w.Write(int64ToBytes(m.start))
w.Write(int64ToBytes(m.end))
w.Write(intToBytes(m.totalRecords))
w.Write(intToBytes(m.keycount))
}
// This is a naive approach for lsm record count
func lsmRecordCount(level int) int {
switch level {
case 0:
return LsmRecordLimitBase
default:
return LsmRecordLimitBase * level
}
}
func (m metricKey) Hash() []byte {
x := md5.Sum([]byte(m))
return x[:]
}
var cacheRecord []record
func bytesToint64(b []byte) int64 {
var c int64
for i := 0; i < 8; i++ {
c |= int64(b[i])
c <<= 8
}
return c
}
func bytesToint(b []byte) int {
var c int
for i := 0; i < 4; i++ {
c |= int(b[i])
c <<= 8
}
return c
}
func int64ToBytes(x int64) []byte {
var b [8]byte
var c int64
c = 1 << 8
c -= 1
for i := 0; i < 8; i++ {
b[i] = byte(x & c)
x >>= 8
}
return b[:]
}
func intToBytes(x int) []byte {
var b [4]byte
var c int
c = 1 << 8
c -= 1
for i := 0; i < 4; i++ {
b[i] = byte(x & c)
x >>= 8
}
return b[:]
}
func (r record) WriteTo(w io.Writer) {
mname := metricKey(r.name)
bts := int64ToBytes(r.ts)
lv := intToBytes(len(r.value))
w.Write(bts)
w.Write(mname.Hash())
w.Write(lv)
w.Write([]byte(r.value))
}
func (m *record) ReadFrom(r io.Reader) {
var b [28]byte
_, err := r.Read(b[:])
if err != nil {
// Handling gracefully
}
m.ts = bytesToint64(b[:8])
m.name = string(b[8:24])
lv := bytesToint(b[24:])
var bb = make([]byte, lv)
_, err = r.Read(bb)
if err != nil {
// Handling it gracefully
}
}
// Writes in DB are in row formats, in lsm file it will column based
// Log Entry Format
// Because there are no updates, timeseries database are append only
func (db *db) write(name, value string) {
r := record{ts: time.Now().Unix(), name: name, value: value}
r.WriteTo(&db.logWriter)
db.loggedBufferedRecords++
if db.loggedBufferedRecords == BufferedRecordsLimit {
err := db.logWriter.Flush()
if err != nil {
// Handle this properly
}
db.loggedBufferedRecords = 0 // Reseting the log records counter
db.logFileRecords += BufferedRecordsLimit
if db.logFileRecords == LogFileRecordLimit {
// It's time to push the data to lsm file
db.writeToLSM(0)
}
}
}
// writeToLSM will read the records from log file and will push them in lsm
// after sorting them
// for simplicity we will first make a level 0 lsm file w/o compactation
// capabilities
// level 0 is log file
//TODO Seperate file pointer while reading and writting from lsm file
func (db *db) writeToLSM(level int) {
// Lets read the records from log file
breader := bufio.NewReader(db.logFile)
var logRecords []record
for breader.Buffered() != 0 {
var r record
r.ReadFrom(breader)
logRecords = append(logRecords, r)
}
newFile := createNewFile()
defer newFile.Close()
buf := bufio.NewWriter(newFile)
writeLogFileInLsmFormat(sortLogFileRecords(logRecords), len(logRecords), buf) // This is a Level 0 File
defer buf.Flush()
}
func (db *db) compact() {
for level := 0; level < MaxLevel && needCompactation(db.lsmFiles[level].file, level); level++ {
levelExists := db.manifest.levelExists(level + 1)
if !levelExists {
db.lsmFiles[level+1].file = createNewFile()
}
newFile := createNewFile()
wr := bufio.NewWriterSize(newFile, WriteBufferSize)
mergeLSMFiles(db.lsmFiles[level].file, db.lsmFiles[level+1].file, wr)
wr.Flush() // Flushing to FS
db.lsmFiles[level+1].file = newFile
db.manifest.setLevel(level + 1)
db.manifest.unsetLevel(level)
}
}
func mergeLSMFiles(a, b io.ReadSeeker, wr io.Writer) {
var (
aH, bH, newHeader, oldHeader lsmMetaInfo
new, old io.ReadSeeker
)
a.Seek(0, 0)
b.Seek(0, 0)
aH.ReadFrom(a)
bH.ReadFrom(b)
if aH.end < bH.end {
new = a
old = b
newHeader = aH
oldHeader = bH
} else {
new = b
old = a
newHeader = bH
oldHeader = aH
}
destHeader := lsmMetaInfo{start: oldHeader.start,
end: newHeader.end, totalRecords: newHeader.totalRecords + oldHeader.totalRecords}
var m = make(map[string][4]int)
var oldkeyb = make([]byte, (KeyLength+IntLength)*oldHeader.keycount)
old.Read(oldkeyb)
olastKeyAddr := KeyLength * oldHeader.keycount
for i := 0; i < oldHeader.keycount; i++ {
start := i * KeyLength
k := oldkeyb[start : start+KeyLength]
x := olastKeyAddr + i*IntLength
c := bytesToint(oldkeyb[x : x+IntLength])
m[string(k)] = [4]int{-1, i, c, 0}
}
var newkeyb = make([]byte, (KeyLength+IntLength)*newHeader.keycount)
new.Read(newkeyb)
nlastKeyAddr := KeyLength * newHeader.keycount
for i := 0; i < newHeader.keycount; i++ {
start := i * KeyLength
k := newkeyb[start : start+KeyLength]
x := nlastKeyAddr + i*IntLength
c := bytesToint(newkeyb[x : x+IntLength])
v, ok := m[string(k)]
if ok {
v[0] = i
v[3] = c
} else {
v = [4]int{i, -1, 0, c}
}
m[string(k)] = v
}
var ks = make(keys, 0, len(m))
i := 0
for k := range m {
ks[i] = key{key: k, new: m[k][0], old: m[k][1], orecords: m[k][2], nrecords: m[k][3]}
i++
}
sort.Sort(ks)
destHeader.keycount = len(m)
destHeader.WriteTo(wr) // Writting header
// Let's merge these files
for v := range ks { // Writting keys
wr.Write([]byte(ks[v].key))
}
for v := range ks { // Writting Values Count
wr.Write(intToBytes(ks[v].orecords + ks[v].nrecords))
}
copyBuffer := make([]byte, CopyBufferSize)
oseekIndex := (2*(IntLength+Int64Length) + (KeyLength+IntLength)*oldHeader.keycount)
nseekIndex := (2*(IntLength+Int64Length) + (KeyLength+IntLength)*newHeader.keycount)
for _, v := range ks { // Writting timestamp values
o := v.old
n := v.new
if o > -1 {
old.Seek(io.SeekStart, oseekIndex+o*Int64Length)
io.CopyBuffer(wr, io.LimitReader(old, int64(v.orecords)*int64(Int64Length)), copyBuffer)
}
if n > -1 {
new.Seek(io.SeekStart, nseekIndex+n*Int64Length)
io.CopyBuffer(wr, io.LimitReader(new, int64(v.nrecords)*int64(Int64Length)), copyBuffer)
}
}
oseekIndex += oldHeader.totalRecords * Int64Length
nseekIndex += newHeader.totalRecords * Int64Length
maxLength := 0
for i := range ks {
sum := ks[i].nrecords + ks[i].orecords
if maxLength < sum {
maxLength = sum
}
}
bf := bytes.NewBuffer(make([]byte, maxLength*IntLength))
for _, v := range ks { // Writting values lengths
o := v.old
n := v.new
if o > -1 {
old.Seek(io.SeekStart, oseekIndex+o*IntLength)
io.CopyBuffer(io.MultiWriter(bf, wr), io.LimitReader(old, int64(v.orecords)*int64(IntLength)), copyBuffer)
}
if n > -1 {
new.Seek(io.SeekStart, nseekIndex+n*IntLength)
io.CopyBuffer(io.MultiWriter(bf, wr), io.LimitReader(new, int64(v.nrecords)*int64(IntLength)), copyBuffer)
}
buf := make([]byte, IntLength)
for i := 0; i < v.orecords; i++ {
b.Read(buf)
v.osum += bytesToint(buf)
}
for i := 0; i < v.nrecords; i++ {
b.Read(buf)
v.nsum += bytesToint(buf)
}
}
oseekIndex += oldHeader.totalRecords * IntLength
nseekIndex += newHeader.totalRecords * IntLength
for _, v := range ks { // Writting values
o := v.old
n := v.new
if o > -1 {
old.Seek(io.SeekStart, oseekIndex+o*Int64Length)
io.CopyBuffer(wr, io.LimitReader(old, int64(v.osum)), copyBuffer)
}
if n > -1 {
new.Seek(io.SeekStart, nseekIndex+n*Int64Length)
io.CopyBuffer(wr, io.LimitReader(new, int64(v.nsum)), copyBuffer)
}
}
}
type key struct {
key string
old, new, orecords, nrecords, osum, nsum int
}
type keys []key
func (k keys) Less(i, j int) bool {
return strings.Compare(k[i].key, k[j].key) == -1
}
func (k keys) Swap(i, j int) {
k[i], k[j] = k[j], k[i]
}
func (k keys) Len() int {
return len(k)
}
// Writes log file data into lsm file format
func writeLogFileInLsmFormat(recrodsToaadd [][]record, length int, wr io.Writer) {
first := recrodsToaadd[0][0]
l := recrodsToaadd[len(recrodsToaadd)-1]
last := recrodsToaadd[len(recrodsToaadd)-1][len(l)-1]
var header = lsmMetaInfo{start: first.ts,
end: last.ts,
keycount: len(recrodsToaadd),
totalRecords: length}
header.WriteTo(wr) // Writting
for i := range recrodsToaadd { // Writting Keys
wr.Write([]byte(recrodsToaadd[i][0].name))
}
for i := range recrodsToaadd { // Writting Value Length
l := len(recrodsToaadd[i])
wr.Write(intToBytes(l))
}
for i := range recrodsToaadd { // Writting Timestamp
for ii := range recrodsToaadd[i] {
wr.Write(int64ToBytes(recrodsToaadd[i][ii].ts))
}
}
for i := range recrodsToaadd { // Writting Length Values
for ii := range recrodsToaadd[i] {
wr.Write(intToBytes(len(recrodsToaadd[i][ii].value)))
}
}
for i := range recrodsToaadd { // Writting Values
for ii := range recrodsToaadd[i] {
wr.Write([]byte(recrodsToaadd[i][ii].value))
}
}
}
func sortLogFileRecords(rds []record) [][]record {
var m = make(map[string][]record)
for i := range rds {
m[rds[i].name] = append(m[rds[i].name], rds[i])
}
var mm = make([][]record, len(m))
i := 0
for k := range m {
rs := records(m[k])
sort.Sort(rs)
mm[i] = rs
i++
}
mmp := preSortedRecords(mm)
sort.Sort(mmp)
return [][]record(mm)
}
func needCompactation(seeker io.Seeker, level int) bool {
beg, _ := seeker.Seek(io.SeekStart, 0)
end, _ := seeker.Seek(io.SeekEnd, 0)
size := end - beg + 1
return size > int64(math.Pow10(level))*MBSize
}
func createNewFile() *os.File {
name := strconv.FormatInt(time.Now().Unix(), 6)
//TODO Handle Error
b := md5.Sum([]byte(name))
f, _ := os.Create(string(b[:]))
return f
}
|
package hello
import (
"github.com/gin-gonic/gin"
"github.com/go-conflict/toolkit"
"net/http"
)
func sayHello(c *gin.Context) {
toolkit.SetJson(c, http.StatusOK, "hello go-conflict", nil)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.