text stringlengths 11 4.05M |
|---|
package solutions
type Deque struct {
indexes []int
}
func (deque *Deque) push(i int) {
deque.indexes = append(deque.indexes, i)
}
func (deque *Deque) getFirst() int {
return deque.indexes[0]
}
func (deque *Deque) popFirst() {
deque.indexes = deque.indexes[1:]
}
func (deque *Deque) getLast() int {
return deque.indexes[len(deque.indexes) - 1]
}
func (deque *Deque) popLast() {
deque.indexes = deque.indexes[:len(deque.indexes) - 1]
}
func (deque *Deque) empty() bool {
return len(deque.indexes) == 0
}
func maxSlidingWindow(nums []int, k int) []int {
if len(nums) < k || k == 0 {
return make([]int, 0)
} else if 1 == k {
return nums
}
result := make([]int, len(nums) - k + 1)
deque := &Deque{}
for i := range nums {
if !deque.empty() && (i - k == deque.getFirst()) {
deque.popFirst()
}
for !deque.empty() && nums[deque.getLast()] < nums[i] {
deque.popLast()
}
deque.push(i)
if i >= k - 1 {
result[i - k + 1] = nums[deque.getFirst()]
}
}
return result
} |
package main
import "testing"
type tuple struct {
p, q string
}
func TestWithoutRepetitions(t *testing.T) {
for k, v := range map[tuple]tuple{
tuple{"a", "b"}: tuple{"b", "b"},
tuple{"a", "a"}: tuple{"a", ""},
tuple{"\n", " "}: tuple{" ", " "}} {
if rp, rq := withoutRepetitions(k.p, k.q); rp != v.p || rq != v.q {
t.Errorf("failed: withoutRepetitions %s %s is %s %s, got %s %s",
k.p, k.q, v.p, v.q, rp, rq)
}
}
}
func withoutRepetitions(p, q string) (string, string) {
if p != q {
return q, q
}
return p, ""
}
|
package app
import (
"fmt"
"time"
"bitbucket.com/barrettbsi/broadvid-adscoops-shared/structs"
)
var campaignsCache = make(map[uint]CacheCampaign)
type CacheCampaign struct {
LastUpdated time.Time
Campaigns []CacheCampaignLayout
ActiveCampaigns []CacheCampaignLayout
InactiveCampaigns []CacheCampaignLayout
PausedCampaigns []CacheCampaignLayout
}
type CacheCampaignLayout struct {
structs.AdscoopCampaign
Impressions string
Engagements string
Loads string
ImpressionsRaw uint
EngagementsRaw uint
LoadsRaw uint
Class string
DisplayImps string
}
func setupCampaignCaches() {
var clients []structs.AdscoopClient
db.Where("enable_client_login = 1").Find(&clients)
for _, c := range clients {
createCampaignCache(c.ID)
}
}
func createCampaignCache(clientid uint) {
var wsData struct {
Type string
Timestamp time.Time
}
tmpcc := CacheCampaign{}
location, _ := time.LoadLocation("America/Los_Angeles")
today := time.Now()
today = today.In(location)
wsData.Timestamp = today
tmpcc.LastUpdated = today
today = time.Date(today.Year(),
today.Month(),
today.Day(), 0, 0, 0, 0, location)
today = today.In(time.UTC)
db.LogMode(true).Select("adscoop_campaigns.id, adscoop_campaigns.name, adscoop_campaigns.campaign_group_weight, adscoop_campaigns.tracking_method, adscoop_campaigns.daily_imps_limit, adscoop_campaigns.paused, SUM(impressions.c) as impressions_raw, SUM(engagements.c) as engagements_raw, SUM(loads.c) as loads_raw, FORMAT(SUM(impressions.c),0) as impressions, FORMAT(SUM(engagements.c),0) as engagements, FORMAT(SUM(loads.c),0) as loads").
Table("adscoop_campaigns").
Joins(fmt.Sprintf(`LEFT OUTER JOIN adscoop_urls ON adscoop_urls.campaign_id = adscoop_campaigns.id
LEFT OUTER JOIN (SELECT SUM(adscoop_trackings.count) as c, url_id FROM adscoop_trackings WHERE timeslice >= '%s' GROUP BY url_id) as impressions ON impressions.url_id = adscoop_urls.id
LEFT OUTER JOIN (SELECT SUM(adscoop_trackings.engagement) as c, url_id FROM adscoop_trackings WHERE timeslice >= '%s' GROUP BY url_id) as engagements ON engagements.url_id = adscoop_urls.id
LEFT OUTER JOIN (SELECT SUM(adscoop_trackings.load) as c, url_id FROM adscoop_trackings WHERE timeslice >= '%s' GROUP BY url_id) as loads ON loads.url_id = adscoop_urls.id`,
today.Format(TimeLayout), today.Format(TimeLayout), today.Format(TimeLayout))).
Where("adscoop_campaigns.client_id = ? AND inactive = 0", clientid).
Order("paused asc").
Group("adscoop_campaigns.id").
Find(&tmpcc.Campaigns)
for _, x := range tmpcc.Campaigns {
x.Class = "success"
if (x.TrackingMethod == 0 && x.DailyImpsLimit <= x.ImpressionsRaw) ||
(x.TrackingMethod == 1 && x.DailyImpsLimit <= x.EngagementsRaw) ||
(x.TrackingMethod == 2 && x.DailyImpsLimit <= x.LoadsRaw) {
x.Class = "default"
tmpcc.InactiveCampaigns = append(tmpcc.InactiveCampaigns, x)
continue
}
if x.Paused {
x.Class = "danger"
tmpcc.PausedCampaigns = append(tmpcc.PausedCampaigns, x)
continue
}
tmpcc.ActiveCampaigns = append(tmpcc.ActiveCampaigns, x)
}
campaignsCache[clientid] = tmpcc
wsData.Type = "campaigns"
broadcastJson(wsData, fmt.Sprintf("%v", clientid))
}
|
// 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 scanapp
import (
"context"
"chromiumos/tast/local/bundles/cros/scanapp/scanning"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/uiauto/scanapp"
"chromiumos/tast/testing"
"chromiumos/tast/testing/hwdep"
)
func init() {
testing.AddTest(&testing.Test{
Func: Scan,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Tests that the Scan app can be used to perform scans",
Contacts: []string{
"cros-peripherals@google.com",
"project-bolton@google.com",
},
Attr: []string{
"group:mainline",
"informational",
"group:paper-io",
"paper-io_scanning",
},
SoftwareDeps: []string{"chrome", "virtual_usb_printer"},
// TODO(b/202847398): Skip sona devices due to abnormal failures.
HardwareDeps: hwdep.D(hwdep.SkipOnModel("sona")),
Fixture: "virtualUsbPrinterModulesLoadedWithChromeLoggedIn",
Data: []string{
scanning.SourceImage,
pngGoldenFile,
jpgGoldenFile,
pdfGoldenFile,
},
})
}
const (
pngGoldenFile = "flatbed_png_color_letter_300_dpi.png"
jpgGoldenFile = "adf_simplex_jpg_grayscale_a4_150_dpi.jpg"
pdfGoldenFile = "adf_duplex_pdf_grayscale_max_300_dpi.pdf"
)
var scanTests = []scanning.TestingStruct{
{
Name: "flatbed_png_color_letter_300_dpi",
Settings: scanapp.ScanSettings{
Source: scanapp.SourceFlatbed,
FileType: scanapp.FileTypePNG,
ColorMode: scanapp.ColorModeColor,
PageSize: scanapp.PageSizeLetter,
Resolution: scanapp.Resolution300DPI,
},
GoldenFile: pngGoldenFile,
}, {
Name: "adf_simplex_jpg_grayscale_a4_150_dpi",
Settings: scanapp.ScanSettings{
Source: scanapp.SourceADFOneSided,
FileType: scanapp.FileTypeJPG,
// TODO(b/181773386): Change this to black and white when the virtual
// USB printer correctly reports the color mode.
ColorMode: scanapp.ColorModeGrayscale,
PageSize: scanapp.PageSizeA4,
Resolution: scanapp.Resolution150DPI,
},
GoldenFile: jpgGoldenFile,
}, {
Name: "adf_duplex_pdf_grayscale_max_300_dpi",
Settings: scanapp.ScanSettings{
Source: scanapp.SourceADFTwoSided,
FileType: scanapp.FileTypePDF,
ColorMode: scanapp.ColorModeGrayscale,
PageSize: scanapp.PageSizeFitToScanArea,
Resolution: scanapp.Resolution300DPI,
},
GoldenFile: pdfGoldenFile,
},
}
func Scan(ctx context.Context, s *testing.State) {
cr := s.FixtValue().(*chrome.Chrome)
var scannerParams = scanning.ScannerStruct{
Descriptors: scanning.Descriptors,
Attributes: scanning.Attributes,
EsclCaps: scanapp.EsclCapabilities,
}
scanning.RunAppSettingsTests(ctx, s, cr, scanTests, scannerParams)
}
|
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/nu7hatch/gouuid"
"github.com/surma/httptools"
)
const (
Width = 600
Height = 600
)
type jobMap struct {
Map map[string]*job
sync.RWMutex
}
var jobs = &jobMap{
Map: map[string]*job{},
}
func main() {
var (
listen = flag.String("listen", "localhost:5000", "Address to bind webserver to")
static = flag.String("static", "./static", "Path to static folder")
)
flag.Parse()
log.Printf("Starting webserver on %s...", *listen)
err := http.ListenAndServe(*listen, httptools.NewRegexpSwitch(map[string]http.Handler{
"/jobs": httptools.MethodSwitch{
"GET": http.HandlerFunc(listJobs),
"POST": http.HandlerFunc(createJob),
},
"/jobs/[0-9a-f-]+": httptools.List{
httptools.DiscardPathElements(1),
httptools.SilentHandlerFunc(extractJobId),
httptools.MethodSwitch{
"GET": http.HandlerFunc(showJob),
"DELETE": http.HandlerFunc(deleteJob),
},
},
"/images/[0-9a-f-]+": httptools.List{
httptools.DiscardPathElements(1),
httptools.SilentHandlerFunc(extractJobId),
httptools.MethodSwitch{
"GET": http.HandlerFunc(listImages),
},
},
"/images/[0-9a-f-]+/[^/]+": httptools.List{
httptools.DiscardPathElements(1),
httptools.SilentHandlerFunc(extractJobId),
httptools.DiscardPathElements(1),
httptools.SilentHandlerFunc(extractImageId),
httptools.MethodSwitch{
"GET": http.HandlerFunc(serveImage),
"DELETE": http.HandlerFunc(deleteImage),
},
},
"/": http.FileServer(http.Dir(*static)),
}))
if err != nil {
log.Fatalf("Error starting webserver on %s: %s", *listen, err)
}
}
func extractJobId(w http.ResponseWriter, r *http.Request) {
parts := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)
valid := false
func() {
jobs.RLock()
defer jobs.RUnlock()
_, valid = jobs.Map[parts[0]]
}()
if !valid {
ErrorWithMessage(w, http.StatusNotFound)
return
}
r.Header.Set("X-Job-ID", parts[0])
}
func extractImageId(w http.ResponseWriter, r *http.Request) {
parts := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)
jobId := r.Header.Get("X-Job-ID")
var j *job
func() {
jobs.RLock()
defer jobs.RUnlock()
j = jobs.Map[jobId]
}()
_, ok := j.Compositions[parts[0]]
if !ok {
ErrorWithMessage(w, http.StatusNotFound)
return
}
r.Header.Set("X-Image-ID", parts[0])
}
func createJob(w http.ResponseWriter, r *http.Request) {
j := &job{
ID: NewUUID(),
Start: time.Now(),
Compositions: map[string][]byte{},
}
err := json.NewDecoder(r.Body).Decode(j)
if err != nil {
ErrorWithMessage(w, http.StatusBadRequest)
log.Printf("Error parsing body: %s", err)
return
}
go j.run()
func() {
jobs.Lock()
defer jobs.Unlock()
jobs.Map[j.ID] = j
}()
http.Error(w, j.ID, http.StatusCreated)
}
func listJobs(w http.ResponseWriter, r *http.Request) {
var list []string
func() {
jobs.RLock()
defer jobs.RUnlock()
list = make([]string, 0, len(jobs.Map))
for key := range jobs.Map {
list = append(list, key)
}
}()
json.NewEncoder(w).Encode(map[string]interface{}{"result": list})
}
func showJob(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Job-ID")
var j *job
func() {
jobs.RLock()
defer jobs.RUnlock()
j = jobs.Map[id]
}()
json.NewEncoder(w).Encode(j)
}
func deleteJob(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Job-ID")
func() {
jobs.Lock()
defer jobs.Unlock()
delete(jobs.Map, id)
}()
ErrorWithMessage(w, http.StatusNoContent)
}
func listImages(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Job-ID")
var j *job
func() {
jobs.RLock()
defer jobs.RUnlock()
j = jobs.Map[id]
}()
list := make([]string, 0, len(j.Compositions))
for key := range j.Compositions {
list = append(list, key)
}
json.NewEncoder(w).Encode(list)
}
func serveImage(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Job-ID")
var j *job
func() {
jobs.RLock()
defer jobs.RUnlock()
j = jobs.Map[id]
}()
img := j.Compositions[r.Header.Get("X-Image-ID")]
w.Header().Set("Content-Type", "image/png")
w.Write(img)
}
func deleteImage(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Job-ID")
var j *job
func() {
jobs.RLock()
defer jobs.RUnlock()
j = jobs.Map[id]
}()
delete(j.Compositions, r.Header.Get("X-Image-ID"))
ErrorWithMessage(w, http.StatusNoContent)
}
func ErrorWithMessage(w http.ResponseWriter, code int) {
http.Error(w, http.StatusText(code), code)
}
func NewUUID() string {
id, err := uuid.NewV4()
if err != nil {
panic(err)
}
return id.String()
}
|
package limitrange
import (
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/informers"
listers "k8s.io/client-go/listers/core/v1"
)
// Calculator 计算容器或POD的资源量限制
type Calculator interface {
// GetContainerLimitRangeItem 获取指定命令空间下的容器资源量限制
GetContainerLimitRangeItem(namespace string) (*corev1.LimitRangeItem, error)
// GetPodLimitRangeItem 获取指定命名空间下的POD资源量限制
GetPodLimitRangeItem(namespace string) (*corev1.LimitRangeItem, error)
}
type limitCalculator struct {
limitRangeLister listers.LimitRangeLister
}
// GetContainerLimitRangeItem 获取指定命令空间下的容器资源量限制
func (l *limitCalculator) GetContainerLimitRangeItem(namespace string) (*corev1.LimitRangeItem, error) {
return l.getLimitRangeItem(namespace, corev1.LimitTypeContainer)
}
// GetPodLimitRangeItem 获取指定命名空间下的POD资源量限制
func (l *limitCalculator) GetPodLimitRangeItem(namespace string) (*corev1.LimitRangeItem, error) {
return l.getLimitRangeItem(namespace, corev1.LimitTypePod)
}
// NewCalculator 返回一个新的 limit range Calculator
func NewCalculator(factory informers.SharedInformerFactory) (Calculator, error) {
if factory == nil {
return nil, fmt.Errorf("NewLimitRangeCalculator required a SharedInformerFactory but got nil")
}
limitRangeLister := factory.Core().V1().LimitRanges().Lister()
// 需要等待informer的store中同步得到limitrange 数据
stopCh := make(chan struct{})
factory.Start(stopCh)
for _, ok := range factory.WaitForCacheSync(stopCh) {
if !ok && !factory.Core().V1().LimitRanges().Informer().HasSynced() {
return nil, fmt.Errorf("infromer did not synced")
}
}
return &limitCalculator{limitRangeLister: limitRangeLister}, nil
}
func (l *limitCalculator) getLimitRangeItem(namespace string, resourceType corev1.LimitType) (*corev1.LimitRangeItem, error) {
limitRanges, err := l.limitRangeLister.LimitRanges(namespace).List(labels.Everything())
if err != nil {
return nil, fmt.Errorf("cannot loading limitRanges from namespace(%v): %v", namespace, err)
}
targetLimitRangeItem := &corev1.LimitRangeItem{Type: resourceType}
for _, limitRange := range limitRanges {
for _, limitItem := range limitRange.Spec.Limits {
if limitItem.Type == resourceType && (limitItem.Min != nil || limitItem.Max != nil || limitItem.Default != nil) {
if limitItem.Default != nil {
targetLimitRangeItem.Default = limitItem.Default
}
// 更新 CPU 的最大下界
targetLimitRangeItem.Min = updateResource(targetLimitRangeItem.Min, limitItem.Min, corev1.ResourceCPU, chooseMaxLowerBound)
// 更新 memory 的最大下界
targetLimitRangeItem.Min = updateResource(targetLimitRangeItem.Min, limitItem.Min, corev1.ResourceMemory, chooseMaxLowerBound)
// 更新 CPU 的最小上界
targetLimitRangeItem.Max = updateResource(targetLimitRangeItem.Max, limitItem.Max, corev1.ResourceCPU, chooseMinUpperBound)
// 更新 memory 的最小上界
targetLimitRangeItem.Max = updateResource(targetLimitRangeItem.Max, limitItem.Max, corev1.ResourceMemory, chooseMinUpperBound)
}
}
}
if targetLimitRangeItem.Max != nil || targetLimitRangeItem.Min != nil || targetLimitRangeItem.Default != nil {
return targetLimitRangeItem, nil
}
return nil, nil
}
// updateResource 更新dst的资源配额
// 使用selector自定义选择dst和src中更合适的资源(resourceName)
func updateResource(dst, src corev1.ResourceList,
resourceName corev1.ResourceName,
selector func(a, b resource.Quantity) resource.Quantity) corev1.ResourceList {
if src == nil {
return dst
}
if dst == nil {
return src.DeepCopy()
}
if srcResource, srcOk := src[resourceName]; srcOk {
dstResource, dstOk := dst[resourceName]
if dstOk {
dst[resourceName] = selector(dstResource, srcResource)
} else {
dst[resourceName] = srcResource.DeepCopy()
}
}
return dst
}
// chooseMinUpperBound 选择资源上界(选择最小的上界)
// 满足所有资源约束
func chooseMinUpperBound(a, b resource.Quantity) resource.Quantity {
if a.Cmp(b) < 0 {
return a
}
return b
}
// chooseMaxLowerBound 选择资源下界(选择最大的下界)
// 满足所有资源约束
func chooseMaxLowerBound(a, b resource.Quantity) resource.Quantity {
if a.Cmp(b) > 0 {
return a
}
return b
}
|
/***** Partie messageDB.go : structure du message et gestion de la base de données *****/
package db
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3" // Importation de librairie permettant d'utiliser SQlite, To install : go get github.com/mattn/go-sqlite3
)
/*** Constantes pour l'utilisation de la base de données ***/
const cheminFichierDB = "./db/chat.db"
const typeSql = "sqlite3"
/*** Structure du type Message ***/
type Message struct {
Contenu string `json:"contenu"` //Le contenu du message
Date string `json:"date"` //La date du message
Salon string `json:"salon"` //Le salon auquel est destiné le message
Createur string `json:"createur"` //L'expéditeur du message
Mail string `json:"mail"` //Le mail de l'expéditeur
Type string `json:"type"` //Le type du message permettant la gestion de l'interface graphique coté client (cf client.js)
}
/*** "Constructeur" du type Message ***/
func New(contenu string, date string, salon string, createur string, mail string, typeMessage string) *Message {
return &Message{contenu, date, salon, createur, mail, typeMessage}
}
/*** Fonction d'affichage ***/
func (m *Message) Print() {
fmt.Println("Contenu : " + m.Contenu + "\nDate : " + m.Date + "\nSalon : " + m.Salon + "\nCreateur : " + m.Createur + "\nMail : " + m.Mail + "\nType : " + m.Type + "\n")
}
/*** Fonction ToString pour retourné l'objet sous forme de chaines de caractères ***/
func (m *Message) ToString() string {
return "{" + m.Contenu + "," + m.Date + "," + m.Salon + "," + m.Createur + "," + m.Mail + "," + m.Type + "}"
}
/*** Fonction permettant l'ajout du message en base de données ***/
func (m *Message) AddMessage() (int, error) {
db, err := sql.Open(typeSql, cheminFichierDB) //Ouverture du fichier .db
defer db.Close() //N'oublions pas la fermeture !
if err != nil {
return 0, err
}
//Préparation de la requête
stmt, err := db.Prepare("INSERT INTO message(contenuMessage,dateHeureMessage,nomSalonMessage,createurMessage,mailGravatarMessage) VALUES (?,?,?,?,?)")
if err != nil {
return 0, err
}
//Exécution de la requête avec la liste des données du message
res, err := stmt.Exec(m.Contenu, m.Date, m.Salon, m.Createur, m.Mail)
if err != nil {
return 0, err
}
//On récupère le nombre de tuples affectés
nb, err := res.RowsAffected()
if err != nil {
return 0, err
}
//on retourne ce nombre
return int(nb), nil
}
/*** Fonction permettant la suppression des messages en fonction du salon en base de données ***/
func DeleteMessageBySalon(salon string) (int, error) {
db, err := sql.Open(typeSql, cheminFichierDB)
defer db.Close()
if err != nil {
return 0, err
}
stmt, err := db.Prepare("DELETE FROM message WHERE nomSalonMessage = ?")
if err != nil {
return 0, err
}
res, err := stmt.Exec(salon)
if err != nil {
return 0, err
}
nb, err := res.RowsAffected()
if err != nil {
return 0, err
}
return int(nb), nil
}
/*** Fonction permettant de supprimer tous les messages stockes dans la base de donnees***/
func DeleteAllMessages() (int, error) {
db, err := sql.Open(typeSql, cheminFichierDB)
defer db.Close()
if err != nil {
return 0, err
}
stmt, err := db.Prepare("DELETE FROM message")
if err != nil {
return 0, err
}
res, err := stmt.Exec()
if err != nil {
return 0, err
}
nb, err := res.RowsAffected()
if err != nil {
return 0, err
}
return int(nb), nil
}
/*** Fonction permettant l'obtention des messages en fonction du salon en base de données ***/
func GetMessagesBySalon(salon string) ([]*Message, error) {
var messages []*Message
db, err := sql.Open(typeSql, cheminFichierDB)
defer db.Close()
if err != nil {
return nil, err
}
stmt, err := db.Prepare("SELECT * FROM message m WHERE m.nomSalonMessage = ? ORDER BY datetime(m.dateHeureMessage) ASC")
if err != nil {
return nil, err
}
//On récupère les tuples affectés
rows, err := stmt.Query(salon)
if err != nil {
return nil, err
}
//Création des variables pour récupérer les données de chaque tuple
var idMessage int
var contenuMessage string
var dateHeureMessage string
var nomSalonMessage string
var createurMessage string
var mailGravatarMessage string
//On parcourt les tuples
for rows.Next() {
//Pour chaque tuple, on fait correspondre les données avec les variables crées précédemment
err = rows.Scan(&idMessage, &contenuMessage, &dateHeureMessage, &nomSalonMessage, &createurMessage, &mailGravatarMessage)
if err != nil {
return nil, err
}
//On ajoute une instance créer à partir du contenu des variables dans la liste des messages à retourner
messages = append(messages, &Message{contenuMessage, dateHeureMessage, nomSalonMessage, createurMessage, mailGravatarMessage, ""})
}
return messages, nil
}
/*** Fonction permettant l'obtention d'un historique de tous les utilisateurs du chat en base de données ***/
func GetUsers() string {
var users string
users = ""
db, err := sql.Open(typeSql, cheminFichierDB)
defer db.Close()
if err != nil {
return ""
}
stmt, err := db.Prepare("SELECT DISTINCT m.createurMessage FROM message m ORDER BY m.createurMessage ASC")
if err != nil {
return ""
}
rows, err := stmt.Query()
if err != nil {
return ""
}
var createurMessage string
for rows.Next() {
err = rows.Scan(&createurMessage)
if err != nil {
return ""
}
users += createurMessage + " "
}
return users
}
|
package ccaddrepo
import (
"embed"
"io/fs"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
//go:embed fixtures
var fixtureRootFS embed.FS
var fixtureFS, _ = fs.Sub(fixtureRootFS, "fixtures")
func TestPlaceHolder(t *testing.T) {
content, err := fs.ReadFile(fixtureFS, "placeholder")
if assert.NoError(t, err) {
assert.Equal(t, "this is a placeholder", string(content))
}
}
func TestSetReporterIDSecret(t *testing.T) {
cctoken, ok := os.LookupEnv("GH_WORKFLOW")
if !ok {
t.Fatalf("\nTO RUN THIS TEST, DECLARE A GH_WORKFLOW ENV VAR WITH A GITHUB API TOKEN\n")
}
err := SetReporterIDSecret(SecretsOptions{
RepoSlug: "parrogo/ccaddrepo",
GHToken: cctoken,
ReporterID: "42",
BadgeID: "43",
ID: "44",
})
if assert.NoError(t, err) {
assert.Equal(t, nil, err)
}
}
func TestGetRepoID(t *testing.T) {
cctoken, ok := os.LookupEnv("CC_TOKEN")
if !ok {
t.Fatalf("\nTO RUN THIS TEST, DECLARE A CC_TOKEN ENV VAR WITH A GITHUB API TOKEN\n")
}
cc := CodeClimate(cctoken)
t.Run("check this repo ID", func(t *testing.T) {
ID, err := cc.GetRepoID("parrogo/ccaddrepo")
if assert.NoError(t, err) {
assert.Equal(t, "606b6ca958f8666dcc00a693", ID)
}
})
}
func TestAddRepo(t *testing.T) {
cctoken, ok := os.LookupEnv("CC_TOKEN")
if !ok {
t.Fatalf("\nTO RUN THIS TEST, DECLARE A CC_TOKEN ENV VAR WITH A GITHUB API TOKEN\n")
}
cc := CodeClimate(cctoken)
t.Run("check centro", func(t *testing.T) {
ID, err := cc.GetRepoID("parrogo/centro")
if err == nil {
err = cc.DeleteRepo(ID)
if !assert.NoError(t, err) {
return
}
}
repo, err := cc.AddRepo("parrogo/centro")
if !assert.NoError(t, err) {
return
}
assert.Greater(t, len(repo.Data.ID), 10)
assert.Greater(t, len(repo.Data.Attributes.BadgeTokenID), 10)
assert.Greater(t, len(repo.Data.Attributes.TestReporterID), 10)
})
}
func TestDeleteRepo(t *testing.T) {
cctoken, ok := os.LookupEnv("CC_TOKEN")
if !ok {
t.Fatalf("\nTO RUN THIS TEST, DECLARE A CC_TOKEN ENV VAR WITH A GITHUB API TOKEN\n")
}
cc := CodeClimate(cctoken)
t.Run("check centro", func(t *testing.T) {
ID, err := cc.GetRepoID("parrogo/centro")
if err != nil && err.Error() == "repository not found: parrogo/centro" {
_, err := cc.AddRepo("parrogo/centro")
if !assert.NoError(t, err) {
return
}
}
if !assert.NoError(t, err) {
return
}
assert.NoError(t, cc.DeleteRepo(ID))
})
}
func TestGetOwnOrgID(t *testing.T) {
cctoken, ok := os.LookupEnv("CC_TOKEN")
if !ok {
t.Fatalf("\nTO RUN THIS TEST, DECLARE A CC_TOKEN ENV VAR WITH A GITHUB API TOKEN\n")
}
cc := CodeClimate(cctoken)
t.Run("check wrong org name", func(t *testing.T) {
ID, err := cc.GetOwnOrgID("nonexistentorg")
if assert.Error(t, err) {
assert.Equal(t, "", ID)
}
})
t.Run("check parrogo ID", func(t *testing.T) {
ID, err := cc.GetOwnOrgID("parrogo")
if assert.NoError(t, err) {
assert.Equal(t, "606ddb6085fc77593c001ec5", ID)
}
})
t.Run("check parro-it ID", func(t *testing.T) {
ID, err := cc.GetOwnOrgID("parro-it")
if assert.NoError(t, err) {
assert.Equal(t, "5610f3b56956806eff013739", ID)
}
})
}
|
package coerce
import (
"github.com/project-flogo/core/data/coerce"
"github.com/project-flogo/core/data/expression/function"
)
func init() {
function.Register(&fnToString{})
function.Register(&fnToInt{})
function.Register(&fnToInt32{})
function.Register(&fnToInt64{})
function.Register(&fnToFloat32{})
function.Register(&fnToFloat64{})
function.Register(&fnToBool{})
function.Register(&fnToBytes{})
}
type fnToString struct {
*baseFn
}
func (*fnToString) Name() string {
return "toString"
}
func (*fnToString) Eval(params ...interface{}) (interface{}, error) {
return coerce.ToString(params[0])
}
type fnToInt struct {
*baseFn
}
func (*fnToInt) Name() string {
return "toInt"
}
func (*fnToInt) Eval(params ...interface{}) (interface{}, error) {
return coerce.ToInt(params[0])
}
type fnToInt32 struct {
*baseFn
}
func (*fnToInt32) Name() string {
return "toInt32"
}
func (*fnToInt32) Eval(params ...interface{}) (interface{}, error) {
return coerce.ToInt32(params[0])
}
type fnToInt64 struct {
*baseFn
}
func (*fnToInt64) Name() string {
return "toInt64"
}
func (*fnToInt64) Eval(params ...interface{}) (interface{}, error) {
return coerce.ToInt64(params[0])
}
type fnToFloat32 struct {
*baseFn
}
func (*fnToFloat32) Name() string {
return "toFloat32"
}
func (*fnToFloat32) Eval(params ...interface{}) (interface{}, error) {
return coerce.ToFloat32(params[0])
}
type fnToFloat64 struct {
*baseFn
}
func (*fnToFloat64) Name() string {
return "toFloat64"
}
func (*fnToFloat64) Eval(params ...interface{}) (interface{}, error) {
return coerce.ToFloat64(params[0])
}
type fnToBool struct {
*baseFn
}
func (*fnToBool) Name() string {
return "toBool"
}
func (*fnToBool) Eval(params ...interface{}) (interface{}, error) {
return coerce.ToBool(params[0])
}
type fnToBytes struct {
*baseFn
}
func (*fnToBytes) Name() string {
return "toBytes"
}
func (*fnToBytes) Eval(params ...interface{}) (interface{}, error) {
return coerce.ToBytes(params[0])
}
|
package main
import (
"github.com/GoAdminGroup/go-admin/context"
"github.com/GoAdminGroup/go-admin/modules/db"
"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
"github.com/GoAdminGroup/go-admin/template/types/form"
)
func GetBlogTagTable(ctx *context.Context) table.Table {
blogTag := table.NewDefaultTable(table.DefaultConfigWithDriver("mysql"))
info := blogTag.GetInfo().HideFilterArea()
info.AddField("Id", "id", db.Int).
FieldFilterable()
info.AddField("Name", "name", db.Varchar)
info.AddField("Created_on", "created_on", db.Int)
info.AddField("Created_by", "created_by", db.Varchar)
info.AddField("Modified_on", "modified_on", db.Int)
info.AddField("Modified_by", "modified_by", db.Varchar)
info.AddField("Deleted_on", "deleted_on", db.Int)
info.AddField("State", "state", db.Tinyint)
info.SetTable("blog_tag").SetTitle("BlogTag").SetDescription("BlogTag")
formList := blogTag.GetForm()
formList.AddField("Id", "id", db.Int, form.Default).
FieldDisableWhenCreate().
FieldDisableWhenUpdate()
formList.AddField("Name", "name", db.Varchar, form.Text).
FieldDisableWhenCreate().
FieldDisableWhenUpdate()
formList.AddField("Created_on", "created_on", db.Int, form.Number).
FieldDisableWhenCreate().
FieldDisableWhenUpdate()
formList.AddField("Created_by", "created_by", db.Varchar, form.Text).
FieldDisableWhenCreate().
FieldDisableWhenUpdate()
formList.AddField("Modified_on", "modified_on", db.Int, form.Number).
FieldDisableWhenCreate().
FieldDisableWhenUpdate()
formList.AddField("Modified_by", "modified_by", db.Varchar, form.Text).
FieldDisableWhenCreate().
FieldDisableWhenUpdate()
formList.AddField("Deleted_on", "deleted_on", db.Int, form.Number).
FieldDisableWhenCreate().
FieldDisableWhenUpdate()
formList.AddField("State", "state", db.Tinyint, form.Number).
FieldDisableWhenCreate().
FieldDisableWhenUpdate()
formList.SetTable("blog_tag").SetTitle("BlogTag").SetDescription("BlogTag")
return blogTag
}
|
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"time"
"yespider-go/settings"
"yespider-go/www/controller"
)
func init() {
// Init config
settings.Setup()
}
func main() {
gin.SetMode(settings.ServerSettings.RunMode)
// Init handler
routersHandler := controller.InitRouter()
HttpPort := fmt.Sprintf(":%v", settings.ServerSettings.HttpPort)
server := &http.Server{
Addr: HttpPort,
Handler: routersHandler,
ReadTimeout: settings.ServerSettings.ReadTimeout * time.Second,
WriteTimeout: settings.ServerSettings.WriteTimeout * time.Second,
}
err := server.ListenAndServe()
if err != nil {
log.Fatalf("Server error : %v", err)
}
fmt.Print("Server listen to ", HttpPort)
}
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"io"
"io/ioutil"
"os"
"strings"
"github.com/aclements/go-z3/internal/ops"
)
func main() {
flagOut := flag.String("o", "", "output to `file`")
flag.Parse()
if flag.NArg() > 0 {
flag.Usage()
os.Exit(2)
}
w := &bytes.Buffer{}
fmt.Fprintf(w, `// Generated by gen.go. DO NOT EDIT.
package st
import (
"fmt"
"math/big"
"github.com/aclements/go-z3/z3"
)
`)
fmt.Fprintf(w, "type sorts struct {\n")
for _, typ := range ops.Types {
fmt.Fprintf(w, "sort%s z3.Sort\n", typ.StName)
}
fmt.Fprintf(w, "}\n\n")
fmt.Fprintf(w, "func initSorts(s *sorts, ctx *z3.Context) {\n")
for _, typ := range ops.Types {
arg := ""
if typ.Bits != 0 {
arg = fmt.Sprintf("%d", typ.Bits)
}
fmt.Fprintf(w, "s.sort%s = ctx.%sSort(%s)\n", typ.StName, typ.SymType, arg)
}
fmt.Fprintf(w, "}\n\n")
for _, typ := range ops.Types {
genDecl(w, typ)
for _, binop := range ops.BinOps {
if binop.Flags&typ.Flags != 0 {
genBinOp(w, typ, binop)
}
}
for _, unop := range ops.UnOps {
if unop.Flags&typ.Flags != 0 && unop.Flags&ops.OpPos == 0 {
genUnOp(w, typ, unop)
}
}
for _, typ2 := range ops.Types {
genConv(w, typ, typ2)
}
}
writeSource(*flagOut, w.Bytes())
}
func writeSource(filename string, src []byte) {
fsrc, err := format.Source(src)
if err != nil {
fmt.Fprint(os.Stderr, string(src))
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if filename == "" {
_, err = os.Stdout.Write(fsrc)
} else {
err = ioutil.WriteFile(filename, fsrc, 0666)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func genDecl(w *bytes.Buffer, t ops.Type) {
symtype := "z3." + t.SymType
fmt.Fprintf(w, "// %s implements symbolic %s values.\n", t.StName, t.ConType)
fmt.Fprintf(w, "type %s struct { C %s", t.StName, t.ConType)
if symtype != "" {
fmt.Fprintf(w, "; S %s", symtype)
}
fmt.Fprintf(w, "}\n\n")
if symtype == "" {
return
}
fmt.Fprintf(w, "// Any%s returns an unconstrained symbolic %s.\n", t.StName, t.StName)
fmt.Fprintf(w, "func Any%s(ctx *z3.Context, name string) %s {\n", t.StName, t.StName)
fmt.Fprintf(w, " cache := getCache(ctx)\n")
fmt.Fprintf(w, " sym := cache.z3.FreshConst(name, cache.sort%s).(%s)\n", t.StName, symtype)
fmt.Fprintf(w, " return %s{S: sym}\n", t.StName)
fmt.Fprintf(w, "}\n\n")
fmt.Fprintf(w, "// String returns x as a string.\n")
fmt.Fprintf(w, "func (x %s) String() string {\n", t.StName)
fmt.Fprintf(w, " if x.IsConcrete() {\n")
fmt.Fprintf(w, " return fmt.Sprint(x.C)\n")
fmt.Fprintf(w, " }\n")
fmt.Fprintf(w, " return x.S.String()\n")
fmt.Fprintf(w, "}\n\n")
fmt.Fprintf(w, "// IsConcrete returns true if x is concrete.\n")
fmt.Fprintf(w, "func (x %s) IsConcrete() bool {\n", t.StName)
fmt.Fprintf(w, " return x.S.Context() == nil\n")
fmt.Fprintf(w, "}\n\n")
fmt.Fprintf(w, "// Eval returns x's concrete value in model m.\n")
fmt.Fprintf(w, "// This also evaluates x with model completion.\n")
fmt.Fprintf(w, "func (x %s) Eval(m *z3.Model) %s {\n", t.StName, t.ConType)
fmt.Fprintf(w, " if x.IsConcrete() { return x.C }\n")
fmt.Fprintf(w, " c := m.Eval(x.S, true).(%s)\n", symtype)
switch {
case t.Flags&ops.IsBool != 0:
fmt.Fprintf(w, "val, ok := c.AsBool()\n")
case t.Flags&ops.IsUnsigned != 0:
fmt.Fprintf(w, "val, ok, _ := c.AsUint64()\n")
case t.Flags&ops.IsInteger != 0:
fmt.Fprintf(w, "val, ok, _ := c.AsInt64()\n")
case t.Flags&ops.IsBigInt != 0:
fmt.Fprintf(w, "val, ok := c.AsBigInt()\n")
case t.Flags&ops.IsBigRat != 0:
fmt.Fprintf(w, "if c2, _, ok := c.Approx(RealApproxDigits); ok { c = c2 }\n")
fmt.Fprintf(w, "val, ok := c.AsBigRat()\n")
}
fmt.Fprintf(w, " if !ok { panic(%q + c.String()) }\n", "model evaluation produced non-concrete value ")
fmt.Fprintf(w, " return (%s)(val)\n", t.ConType)
fmt.Fprintf(w, "}\n\n")
fmt.Fprintf(w, "// sym returns x's symbolic value, creating it if necessary.\n")
fmt.Fprintf(w, "func (x %s) sym(c *cache) %s {\n", t.StName, symtype)
fmt.Fprintf(w, "if !x.IsConcrete() { return x.S }\n")
switch symtype {
case "z3.Bool":
fmt.Fprintf(w, "return c.z3.FromBool(x.C)\n")
case "z3.BV":
// TODO: Is this right for unsigned types?
fmt.Fprintf(w, "return c.z3.FromInt(int64(x.C), c.sort%s).(z3.BV)\n", t.StName)
case "z3.Int":
fmt.Fprintf(w, "return c.z3.FromBigInt(x.C, c.sort%s).(z3.Int)\n", t.StName)
case "z3.Real":
fmt.Fprintf(w, "return c.z3.FromBigRat(x.C)\n")
}
fmt.Fprintf(w, "}\n\n")
}
func genBinOp(w *bytes.Buffer, t ops.Type, op ops.Op) {
resType := t.StName
if op.Flags&ops.OpCompare != 0 {
resType = "Bool"
}
rType := t.StName
if op.Flags&ops.OpShift != 0 {
// Right operand is an unsigned int.
rType = "Uint64"
}
fmt.Fprintf(w, "func (x %s) %s(y %s) %s {\n", t.StName, op.Method, rType, resType)
// If x and y are concrete, do concrete operation.
fmt.Fprintf(w, "if x.IsConcrete() && y.IsConcrete() {\n")
if t.Flags&(ops.IsBigInt|ops.IsBigRat) == 0 {
fmt.Fprintf(w, "return %s{C: x.C %s y.C}\n", resType, op.Op)
} else if op.Flags&ops.OpCompare == 0 {
fmt.Fprintf(w, "z := %s{C: new(%s)}\n", resType, strings.TrimLeft(t.ConType, "*"))
fmt.Fprintf(w, "z.C.%s(x.C, y.C)\n", op.Method)
fmt.Fprintf(w, "return z\n")
} else {
fmt.Fprintf(w, "return Bool{C: x.C.Cmp(y.C) %s 0}\n", op.Op)
}
fmt.Fprintf(w, "}\n")
// Otherwise, do operation symbolically.
fmt.Fprintf(w, "ctx := x.S.Context()\n")
fmt.Fprintf(w, "if ctx == nil { ctx = y.S.Context() }\n")
fmt.Fprintf(w, "cache := getCache(ctx)\n")
symop := op.Method
if symop == "Quo" && t.Flags&(ops.IsInteger|ops.IsBigRat) != 0 {
// On bit-vectors and reals, Go's / operator is
// equivalent to Z3's [SU]Div.
symop = "Div"
}
if op.Flags&ops.Z3SignedPrefix != 0 {
switch {
case t.Flags&ops.IsUnsigned != 0:
symop = "U" + symop
case t.Flags&ops.IsInteger != 0:
symop = "S" + symop
case t.Flags&(ops.IsFloat|ops.IsBigInt|ops.IsBigRat) != 0:
symop = symop
default:
panic("bad symop " + symop)
}
}
rs := "y.sym(cache)"
if op.Flags&ops.OpShift != 0 {
fmt.Fprintf(w, "var rs z3.BV\n")
rs = "rs"
// Short-circuit if right is concrete.
fmt.Fprintf(w, "if y.IsConcrete() {\n")
fmt.Fprintf(w, " if y.C >= %d {\n", t.Bits)
fmt.Fprintf(w, " return %s{C: 0}\n", resType)
fmt.Fprintf(w, " }\n")
if t.Bits == 64 {
fmt.Fprintf(w, "}\n")
// Size matches. There are no truncation
// issues, so just make y symbolic.
fmt.Fprintf(w, "rs = y.sym(cache)\n")
} else if t.Bits < 64 {
// Z3 needs it to be the same width as the
// left operand.
//
// If it's concrete, we've already
// overflow-checked it, so we can just
// truncate the concrete value and use that.
fmt.Fprintf(w, " rs = Uint%d{C: uint%d(y.C)}.sym(cache)\n", t.Bits, t.Bits)
fmt.Fprintf(w, "} else {\n")
// If it's symbolic, we can't just truncate it
// because the value might be large, so
// collapse the top many bits into one top
// bit.
fmt.Fprintf(w, " rs = y.sym(cache)\n")
fmt.Fprintf(w, " rs = rs.Extract(63, %d).AnyBits().Concat(rs.Extract(%d, 0))\n", t.Bits-1, t.Bits-2)
fmt.Fprintf(w, "}\n")
}
}
expr := fmt.Sprintf("x.sym(cache).%s(%s)", symop, rs)
switch symop {
case "AndNot":
// There's no Z3 method for this one, but it's easy to
// build up.
expr = "x.sym(cache).And(y.Not().sym(cache))"
case "Quo":
// This is messy. Z3's Int Div rounds toward -inf, but
// Go's "/" and big.Int.Quo round toward 0.
//
// x div y + (x mod y == 0 || x >= 0 ? 0 : (y >= 0 ? 1 : -1))
fmt.Fprintf(w, "xs, ys := x.sym(cache), y.sym(cache)\n")
fmt.Fprintf(w, "zero := cache.z3.FromInt(0, cache.sort%s).(z3.Int)\n", t.StName)
fmt.Fprintf(w, "one := cache.z3.FromInt(1, cache.sort%s).(z3.Int)\n", t.StName)
expr = "xs.Div(ys).Add(xs.Mod(ys).Eq(zero).Or(xs.GE(zero)).IfThenElse(zero, ys.GE(zero).IfThenElse(one, one.Neg())).(z3.Int))"
case "Rem":
if t.Flags&ops.IsBigInt == 0 {
break
}
// This is even messier. :(
fmt.Fprintf(w, "xs, ys := x.sym(cache), y.sym(cache)\n")
fmt.Fprintf(w, "zero := cache.z3.FromInt(0, cache.sort%s).(z3.Int)\n", t.StName)
fmt.Fprintf(w, "one := cache.z3.FromInt(1, cache.sort%s).(z3.Int)\n", t.StName)
expr = "xs.Sub(xs.Div(ys).Add(xs.Mod(ys).Eq(zero).Or(xs.GE(zero)).IfThenElse(zero, ys.GE(zero).IfThenElse(one, one.Neg())).(z3.Int)).Mul(ys))"
}
fmt.Fprintf(w, " return %s{S: %s}\n", resType, expr)
fmt.Fprintf(w, "}\n\n")
}
func genUnOp(w *bytes.Buffer, t ops.Type, op ops.Op) {
fmt.Fprintf(w, "func (x %s) %s() %s {\n", t.StName, op.Method, t.StName)
// If x is concrete, do concrete operation.
fmt.Fprintf(w, "if x.IsConcrete() {\n")
if t.Flags&(ops.IsBigInt|ops.IsBigRat) == 0 {
fmt.Fprintf(w, "return %s{C: %sx.C}\n", t.StName, op.Op)
} else {
fmt.Fprintf(w, "z := %s{C: new(%s)}\n", t.StName, strings.TrimLeft(t.ConType, "*"))
fmt.Fprintf(w, "z.C.%s(x.C)\n", op.Method)
fmt.Fprintf(w, "return z\n")
}
fmt.Fprintf(w, "}\n")
// Otherwise, do symbolic operation.
fmt.Fprintf(w, "return %s{S: x.S.%s()}\n", t.StName, op.Method)
fmt.Fprintf(w, "}\n\n")
}
func genConv(w io.Writer, from, to ops.Type) {
if from.Flags&to.Flags&ops.IsInteger == 0 {
return
}
op := ""
switch {
case to.Bits < from.Bits:
op = fmt.Sprintf("Extract(%d, 0)", to.Bits-1)
case from.Flags&ops.IsUnsigned != 0:
op = fmt.Sprintf("ZeroExtend(%d)", to.Bits-from.Bits)
case from.Flags&ops.IsInteger != 0:
op = fmt.Sprintf("SignExtend(%d)", to.Bits-from.Bits)
}
fmt.Fprintf(w, "func (x %s) To%s() %s {\n", from.StName, to.StName, to.StName)
fmt.Fprintf(w, " if x.IsConcrete() {\n")
fmt.Fprintf(w, " return %s{C: %s(x.C)}\n", to.StName, to.ConType)
fmt.Fprintf(w, " }\n")
fmt.Fprintf(w, " return %s{S: x.S.%s}\n", to.StName, op)
fmt.Fprintf(w, "}\n\n")
}
|
package routers
import (
"fmt"
"log"
"net/http"
"github.com/fatih/color"
"github.com/gorilla/mux"
"github.com/pmqueiroz/http-advices/advice"
)
type User struct {
Email string `json:"Email"`
Password string `json:"Password"`
Bio string `json:"Bio"`
}
type Users []User
func docs(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "docs/docs.html")
}
func handleRequests(port string) {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", docs).Methods("GET")
router.HandleFunc("/advices", advice.GetAllAdvices).Methods("GET")
router.HandleFunc("/advices", advice.SuggestNewAdvice).Methods("POST")
router.HandleFunc("/advices/{status}", advice.GetAdviceByStatus).Methods("GET")
router.HandleFunc("/advices/search/{query}", advice.GetAdvicesByQuery).Methods("GET")
log.Fatal(http.ListenAndServe(":" + port, router))
}
func Run(port *string) {
alert := color.New(color.FgHiMagenta, color.Bold).PrintfFunc()
message := "Running on port "
fmt.Print(message)
alert(*port)
handleRequests(*port)
} |
package util
import "time"
const (
ServerName = "Segaline"
ServerVersion = "0.1.0"
ServerNameVersion = ServerName + "/" + ServerVersion
)
const (
DefaultEmptyRequestTarget = "/index.html"
DefaultReadTimeout = 10 * time.Second
DefaultFallbackErrorTemplate = "{statusCode} - {serverInfo}"
)
const (
RequestMaxContentLength = 65_536
RequestMaxURILength = 32_768
RequestOWS = " \t"
)
const (
ResponseWriterBufferSize = 4_096
ResponseChunkSize = 4_096
ResponseMaxUnchunkedBody = 8 * ResponseChunkSize
)
const (
ErrorContentLengthExceeded = "content length maximum exceeded"
ErrorRequestURILengthExceeded = "request uri length maximum exceeded"
ErrorUnsupportedMethod = "unsupported method"
ErrorUnsupportedTransferEncoding = "unsupported transfer encoding"
ErrorTimeoutReached = "timeout reached"
)
|
package productready
import (
"context"
"fmt"
"log"
"mraft/productready/config"
"mraft/productready/httpd"
"mraft/productready/storage"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
type Engine struct {
prefix string
server *http.Server
router *gin.Engine
raftStorage *storage.Storage
kvHandle *httpd.KVHandle
}
func NewEngine(dcfg *config.DynamicConfig) *Engine {
cfg := config.NewOnDiskRaftConfig(dcfg)
if cfg.Join {
// 先调用webapi的http接口,告知集群有新节点加入
code, err := cfg.JoinNewNode(fmt.Sprintf("%s:%d", dcfg.IP, dcfg.RaftPort))
if code < 0 {
log.Fatal("join new node", err)
}
// 新增的节点已经存在, 视为节点重启,根据dragonboat的文档:
// 当一个节点重启时,不论该节点是一个初始节点还是后续通过成员变更添加的节点,均无需再次提供初始成员信息,也不再需要设置join参数为true
if code == 1 {
cfg.Join = false
cfg.Peers = make(map[uint64]string)
log.Println("join new node restart")
}
}
cfs := []string{
"kvstorage",
}
raftStorage, err := storage.NewStorage(
cfg.DeploymentID,
cfg.NodeID,
fmt.Sprintf("%s:%s", cfg.IP, cfg.RaftPort),
cfg.DataDir,
cfs,
cfg.Join,
cfg.Peers,
)
if err != nil {
log.Fatal(err)
}
// 等待raft集群ready
for {
if raftStorage.ClusterAllReady() {
break
}
time.Sleep(2 * time.Second)
}
router := gin.New()
router.Use(gin.Recovery())
engine := &Engine{
prefix: "/raft",
router: router,
server: &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", cfg.HttpPort),
Handler: router,
ReadTimeout: 20 * time.Second,
WriteTimeout: 40 * time.Second,
},
raftStorage: raftStorage,
kvHandle: httpd.NewKVHandle("kvstorage", raftStorage),
}
engine.registerRouter(router)
go func() {
if err := engine.server.ListenAndServe(); err != nil {
panic(err.Error())
}
}()
return engine
}
func (engine *Engine) Stop() {
if engine.server != nil {
if err := engine.server.Shutdown(context.Background()); err != nil {
fmt.Println("Server Shutdown: ", err)
}
}
engine.raftStorage.StopRaftNode()
}
|
package mongodb
import (
"testing"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
"github.com/stretchr/testify/require"
)
var testProviders map[string]terraform.ResourceProvider
var testProvider *schema.Provider
func init() {
testProvider = Provider().(*schema.Provider)
testProviders = map[string]terraform.ResourceProvider{
"mongodb": testProvider,
}
}
func TestProvider(t *testing.T) {
require.NoError(t, Provider().(*schema.Provider).InternalValidate())
}
func testProviderPreCheck(t *testing.T) {
t.Helper()
require.NoError(t, testProvider.Configure(terraform.NewResourceConfig(nil)))
}
|
// Copyright (c) 2018 Uber Technologies, Inc.
//
// 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 trafficcontrol
import (
"github.com/m3db/m3aggregator/aggregator/handler/common"
"github.com/m3db/m3aggregator/aggregator/handler/router"
"github.com/uber-go/tally"
)
type metrics struct {
trafficControlNotAllowed tally.Counter
}
func newMetrics(scope tally.Scope) metrics {
return metrics{
trafficControlNotAllowed: scope.Counter("traffic-control-not-allowed"),
}
}
type controlledRouter struct {
Controller
router.Router
m metrics
}
// NewRouter creates a traffic controlled router.
func NewRouter(
trafficController Controller,
router router.Router,
scope tally.Scope,
) router.Router {
return &controlledRouter{
Controller: trafficController,
Router: router,
m: newMetrics(scope),
}
}
func (r *controlledRouter) Route(shard uint32, buffer *common.RefCountedBuffer) error {
if !r.Controller.Allow() {
buffer.DecRef()
r.m.trafficControlNotAllowed.Inc(1)
return nil
}
return r.Router.Route(shard, buffer)
}
func (r *controlledRouter) Close() {
r.Controller.Close()
r.Router.Close()
}
|
package host
import (
"context"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"gopkg.in/yaml.v2"
)
// AddFromFileOptions contains available options for adding from file.
type AddFromDockerOptions struct {
Dst string
Domain string
Profile string
Watch bool
Docker *DockerOptions
}
// DockerOptions contains parameters to sync with docker and docker-compose
type DockerOptions struct {
Network string
ComposeFile string
ProjectName string
KeepPrefix bool
}
func AddFromDocker(ctx context.Context, opts *AddFromDockerOptions) error {
cli, err := client.NewEnvClient()
if err != nil {
panic(err)
}
defer cli.Close()
f := filters.NewArgs()
f.Add("status", "running")
networkID, err := getNetworkID(ctx, cli, opts.Docker)
if err != nil {
return err
}
if networkID != "" {
f.Add("network", networkID)
}
var containers []string
if opts.Docker.ComposeFile != "" {
containers, err = parseComposeFile(opts.Docker.ComposeFile, opts.Docker.ProjectName)
if err != nil {
return err
}
}
list, err := cli.ContainerList(ctx, types.ContainerListOptions{
Filters: f,
})
if err != nil {
return err
}
var lines []string
for _, c := range list {
for _, n := range c.NetworkSettings.Networks {
if networkID != "" && n.NetworkID != networkID {
continue
}
name := strings.Replace(c.Names[0], "/", "", -1)
if len(containers) == 0 {
name = fmt.Sprintf("%s.%s", name, opts.Domain)
lines = append(lines, fmt.Sprintf("%s %s", n.IPAddress, name))
} else {
for _, c := range containers {
match, err := regexp.MatchString(fmt.Sprintf("^%s(_[0-9]+)?", c), name)
if err != nil {
return err
}
if match {
name = fmt.Sprintf("%s.%s", name, opts.Domain)
if !opts.Docker.KeepPrefix {
name = strings.Replace(name, opts.Docker.ProjectName+"_", "", 1)
}
lines = append(lines, fmt.Sprintf("%s %s", n.IPAddress, name))
}
}
}
}
}
newData := &hostFile{
profiles: profileMap{
"default": lines,
},
}
return add(newData, &commonAddOptions{
opts.Dst,
opts.Profile,
true,
})
}
type composeData struct {
Services map[string]composeService `yaml:"services"`
}
type composeService struct {
ContainerName string `yaml:"container_name"`
}
func parseComposeFile(file, projectName string) ([]string, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
data := &composeData{}
err = yaml.Unmarshal(bytes, &data)
if err != nil {
return nil, err
}
var containers []string
for serv, data := range data.Services {
name := data.ContainerName
if data.ContainerName == "" {
name = fmt.Sprintf("%s_%s", projectName, serv)
}
containers = append(containers, name)
}
return containers, nil
}
func getNetworkID(ctx context.Context, cli *client.Client, opts *DockerOptions) (string, error) {
if opts == nil || opts.Network == "" {
return "", nil
}
var networkID string
nets, err := cli.NetworkList(ctx, types.NetworkListOptions{})
if err != nil {
return "", err
}
for _, net := range nets {
if net.Name == opts.Network || net.ID == opts.Network {
networkID = net.ID
break
}
}
if networkID == "" {
return "", fmt.Errorf("unknown network name or ID: '%s'", opts.Network)
}
return networkID, nil
}
|
package gevent
/* ================================================================================
* gevent
* qq group: 582452342
* email : 2091938785@qq.com
* author : 美丽的地球啊 - mliu
* ================================================================================ */
type (
IEventSource interface {
GetChannelName() string
GetEventName() string
GetData() interface{}
}
)
|
package base
import (
"errors"
"fmt"
//jwt "github.com/gogf/gf-jwt"
jwt "github.com/gogf/gf-jwt"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/os/glog"
"github.com/zhwei820/gadmin/app/model"
"github.com/zhwei820/gadmin/utils/crypt"
"time"
)
var (
// The underlying JWT middleware.
GfJWTMiddleware *jwt.GfJWTMiddleware
)
// Initialization function,
// rewrite this function to customized your own JWT settings.
func init() {
authMiddleware, err := jwt.New(&jwt.GfJWTMiddleware{
Realm: "gf admin",
Key: []byte("secret key"),
Timeout: time.Hour * 24 * 100, //token有效时间1
MaxRefresh: time.Hour * 24 * 100, //token刷新有效时间
IdentityKey: "username", // 用户关键字
TokenLookup: "header: Authorization", // 捕抓请求的指定数据
TokenHeadName: "jwt", // token 头名称
TimeFunc: time.Now,
Authenticator: SimpleAuthenticator, //登录验证
LoginResponse: LoginResponse, //登录返回token
RefreshResponse: RefreshResponse, //刷新token
Unauthorized: Unauthorized, //未登录返回
IdentityHandler: IdentityHandler, //返回数据给Authorizator
PayloadFunc: PayloadFunc, //将Authenticator返回的内容记录到jwt
Authorizator: Authorizator, //接收IdentityHandler数据并判断权限
HTTPStatusMessageFunc: HTTPStatusMessageFunc, //错误处理
})
if err != nil {
glog.Fatal("JWT Error:" + err.Error())
}
GfJWTMiddleware = authMiddleware
}
func PayloadFunc(data interface{}) jwt.MapClaims {
claims := jwt.MapClaims{}
params := data.(map[string]interface{})
if len(params) > 0 {
for k, v := range params {
claims[k] = v
}
}
return claims
}
func Authorizator(data interface{}, r *ghttp.Request) bool {
method := r.Method
path := r.URL.Path
glog.Debugf("user:%v ,method:%v ,path:%v\n", data, method, path)
return model.Enforcer.Enforce(data, path, method)
}
// IdentityHandler sets the identity for JWT.
func IdentityHandler(r *ghttp.Request) interface{} {
claims := jwt.ExtractClaims(r)
return claims["username"]
}
// Unauthorized is used to define customized Unauthorized callback function.
func Unauthorized(r *ghttp.Request, code int, message string) {
Fail(r, code, message)
}
func HTTPStatusMessageFunc(e error, r *ghttp.Request) string {
glog.Debug(e.Error())
switch e.Error() {
case "Token is expired":
return "token超时"
}
return e.Error()
}
// LoginResponse is used to define customized login-successful callback function.
func LoginResponse(r *ghttp.Request, code int, token string, expire time.Time) {
var tk struct {
Token string `json:"token"`
Expire string `json:"expire"`
Perms []string `json:"perms"` // policys
}
username := r.GetString("username")
policys := model.Enforcer.GetPermissionsForUser(username)
if len(policys) == 0 {
roles := model.Enforcer.GetRolesForUser(username)
for _, item := range roles {
policys = append(policys, model.Enforcer.GetPermissionsForUser(item)...)
}
}
Perms := make([]string, 0)
for _, item := range policys {
perm := fmt.Sprintf("%v:%v", item[1], item[2])
if perm == "*:(GET)|(POST)|(PUT)|(DELETE)|(PATCH)|(OPTIONS)|(HEAD)" {
perm = "superuser"
}
Perms = append(Perms, perm)
}
tk.Perms = Perms
tk.Token = GfJWTMiddleware.TokenHeadName + " " + token
tk.Expire = expire.Format(time.RFC3339)
Success(r, tk)
}
// RefreshResponse is used to get a new token no matter current token is expired or not.
func RefreshResponse(r *ghttp.Request, code int, token string, expire time.Time) {
var tk struct {
Token string `json:"token"`
Expire string `json:"expire"`
}
tk.Token = GfJWTMiddleware.TokenHeadName + " " + token
tk.Expire = expire.Format(time.RFC3339)
Success(r, tk)
}
// 简单 Authenticator 登录验证
func SimpleAuthenticator(r *ghttp.Request) (interface{}, error) {
data, _ := r.GetJson()
name := data.GetString("username")
password := data.GetString("password")
//glog.Debugfln("%v %v", name, password)
if password != "" {
u, err := model.GetUserByName(name)
if err != nil {
return nil, errors.New("用户名, 密码错误")
}
if u.Password == crypt.EncryptPassword(password) {
r.SetParam("username", u.Username)
return g.Map{
"username": u.Username,
"id": u.Id,
}, nil
}
}
return nil, jwt.ErrFailedAuthentication
}
|
package main
import (
"bufio"
"container/list"
"fmt"
"math"
"os"
"rand"
"regexp"
"strings"
"time"
)
var dict = map[string]*list.List{}
func soundex(word string) string {
word = strings.ToLower(word)
firstLetter := word[0:1]
word = word[1:]
//I need a better regexp lib. Could make this that much faster.
searches := []string{
"[bfpv]", "[cgjkqsxz]", "[dt]", "[l]", "[mn]", "[r]",
"1[hw]1", "2[hw]2", "3[hw]3", "4[hw]4", "5[hw]5", "6[hw]6",
"11+", "22+", "33+", "44+", "55+", "66+",
"[^0-9]",
}
replaces := []string{
"1", "2", "3", "4", "5", "6",
"1h", "2h", "3h", "4h", "5h", "6h",
"1", "2", "3", "4", "5", "6",
"",
}
for i, r := range searches {
re := regexp.MustCompile(r)
word = re.ReplaceAllString(word, replaces[i])
}
return (firstLetter + word + strings.Repeat("0", 3))[0:4]
}
func hammingDistance(s1 string, s2 string) int {
i, ret := len(s1)-1, 0
if len(s1) != len(s2) {
return math.MaxInt32
}
for ; i >= 0; i-- {
if s1[i:i+1] != s2[i:i+1] {
ret++
}
}
return ret
}
func findReplacement(word string) string {
ret := word
s := soundex(word)
if l, ok := dict[s]; ok {
dist := math.MaxInt32
for s := range l.Iter() {
n := hammingDistance(word, s.(string))
if n < dist && s.(string) != word {
dist = n
ret = s.(string)
}
}
}
return ret
}
func relay(in chan string, out chan string) {
w := strings.Fields(<-in)
r := rand.Intn(len(w) - 1)
w[r] = findReplacement(w[r])
out <- strings.Join(w, " ")
}
func main() {
rand.Seed(time.Nanoseconds())
msg := "Hate hate hate hatred for all one and all. No matter what you believe. Don't believe in you and that's true. Yeah. We hate everyone We hate everyone."
file, err := os.Open("/usr/share/dict/words", os.O_RDONLY, 0)
if err != nil {
panic(err.String())
}
bufReader := bufio.NewReader(file)
for {
w, e := bufReader.ReadString('\n')
if e != nil {
break
}
if w[0] < 'a' || w[0] > 'z' {
continue
}
if len(w) > 1 {
w = w[0 : len(w)-1]
soundex := soundex(w)
if _, ok := dict[soundex]; !ok {
dict[soundex] = list.New()
}
dict[soundex].PushBack(w)
}
}
in := make(chan string)
start := in
var out chan string
for i := 0; i < 20; i++ {
out = make(chan string)
go relay(in, out)
in = out
}
start <- msg
relayed := <-out
fmt.Printf(" original:\n%s\n relayed:\n%s\n", msg, relayed)
}
|
// Package api defines the graw api for Reddit bots.
package api
// Actor defines methods for bots that do things (send messages, make posts,
// fetch threads, etc).
type Actor interface {
// TakeEngine is called when the engine starts; bots should save the
// engine so they can call its methods. This is only called once.
TakeEngine(eng Engine)
}
// Loader defines methods for bots that use external resources or need to do
// initialization.
type Loader interface {
// SetUp is the first method ever called on the bot, and it will be
// allowed to finish before other methods are called. Bots should
// load resources here.
SetUp() error
// TearDown is the last method ever called on the bot, and all other
// method calls will finish before this method is called. Bots should
// unload resources here.
TearDown() error
}
// Failer defines methods bots can use to control how the Engine responds to
// failures.
type Failer interface {
// Fail will be called when the engine encounters an error. The bot can
// return true to instruct the engine to fail, or false to instruct the
// engine to try again.
//
// This method will be called in the main engine loop; the bot may
// choose to pause here or do other things to respond to the failure
// (e.g. pause for three hours to respond to Reddit down time).
Fail(err error) bool
}
|
package entity
// 用户实体
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
CreateTime int64 `json:"createTime"`
}
|
package horenso
const version = "0.9.0"
var revision = "Devel"
|
package handler
import (
"context"
"net"
"net/http"
"github.com/caos/logging"
"github.com/gorilla/csrf"
"github.com/rakyll/statik/fs"
"golang.org/x/text/language"
"github.com/caos/zitadel/internal/api/authz"
"github.com/caos/zitadel/internal/api/http/middleware"
"github.com/caos/zitadel/internal/auth/repository/eventsourcing"
"github.com/caos/zitadel/internal/crypto"
"github.com/caos/zitadel/internal/form"
_ "github.com/caos/zitadel/internal/ui/login/statik"
)
type Login struct {
endpoint string
router http.Handler
renderer *Renderer
parser *form.Parser
authRepo *eventsourcing.EsRepository
zitadelURL string
oidcAuthCallbackURL string
}
type Config struct {
OidcAuthCallbackURL string
ZitadelURL string
LanguageCookieName string
DefaultLanguage language.Tag
CSRF CSRF
Cache middleware.CacheConfig
}
type CSRF struct {
CookieName string
Key *crypto.KeyConfig
Development bool
}
const (
login = "LOGIN"
)
func CreateLogin(config Config, authRepo *eventsourcing.EsRepository, prefix string) *Login {
login := &Login{
oidcAuthCallbackURL: config.OidcAuthCallbackURL,
zitadelURL: config.ZitadelURL,
authRepo: authRepo,
}
statikFS, err := fs.NewWithNamespace("login")
logging.Log("CONFI-Ga21f").OnError(err).Panic("unable to create filesystem")
csrf, err := csrfInterceptor(config.CSRF, login.csrfErrorHandler())
logging.Log("CONFI-dHR2a").OnError(err).Panic("unable to create csrfInterceptor")
cache, err := middleware.DefaultCacheInterceptor(EndpointResources, config.Cache.MaxAge.Duration, config.Cache.SharedMaxAge.Duration)
logging.Log("CONFI-BHq2a").OnError(err).Panic("unable to create cacheInterceptor")
security := middleware.SecurityHeaders(csp(), login.cspErrorHandler)
login.router = CreateRouter(login, statikFS, csrf, cache, security)
login.renderer = CreateRenderer(prefix, statikFS, config.LanguageCookieName, config.DefaultLanguage)
login.parser = form.NewParser()
return login
}
func csp() *middleware.CSP {
csp := middleware.DefaultSCP
csp.ObjectSrc = middleware.CSPSourceOptsSelf()
csp.StyleSrc = csp.StyleSrc.AddNonce()
csp.ScriptSrc = csp.ScriptSrc.AddNonce()
return &csp
}
func csrfInterceptor(config CSRF, errorHandler http.Handler) (func(http.Handler) http.Handler, error) {
csrfKey, err := crypto.LoadKey(config.Key, config.Key.EncryptionKeyID)
if err != nil {
return nil, err
}
return csrf.Protect([]byte(csrfKey),
csrf.Secure(!config.Development),
csrf.CookieName(config.CookieName),
csrf.Path("/"),
csrf.ErrorHandler(errorHandler),
), nil
}
func (l *Login) Handler() http.Handler {
return l.router
}
func (l *Login) Listen(ctx context.Context) {
if l.endpoint == "" {
l.endpoint = ":80"
} else {
l.endpoint = ":" + l.endpoint
}
defer logging.LogWithFields("APP-xUZof", "port", l.endpoint).Info("html is listening")
httpListener, err := net.Listen("tcp", l.endpoint)
logging.Log("CONFI-W5q2O").OnError(err).Panic("unable to start listener")
httpServer := &http.Server{
Handler: l.router,
}
go func() {
<-ctx.Done()
if err = httpServer.Shutdown(ctx); err != nil {
logging.Log("APP-mJKTv").WithError(err)
}
}()
go func() {
err := httpServer.Serve(httpListener)
logging.Log("APP-oSklt").OnError(err).Panic("unable to start listener")
}()
}
func setContext(ctx context.Context, resourceOwner string) context.Context {
data := authz.CtxData{
UserID: login,
OrgID: resourceOwner,
}
return authz.SetCtxData(ctx, data)
}
|
// 201.Hands-on-exercise#1
// test
// benchmarks
// coverage
// coverage net
// exsample
package main
import (
"fmt"
"udemy_golang/src/201.Hands-on-exercise-1/dog"
)
type canine struct {
name string
age int
}
func main() {
fido := canine{
name: "Fido",
age: dog.Years(10),
}
fmt.Println(fido)
fmt.Println(dog.YearsTwo(20))
}
|
package main
import (
"fmt"
)
func main() {
var (
c string
n, level, valleys int
)
fmt.Scanf("%d\n", &n)
fmt.Scanf("%s\n", &c)
for _, r := range []rune(c) {
switch {
case r == 'U':
level++
case r == 'D':
level--
}
if level == 0 && r == 'U' {
valleys++
}
}
fmt.Printf("%d\n", valleys)
}
|
package service
import (
"github.com/jinzhu/gorm"
"github.com/zzsds/micro-sms-service/consts"
"github.com/zzsds/micro-sms-service/models"
)
// TemplateRepo ...
type TemplateRepo struct {
}
func NewTemplateRepo() *TemplateRepo {
return &TemplateRepo{}
}
// Create ...
func (r *TemplateRepo) Create(templateModel *models.Template) error {
tx := Db.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Error; err != nil {
return err
}
if err := tx.Create(&templateModel).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
// GetCodeTemplateFirst ...
func (r *TemplateRepo) GetCodeTemplateFirst(provider string, bizType int32) (*models.Template, error) {
var (
templateModel models.Template
err error
)
templateModel.Provider = provider
dbx := Db.Scopes(Scope("enabled", consts.Enabled_Yes), Scope("mode", consts.SmsMode_Code), Scope("biz_type", bizType))
if err = dbx.Where(&templateModel).First(&templateModel).Error; err != nil {
return nil, err
}
return &templateModel, nil
}
// GetNoticeTemplateFirst ...
func (r *TemplateRepo) GetNoticeTemplateFirst(provider string, bizType int32) (*models.Template, error) {
var (
templateModel models.Template
err error
)
templateModel.Provider = provider
dbx := Db.Scopes(Scope("enabled", consts.Enabled_Yes), Scope("mode", consts.SmsMode_Notice), Scope("biz_type", bizType))
if err = dbx.Where(&templateModel).First(&templateModel).Error; err != nil {
return nil, err
}
return &templateModel, nil
}
func (r *TemplateRepo) FirstModelTemplate(m models.Template) (result *models.Template, err error) {
result = new(models.Template)
if err = Db.Where(models.Template{
Model: gorm.Model{ID: m.ID},
Provider: m.Provider,
Mode: m.Mode,
BizType: m.BizType,
}).First(result).Error; err != nil {
return
}
return
}
|
/*
*
*/
package log
import (
"io"
"os"
"github.com/sirupsen/logrus"
)
var Logger *logrus.Logger = nil
type Level uint32
const (
PanicLevel Level = iota
FatalLevel
ErrorLevel
WarnLevel
InfoLevel
DebugLevel
TraceLevel
)
// case "json":
// formatter = &logrus.JSONFormatter{}
// default:
// formatter = &logrus.TextFormatter{}
type Formatter int
const (
JSONFormatter Formatter = iota
TextFormatter
)
type Entry struct {
*logrus.Entry
}
func SetFormatter(formatter Formatter) {
switch formatter {
case JSONFormatter:
Logger.SetFormatter(&logrus.JSONFormatter{})
case TextFormatter:
Logger.SetFormatter(&logrus.TextFormatter{})
}
}
func Init(formatter Formatter, level Level) {
Logger = logrus.New()
SetFormatter(formatter)
Logger.SetOutput(os.Stdout)
Logger.SetLevel(logrus.Level(level))
}
func GetEntry() Entry {
return Entry{logrus.NewEntry(Logger)}
}
// WithField methods wrappers
func WithField(key string, value interface{}) Entry {
return Entry{Logger.WithField(key, value)}
}
func (entry Entry) WithField(key string, value interface{}) Entry {
return Entry{entry.Entry.WithField(key, value)}
}
// WriterLevel methods wrappers
func WriterLevel(level Level) *io.PipeWriter {
return Logger.WriterLevel(logrus.Level(level))
}
func (entry Entry) WriterLevel(level Level) *io.PipeWriter {
return entry.Entry.WriterLevel(logrus.Level(level))
}
// logrus.Entry wrappers
func (entry Entry) Debug(str string) {
entry.Entry.Debug(str)
}
func (entry Entry) Debugf(str string, args ...interface{}) {
entry.Entry.Debugf(str, args...)
}
func (entry Entry) Info(str string) {
entry.Entry.Info(str)
}
func (entry Entry) Infof(str string, args ...interface{}) {
entry.Entry.Infof(str, args...)
}
func (entry Entry) Warn(str string) {
entry.Entry.Warn(str)
}
func (entry Entry) Warnf(str string, args ...interface{}) {
entry.Entry.Warnf(str, args...)
}
func (entry Entry) Error(err error) bool {
if err != nil {
entry.Entry.Error(err)
return true
}
return false
}
func (entry Entry) Errorf(str string, args ...interface{}) {
entry.Entry.Errorf(str, args...)
}
func (entry Entry) Fatal(str string) {
entry.Entry.Fatal(str)
}
func (entry Entry) Fatalf(str string, args ...interface{}) {
entry.Entry.Fatalf(str, args...)
}
// logrus.Logger wrappers
func Debug(str string) {
Logger.Debug(str)
}
func Debugf(str string, args ...interface{}) {
Logger.Debugf(str, args...)
}
func Info(str string) {
Logger.Info(str)
}
func Infof(str string, args ...interface{}) {
Logger.Infof(str, args...)
}
func Warn(str string) {
Logger.Warn(str)
}
func Warnf(str string, args ...interface{}) {
Logger.Warnf(str, args...)
}
func Error(err error) bool {
if err != nil {
Logger.Error(err)
return true
}
return false
}
func Errorf(str string, args ...interface{}) {
Logger.Errorf(str, args...)
}
func Fatal(str string) {
Logger.Fatal(str)
}
func Fatalf(str string, args ...interface{}) {
Logger.Fatalf(str, args...)
}
|
package lsifstore
import (
"context"
"database/sql"
"github.com/keegancsmith/sqlf"
"github.com/opentracing/opentracing-go/log"
"github.com/sourcegraph/sourcegraph/internal/database/basestore"
"github.com/sourcegraph/sourcegraph/internal/observation"
"github.com/sourcegraph/sourcegraph/lib/codeintel/semantic"
)
// DocumentationPage returns the documentation page with the given PathID.
func (s *Store) DocumentationPage(ctx context.Context, bundleID int, pathID string) (_ *semantic.DocumentationPageData, err error) {
ctx, _, endObservation := s.operations.documentationPage.WithAndLogger(ctx, &err, observation.Args{LogFields: []log.Field{
log.Int("bundleID", bundleID),
log.String("pathID", pathID),
}})
defer endObservation(1, observation.Args{})
page, err := s.scanFirstDocumentationPageData(s.Store.Query(ctx, sqlf.Sprintf(documentationPageDataQuery, bundleID, pathID)))
if err != nil {
return nil, err
}
return page, nil
}
const documentationPageDataQuery = `
-- source: enterprise/internal/codeintel/stores/lsifstore/documentation.go:DocumentationPage
SELECT
dump_id,
path_id,
data
FROM
lsif_data_documentation_pages
WHERE
dump_id = %s AND
path_id = %s
`
// scanFirstDocumentationPageData reads the first DocumentationPageData row. If no rows match the
// query, a nil is returned.
func (s *Store) scanFirstDocumentationPageData(rows *sql.Rows, queryErr error) (_ *semantic.DocumentationPageData, err error) {
if queryErr != nil {
return nil, queryErr
}
defer func() { err = basestore.CloseRows(rows, err) }()
if !rows.Next() {
return nil, nil
}
var (
rawData []byte
uploadID int
pathID string
)
if err := rows.Scan(
&uploadID,
&pathID,
&rawData,
); err != nil {
return nil, err
}
record, err := s.serializer.UnmarshalDocumentationPageData(rawData)
if err != nil {
return nil, err
}
return record, nil
}
|
package configure
import (
"log"
"net/http"
"github.com/gorilla/sessions"
)
var (
key = []byte(AppProperties.CookieSecretKey)
// Store : session store
Store = sessions.NewCookieStore(key)
)
const ssoSession = "sso_session"
// GetSession : get session from key store
func GetSession(r *http.Request) *sessions.Session {
session, err := Store.Get(r, ssoSession)
if err != nil {
log.Println("Failed to get session")
}
return session
}
|
package business
import (
"finance/models"
models_driver "finance/models/driver"
plugins "finance/plugins/common"
"finance/validator"
forms "finance/validator/driver"
"github.com/gin-gonic/gin"
"strings"
)
// 添加驾驶员
func AddDriver(context *gin.Context) {
var form forms.DriverAddForm
context.ShouldBindJSON(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
driver := models_driver.FinanceDriver{
Name: form.Name,
NumberPlate: form.NumberPlate,
Phone: form.Phone}
// 保存修改
models.DB.Save(&driver)
plugins.ApiExport(context).ApiExport()
return
}
// 驾驶员详情
func DriverInfo(context *gin.Context) {
var form forms.DriverInfoForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
driver := form.GetDriver()
if driver.ID == 0 {
plugins.ApiExport(context).Error(5011, "驾驶员编号错误")
return
}
export := plugins.ApiExport(context)
export.SetData("driver", driver.ToJson())
export.ApiExport()
return
}
// 编辑驾驶员
func DriverEdit(context *gin.Context) {
var form forms.DriverEditForm
context.ShouldBindJSON(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
driver := form.GetDriver()
if driver.ID == 0 {
plugins.ApiExport(context).Error(5011, "驾驶员编号错误")
return
}
driver.Name = form.Name
driver.NumberPlate = form.NumberPlate
driver.Phone = form.Phone
models.DB.Save(&driver)
plugins.ApiExport(context).ApiExport()
return
}
// 删除驾驶员
func DeleteDriver(context *gin.Context) {
var form forms.DriverDeleteForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
driver := form.GetDriver()
if driver.ID == 0 {
plugins.ApiExport(context).Error(5011, "驾驶员编号错误")
return
}
driver.Delete()
plugins.ApiExport(context).ApiExport()
return
}
// 驾驶员列表
func DriverList(context *gin.Context) {
var form forms.DriverListForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
drivers := form.GetDrivers()
driversJson := make([]map[string]interface{}, 0)
for _, item := range drivers {
driversJson = append(driversJson, item.ToJson())
}
plugins.ApiExport(context).ListPageExport(driversJson, form.Page, form.Total)
return
}
// 添加驾驶员车次
func AddDriverTrips(context *gin.Context) {
var form forms.TripsAddForm
context.ShouldBindJSON(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
// 自定义逻辑验证
if err := form.Valid(); err != nil {
plugins.ApiExport(context).Error(1001, err.Error())
return
}
trips := models_driver.FinanceDriverTrips{
ProvinceId: form.ProvinceId,
ProvinceName: form.ProvinceName,
Date: form.ValidDate,
DriverId: form.DriverId,
Remark: form.Remark}
// 保存修改
models.DB.Save(&trips)
plugins.ApiExport(context).ApiExport()
return
}
// 驾驶员车次列表
func DriverTripsList(context *gin.Context) {
var form forms.TripsListForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
tripss := form.GetTrips()
tripss_json := make([]map[string]interface{}, 0)
for _, item := range tripss {
tripss_json = append(tripss_json, item.ToJson())
}
plugins.ApiExport(context).ListPageExport(tripss_json, form.Page, form.Total)
return
}
// 驾驶员车次详情
func DriverTripsInfo(context *gin.Context) {
var form forms.TripsInfoForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
trips := form.Trips()
if trips.ID == 0 {
plugins.ApiExport(context).Error(5011, "车次编号错误")
return
}
export := plugins.ApiExport(context)
export.SetData("trips", trips.ToJson())
export.ApiExport()
return
}
// 编辑驾驶员车次
func DriverTripsEdit(context *gin.Context) {
var form forms.TripsEditForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
// 自定义逻辑验证
if err := form.Valid(); err != nil {
plugins.ApiExport(context).Error(1001, err.Error())
return
}
trips := form.Trips()
if trips.ID == 0 {
plugins.ApiExport(context).Error(5011, "车次编号错误")
return
}
trips.Remark = form.Remark
trips.Date = form.ValidDate
trips.ProvinceName = form.ProvinceName
trips.ProvinceId = form.ProvinceId
models.DB.Save(&trips)
plugins.ApiExport(context).ApiExport()
return
}
// 删除车次
func DeleteDriverTrips(context *gin.Context) {
var form forms.TripsDeleteForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
trips := form.Trips()
if trips.ID == 0 {
plugins.ApiExport(context).Error(5011, "车次编号错误")
return
}
trips.DeleteSelf()
plugins.ApiExport(context).ApiExport()
return
}
// 驾驶员车次订单列表
func DriverTripsOrderList(context *gin.Context) {
var form forms.TripsOrderListForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
// 自定义逻辑验证
if err := form.Valid(); err != nil {
plugins.ApiExport(context).Error(5011, err.Error())
return
}
trips := form.Trips()
totalOrderCount := 0
completeOrderCount := 0
var totalExpectedAmount float64
var totalActualAmount float64
trips.GetDetails()
detailsJson := make([]map[string]interface{}, 0)
for _, item := range trips.Details {
detailsJson = append(detailsJson, item.ToJson(context))
totalOrderCount += 1
if item.ExpectedAmount == item.ActualAmount && item.ExpectedAmount != 0 {
completeOrderCount += 1
}
totalActualAmount += item.ActualAmount
totalExpectedAmount += item.ExpectedAmount
}
export := plugins.ApiExport(context)
export.SetData("items", detailsJson)
export.SetData("total_actual_amount", totalActualAmount)
export.SetData("total_expected_amount", totalExpectedAmount)
export.SetData("total_order_count", totalOrderCount)
export.SetData("complete_order_count", completeOrderCount)
export.ApiExport()
return
}
// 驾驶员车次添加订单
func DriverTripsAddOrder(context *gin.Context) {
var form forms.AddTripsOrderForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
if err := form.Valid(); err != nil {
plugins.ApiExport(context).Error(1001, err.Error())
return
}
order := form.Order()
trips_order := models_driver.FinanceDriverTripsDetails{
TripsId: form.TripsId,
OrderId: form.OrderId,
ExpectedAmount: order.ExpectedAmount,
ActualAmount: order.ActualAmount}
// 创建分配记录
if err := models.DB.Save(&trips_order).Error; err != nil {
// 错误内容包含Duplicate entry双重输入错误
if index := strings.Index(err.Error(), "Duplicate entry"); index >= 0 {
plugins.ApiExport(context).Error(1001, "此订单已分配,勿重复操作.")
return
}
plugins.ApiExport(context).Error(1001, err.Error())
return
}
// 修改订单分配状态
order.EditAllocationStatus(1)
plugins.ApiExport(context).ApiExport()
return
}
// 驾驶员车次删除订单
func DriverTripsDeleteOrder(context *gin.Context) {
var form forms.DeleteTripsOrderForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
details := form.GetTripsDetails()
if details.ID == 0 {
plugins.ApiExport(context).Error(5011, "车次订单未找到.")
return
}
details.DeleteSelf()
plugins.ApiExport(context).ApiExport()
return
}
// 驾驶员车次修改金额
func DriverTripsEditOrderAmount(context *gin.Context) {
var form forms.EditTripsOrderAmountForm
context.ShouldBind(&form)
if err := validator.Valid.Struct(&form); err != nil {
plugins.ApiExport(context).FormError(err)
return
}
if err := form.Valid(); err != nil {
plugins.ApiExport(context).Error(5011, err.Error())
return
}
details := form.TripsDetails()
details.ExpectedAmount = form.ExpectedAmount
details.ActualAmount = form.ActualAmount
models.DB.Save(&details)
plugins.ApiExport(context).ApiExport()
return
}
|
package image
import (
"encoding/gob"
"errors"
"fmt"
"io"
"path/filepath"
"github.com/openshift/oc-mirror/pkg/api/v1alpha2"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
)
// Associations is a map for Association
// searching
type Associations map[string]v1alpha2.Association
// AssociationSet is a set of image Associations
// mapped to their images
type AssociationSet map[string]Associations
// Search will return all Associations for the specificed key
func (as AssociationSet) Search(key string) (values []v1alpha2.Association, found bool) {
assocs, found := as[key]
values = make([]v1alpha2.Association, len(assocs))
count := 0
for _, value := range assocs {
values[count] = value
count++
}
return
}
// UpdateKey will move values under oldKey to newKey in Assocations.
// Old entries will be deleted.
func (as AssociationSet) UpdateKey(oldKey, newKey string) error {
// make sure we don't delete the
// same key we just set
if newKey == oldKey {
return nil
}
values, found := as.Search(oldKey)
if !found {
return errors.New("key does not exist in map")
}
as.Add(newKey, values...)
delete(as, oldKey)
return nil
}
// UpdateValue will update the Association values for a given key
func (as AssociationSet) UpdateValue(key string, value v1alpha2.Association) error {
assocs, found := as[key]
if !found {
return errors.New("key does not exist in map")
}
assocs[value.Name] = value
return nil
}
// Add stores a key-value pair in this multimap.
func (as AssociationSet) Add(key string, values ...v1alpha2.Association) {
assocs, found := as[key]
for _, value := range values {
if found {
assocs[value.Name] = value
} else {
assocs = make(Associations)
assocs[value.Name] = value
as[key] = assocs
}
}
}
// Keys returns all unique keys contained in map
func (as AssociationSet) Keys() []string {
keys := make([]string, len(as))
count := 0
for key := range as {
keys[count] = key
count++
}
return keys
}
// SetContainsKey checks if the AssociationSet map contains a key
func (as AssociationSet) SetContainsKey(key string) (found bool) {
_, found = as[key]
return
}
// ContainsKey checks if the Associations map contains the specified key
func (as AssociationSet) ContainsKey(setKey, key string) (found bool) {
asSet, found := as[setKey]
if !found {
return false
}
_, found = asSet[key]
return
}
// Merge Associations into the receiver.
func (as AssociationSet) Merge(in AssociationSet) {
for imageName, assocs := range in {
for _, value := range assocs {
as.Add(imageName, value)
}
}
}
// Encode Associations in an efficient, opaque format.
func (as AssociationSet) Encode(w io.Writer) error {
if err := as.Validate(); err != nil {
return fmt.Errorf("invalid image associations: %v", err)
}
enc := gob.NewEncoder(w)
if err := enc.Encode(as); err != nil {
return fmt.Errorf("error encoding image associations: %v", err)
}
return nil
}
// Decode Associations from an opaque format. Only useable if Associations
// was encoded with Encode().
func (as *AssociationSet) Decode(r io.Reader) error {
dec := gob.NewDecoder(r)
if err := dec.Decode(as); err != nil {
return fmt.Errorf("error decoding image associations: %v", err)
}
// Update paths for local usage.
for imageName, assocs := range *as {
for _, assoc := range assocs {
assoc.Path = filepath.FromSlash(assoc.Path)
if err := as.UpdateValue(imageName, assoc); err != nil {
return err
}
}
}
return nil
}
// UpdatePath path will update path values for local
// AssociationSet use
func (as *AssociationSet) UpdatePath() error {
// Update paths for local usage.
for imageName, assocs := range *as {
for _, assoc := range assocs {
assoc.Path = filepath.FromSlash(assoc.Path)
if err := as.UpdateValue(imageName, assoc); err != nil {
return err
}
}
}
return nil
}
// Validate AssociationSet and all contained Associations
func (as AssociationSet) Validate() error {
var errs []error
for imageName, assocs := range as {
for _, assoc := range assocs {
if len(assoc.ManifestDigests) != 0 {
for _, digest := range assoc.ManifestDigests {
if _, found := assocs[digest]; !found {
errs = append(errs, fmt.Errorf("image %q: digest %s not found", imageName, digest))
continue
}
}
}
if err := assoc.Validate(); err != nil {
errs = append(errs, err)
}
}
}
return utilerrors.NewAggregate(errs)
}
// GetDigests will return all layer and manifest digests in the AssociationSet
func (as *AssociationSet) GetDigests() []string {
var digests []string
for _, assocs := range *as {
for _, assoc := range assocs {
digests = append(digests, assoc.LayerDigests...)
digests = append(digests, assoc.ManifestDigests...)
digests = append(digests, assoc.ID)
}
}
return digests
}
// AssocPathsForBlobs returns a map with the first association path found
// for each layer digest in the Association Set. This can be used
// to pull layers to reform images. As defined in the Association spec,
// the path can be a local or remote reference.
func AssocPathsForBlobs(as AssociationSet) map[string]string {
reposByBlob := map[string]string{}
for _, assocs := range as {
for _, assoc := range assocs {
for _, dgst := range assoc.LayerDigests {
if _, found := reposByBlob[dgst]; found {
continue
}
reposByBlob[dgst] = assoc.Path
}
}
}
return reposByBlob
}
// Prune will return a pruned AssociationSet containing provided keys
func Prune(in AssociationSet, keepKey []string) (AssociationSet, error) {
// return a new map with the pruned mapping
pruned := AssociationSet{}
for _, key := range keepKey {
assocs, ok := in[key]
if !ok {
return pruned, fmt.Errorf("key %s does not exist in provided associations", key)
}
pruned[key] = assocs
}
return pruned, nil
}
|
package test
import (
"blockchain/certdemo/certdb"
"fmt"
"github.com/syndtr/goleveldb/leveldb"
"log"
"time"
)
func main() {
fmt.Println("test expired ")
Expired()
}
func ExpiredSelect() {
for {
select {
//改成配置文件的 todo
case <-time.After(10 * time.Second):
log.Println("timeout: gen cert")
}
}
}
func Expired() {
certdb.DbCert.Deal(certdb.T1)
}
func GetAll() {
certdb.DbCert.Show()
return
//需要只读模式
db, err := leveldb.OpenFile("./dbcert", nil)
//defer db.Close()
if err != nil {
fmt.Println(err)
panic(err)
}
iter := db.NewIterator(nil, nil)
//这里边不能再加锁了
for iter.Next() {
pubkey := iter.Key()
val := iter.Value()
//更新data
log.Println(string(pubkey))
log.Println(string(val))
}
iter.Release()
}
func Get() {
cert, err := certdb.DbCert.Get(`-----BEGIN EC Public KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvJWnkVzQu5YwW+demNt9Zv8n5TAo
VOBq4Q3YrnPJ7UWEwmSxmWpWSZLJb2Cc+oAbUsGe1NaeUkFs/+P94po/vg==
-----END EC Public KEY-----`)
if err != nil {
log.Println(err)
return
}
log.Println(cert)
}
|
package profile
import (
"github.com/evcc-io/evcc/util"
sc "github.com/lorenzodonini/ocpp-go/ocpp1.6/smartcharging"
)
type SmartCharging struct {
log *util.Logger
}
func NewSmartCharging(log *util.Logger) *SmartCharging {
return &SmartCharging{
log: log,
}
}
// OnSetChargingProfile handles the CS message
func (s *SmartCharging) OnSetChargingProfile(request *sc.SetChargingProfileRequest) (confirmation *sc.SetChargingProfileConfirmation, err error) {
s.log.TRACE.Printf("recv: %s %+v", request.GetFeatureName(), request)
return sc.NewSetChargingProfileConfirmation(sc.ChargingProfileStatusRejected), nil
}
// OnClearChargingProfile handles the CS message
func (s *SmartCharging) OnClearChargingProfile(request *sc.ClearChargingProfileRequest) (confirmation *sc.ClearChargingProfileConfirmation, err error) {
s.log.TRACE.Printf("recv: %s %+v", request.GetFeatureName(), request)
return sc.NewClearChargingProfileConfirmation(sc.ClearChargingProfileStatusUnknown), nil
}
// OnGetCompositeSchedule handles the CS message
func (s *SmartCharging) OnGetCompositeSchedule(request *sc.GetCompositeScheduleRequest) (confirmation *sc.GetCompositeScheduleConfirmation, err error) {
s.log.TRACE.Printf("recv: %s %+v", request.GetFeatureName(), request)
return sc.NewGetCompositeScheduleConfirmation(sc.GetCompositeScheduleStatusRejected), nil
}
|
package orm
import (
"github.com/muidea/magicOrm/builder"
"github.com/muidea/magicOrm/model"
)
func (s *impl) updateSingle(modelInfo model.Model) (err error) {
builder := builder.NewBuilder(modelInfo, s.modelProvider)
sqlStr, sqlErr := builder.BuildUpdate()
if sqlErr != nil {
err = sqlErr
return err
}
_, err = s.executor.Update(sqlStr)
return err
}
func (s *impl) updateRelation(modelInfo model.Model, fieldInfo model.Field) (err error) {
fType := fieldInfo.GetType()
if fType.IsBasic() {
return
}
err = s.deleteRelation(modelInfo, fieldInfo, 0)
if err != nil {
return
}
err = s.insertRelation(modelInfo, fieldInfo)
if err != nil {
return
}
return
}
// Update update
func (s *impl) Update(entityModel model.Model) (ret model.Model, err error) {
err = s.executor.BeginTransaction()
if err != nil {
return
}
for {
err = s.updateSingle(entityModel)
if err != nil {
break
}
for _, field := range entityModel.GetFields() {
err = s.updateRelation(entityModel, field)
if err != nil {
break
}
}
break
}
if err == nil {
cErr := s.executor.CommitTransaction()
if cErr != nil {
err = cErr
}
} else {
rErr := s.executor.RollbackTransaction()
if rErr != nil {
err = rErr
}
}
if err != nil {
return
}
ret = entityModel
return
}
|
/*
* Unlocks PDF files, tries to decrypt encrypted documents with the given password,
* if that fails it tries an empty password as best effort.
*
* Run as: go run pdf_unlock.go input.pdf <password> output.pdf
*/
package main
import (
"fmt"
"os"
pdf "github.com/unidoc/unidoc/pdf/model"
"bufio"
"github.com/slok/gospinner"
"log"
)
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func main() {
if len(os.Args) < 4 {
fmt.Printf("Usage: go run pdf_unlock.go input.pdf <password_file> output.pdf\n")
os.Exit(1)
}
inputPath := os.Args[1]
passwordFile := os.Args[2]
outputPath := os.Args[3]
s, err := gospinner.NewSpinner(gospinner.Dots2)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
s.Start("Opening password file")
file, err := os.Open(passwordFile)
if err != nil {
log.Fatal(err)
}
defer file.Close()
s.Succeed()
s.Start("Trying to crack PDF")
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
s.SetMessage(fmt.Sprintf("Working: %s", line))
err := unlockPdf(inputPath, outputPath, line)
if err != nil {
} else {
fmt.Printf("Complete. Password: %s see output file: %s\n", line, outputPath)
s.Succeed()
os.Exit(0)
}
}
s.Succeed()
}
func unlockPdf(inputPath string, outputPath string, password string) error {
pdfWriter := pdf.NewPdfWriter()
f, err := os.Open(inputPath)
if err != nil {
return err
}
defer f.Close()
pdfReader, err := pdf.NewPdfReader(f)
if err != nil {
return err
}
isEncrypted, err := pdfReader.IsEncrypted()
if err != nil {
return err
}
// Try decrypting both with given password and an empty one if that fails.
if isEncrypted {
auth, err := pdfReader.Decrypt([]byte(password))
if err != nil {
return err
}
if !auth {
return fmt.Errorf("Wrong password\n")
}
}
numPages, err := pdfReader.GetNumPages()
if err != nil {
return err
}
for i := 0; i < numPages; i++ {
pageNum := i + 1
page, err := pdfReader.GetPage(pageNum)
if err != nil {
return err
}
err = pdfWriter.AddPage(page)
if err != nil {
return err
}
}
fWrite, err := os.Create(outputPath)
if err != nil {
return err
}
defer fWrite.Close()
err = pdfWriter.Write(fWrite)
if err != nil {
return err
}
return nil
}
|
package server
import (
"fmt"
"github.com/20zinnm/entity"
"github.com/20zinnm/spac/common/net"
"github.com/20zinnm/spac/common/world"
"github.com/20zinnm/spac/server/bounding"
"github.com/20zinnm/spac/server/despawning"
"github.com/20zinnm/spac/server/health"
"github.com/20zinnm/spac/server/movement"
"github.com/20zinnm/spac/server/networking"
"github.com/20zinnm/spac/server/perceiving"
"github.com/20zinnm/spac/server/physics"
"github.com/20zinnm/spac/server/shooting"
"github.com/gorilla/websocket"
"io"
"log"
"net/http"
"time"
)
type server struct {
bind string
radius float64
tick time.Duration
upgrader *websocket.Upgrader
debug bool
}
type Option func(*server)
func BindAddress(address string) Option {
return func(s *server) {
s.bind = address
}
}
func WorldRadius(radius float64) Option {
return func(s *server) {
s.radius = radius
}
}
func TickRate(tick time.Duration) Option {
return func(s *server) {
s.tick = tick
}
}
func Upgrader(upgrader *websocket.Upgrader) Option {
return func(s *server) {
s.upgrader = upgrader
}
}
func Debug() Option {
return func(s *server) {
s.debug = true
}
}
func Start(options ...Option) {
server := &server{
bind: ":8080",
radius: 10000,
tick: time.Second / 60,
upgrader: &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
},
}
for _, o := range options {
o(server)
}
var manager = entity.NewManager()
defer manager.Destroy()
space := world.NewSpace()
manager.AddSystem(bounding.New(server.radius))
manager.AddSystem(movement.New())
manager.AddSystem(shooting.New(manager, space))
manager.AddSystem(physics.New(manager, space))
manager.AddSystem(perceiving.New(space))
manager.AddSystem(health.New(manager, space))
manager.AddSystem(despawning.New(manager))
netwk := networking.New(manager, space, server.radius)
manager.AddSystem(netwk)
go func() {
ticker := time.NewTicker(server.tick)
defer ticker.Stop()
last := time.Now()
skip := 0
for range ticker.C {
if len(ticker.C) > 0 {
skip++
continue // we're behind!
}
if skip > 0 {
fmt.Printf("Server lagging! Skipping %d ticks.", skip)
skip = 0
}
now := time.Now()
delta := now.Sub(last).Seconds()
last = now
manager.Update(delta)
}
fmt.Println("game stopped")
}()
fmt.Println("game started")
http.Handle("/ws", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := server.upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("error upgrading connection", err)
return
}
netwk.Add(net.Websocket(conn))
}))
if server.debug {
http.Handle("/debug", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "debugging")
fmt.Fprintln(w, "=========")
for _, system := range manager.Systems() {
if debuggable, ok := system.(Debuggable); ok {
debuggable.Debug(w)
fmt.Fprintf(w, "---\n")
}
}
}))
}
log.Fatal(http.ListenAndServe(server.bind, nil))
}
type Debuggable interface {
Debug(to io.Writer)
}
|
package main
var x []num
|
package main
import (
"fmt"
"strings"
)
var pow = []int{1, 2, 4, 8}
func main() {
// The range form of the for loop iterates over a slice or map.
// When ranging over a slice, two values are returned for each iteration. The
// first is the index, and the second is a copy of the element at that index.
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v) // 2**0 = 1 2**1 = 2 2**2 = 4 2**3 = 8
}
// You can skip the index or value by assigning to _.
// for i, _ := range pow
// for _, value := range pow
// A map maps keys to values.
// The zero value of a map is nil. A nil map has no keys,
// nor can keys be added.
var m1 map[string]int
m1 = wordCount("I Love You! I Love You! I Love You!")
fmt.Println(m1) // map[I:3 Love:3 You!:3]
// Delete an element:
delete(m1, "Love")
fmt.Println(m1) // map[I:3 You!:3]
// Insert an element:
m1["Love"] = 10000
// Retrieve an element and update an element:
m1["I"] = m1["Love"]
m1["You!"] = m1["Love"]
fmt.Println(m1) // map[I:10000 Love:10000 You!:10000]
// Test that a key is present with a two-value assignment:
// elem, ok = m[key]
// If key is in m, ok is true. If not, ok is false. If key is not in the map,
// then elem is the zero value for the map's element type.
v, ok := m1["Love"]
fmt.Println("The value:", v, "Present?", ok) // The value: 10000 Present? true
// Map literals are like struct literals, but the keys are required.
m2 := map[int]string{
5: "我",
2: "爱",
0: "你",
}
fmt.Println(m2) // map[0:你 2:爱 5:我]
}
func wordCount(s string) map[string]int {
// The make function returns a map of the given type,
// initialized and ready for use.
result := make(map[string]int)
// Fields splits the string s around each instance of one or more consecutive
// white space characters, as defined by unicode. IsSpace, returning a slice
// of substrings of s or an empty slice if s contains only white space.
arr := strings.Fields(s)
for _, v := range arr {
result[v]++
}
return result
}
|
package validate
import (
"github.com/pgavlin/warp/wasm"
"github.com/pgavlin/warp/wasm/code"
)
type validator struct {
module *wasm.Module
validateCode bool
importedFunctions []uint32
importedGlobals []wasm.GlobalVar
tables int
memories int
locals []wasm.ValueType
}
func ValidateModule(m *wasm.Module, validateCode bool) error {
v := validator{
module: m,
validateCode: validateCode,
}
if v.module.Import != nil {
for _, i := range v.module.Import.Entries {
switch i := i.Type.(type) {
case wasm.FuncImport:
v.importedFunctions = append(v.importedFunctions, i.Type)
case wasm.TableImport:
v.tables++
case wasm.MemoryImport:
v.memories++
case wasm.GlobalVarImport:
v.importedGlobals = append(v.importedGlobals, i.Type)
}
}
}
if v.module.Table != nil {
v.tables += len(v.module.Table.Entries)
}
if v.module.Memory != nil {
v.memories += len(v.module.Memory.Entries)
}
return v.validateModule()
}
func (v *validator) validateModule() error {
if err := v.validateTypes(); err != nil {
return err
}
if err := v.validateFunctions(); err != nil {
return err
}
if err := v.validateTables(); err != nil {
return err
}
if err := v.validateMemories(); err != nil {
return err
}
if err := v.validateGlobals(); err != nil {
return err
}
if err := v.validateElements(); err != nil {
return err
}
if err := v.validateData(); err != nil {
return err
}
if err := v.validateStart(); err != nil {
return err
}
if err := v.validateImports(); err != nil {
return err
}
if err := v.validateExports(); err != nil {
return err
}
return nil
}
func (v *validator) validateTypes() error {
// no-op: all types are valid by definition
return nil
}
func (v *validator) validateFunctions() error {
var types []uint32
if v.module.Function != nil {
types = v.module.Function.Types
}
var bodies []wasm.FunctionBody
if v.module.Code != nil {
bodies = v.module.Code.Bodies
}
if len(types) != len(bodies) {
return wasm.ValidationError("function and code section have inconsistent lengths")
}
for i, typeidx := range types {
sig, ok := v.GetType(typeidx)
if !ok {
return wasm.ValidationError("unknown type")
}
if !v.validateCode {
continue
}
body := bodies[i]
v.SetFunction(sig, body)
_, err := code.Decode(body.Code, v, sig.ReturnTypes)
if err != nil {
return err
}
}
return nil
}
func (v *validator) validateLimits(limits wasm.ResizableLimits) error {
if limits.Flags != 0 && limits.Initial > limits.Maximum {
return wasm.ValidationError("size minimum must not be greater than maximum")
}
return nil
}
func (v *validator) validateTables() error {
if v.module.Table == nil || len(v.module.Table.Entries) == 0 {
return nil
}
if v.tables > 1 {
return wasm.ValidationError("multiple tables")
}
return v.validateLimits(v.module.Table.Entries[0].Limits)
}
func (v *validator) validateMemories() error {
if v.module.Memory == nil || len(v.module.Memory.Entries) == 0 {
return nil
}
if v.memories > 1 {
return wasm.ValidationError("multiple memories")
}
limits := v.module.Memory.Entries[0].Limits
if err := v.validateLimits(limits); err != nil {
return err
}
if limits.Initial > 65536 || limits.Flags != 0 && limits.Maximum > 65536 {
return wasm.ValidationError("memory size must be at most 65536 pages (4GiB)")
}
return nil
}
func (v *validator) validateGlobals() error {
if v.module.Global == nil {
return nil
}
scope := v.globalScope()
for _, g := range v.module.Global.Globals {
if err := v.validateInitExpr(g.Init, g.Type.Type, scope); err != nil {
return err
}
}
return nil
}
func (v *validator) validateElements() error {
if v.module.Elements == nil {
return nil
}
for _, elem := range v.module.Elements.Entries {
if elem.Index >= uint32(v.tables) {
return wasm.ValidationError("unknown table")
}
if err := v.validateInitExpr(elem.Offset, wasm.ValueTypeI32, v); err != nil {
return err
}
for _, funcidx := range elem.Elems {
if _, ok := v.GetFunctionSignature(funcidx); !ok {
return wasm.ValidationError("unknown function")
}
}
}
return nil
}
func (v *validator) validateData() error {
if v.module.Data == nil {
return nil
}
for _, data := range v.module.Data.Entries {
if data.Index >= uint32(v.memories) {
return wasm.ValidationError("unknown memory")
}
if err := v.validateInitExpr(data.Offset, wasm.ValueTypeI32, v); err != nil {
return err
}
}
return nil
}
func (v *validator) validateStart() error {
if v.module.Start == nil {
return nil
}
sig, ok := v.GetFunctionSignature(v.module.Start.Index)
if !ok {
return wasm.ValidationError("unknown function")
}
if len(sig.ParamTypes) != 0 || len(sig.ReturnTypes) != 0 {
return wasm.ValidationError("start function")
}
return nil
}
func (v *validator) validateImports() error {
if v.module.Import == nil {
return nil
}
for _, i := range v.module.Import.Entries {
switch i := i.Type.(type) {
case wasm.FuncImport:
if _, ok := v.GetFunctionSignature(i.Type); !ok {
return wasm.ValidationError("unknown type")
}
case wasm.TableImport:
if err := v.validateLimits(i.Type.Limits); err != nil {
return err
}
case wasm.MemoryImport:
if err := v.validateLimits(i.Type.Limits); err != nil {
return err
}
case wasm.GlobalVarImport:
// OK
}
}
return nil
}
func (v *validator) validateExports() error {
if v.module.Export == nil {
return nil
}
names := map[string]bool{}
for _, e := range v.module.Export.Entries {
if names[e.FieldStr] {
return wasm.ValidationError("duplicate export name")
}
names[e.FieldStr] = true
switch e.Kind {
case wasm.ExternalFunction:
if _, ok := v.GetFunctionSignature(e.Index); !ok {
return wasm.ValidationError("unknown function")
}
case wasm.ExternalTable:
if e.Index >= uint32(v.tables) {
return wasm.ValidationError("unknown table")
}
case wasm.ExternalMemory:
if e.Index >= uint32(v.memories) {
return wasm.ValidationError("unknown memory")
}
case wasm.ExternalGlobal:
if _, ok := v.GetGlobalType(e.Index); !ok {
return wasm.ValidationError("unknown global")
}
}
}
return nil
}
func (v *validator) validateInitExpr(expr []byte, expected wasm.ValueType, scope code.Scope) error {
decoded, err := code.Decode(expr, scope, []wasm.ValueType{expected})
if err != nil {
return err
}
for _, instr := range decoded.Instructions {
switch instr.Opcode {
case code.OpI32Const, code.OpI64Const, code.OpF32Const, code.OpF64Const, code.OpEnd:
// OK
case code.OpGlobalGet:
if v.importedGlobals[int(instr.Globalidx())].Mutable {
return wasm.ValidationError("constant expression required")
}
default:
return wasm.ValidationError("constant expression required")
}
}
return nil
}
|
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// 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 watchdog
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"reflect"
"testing"
"time"
dto "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/assert"
v1 "k8s.io/api/core/v1"
)
type mockObjectType int
const (
mockPodListType mockObjectType = iota
mockNodeListType
)
type mockObject struct {
podList *v1.PodList
nodeList *v1.NodeList
pc *PromMetricCollector
}
func newMockObject(filename string, t mockObjectType) *mockObject {
list, _ := ioutil.ReadFile(filename)
mo := mockObject{}
if t == mockPodListType {
podList := v1.PodList{}
json.Unmarshal(list, &podList)
mo.podList = &podList
} else if t == mockNodeListType {
nodeList := v1.NodeList{}
json.Unmarshal(list, &nodeList)
mo.nodeList = &nodeList
}
mo.pc = &PromMetricCollector{}
return &mo
}
func TestGeneratePodsMetrics(t *testing.T) {
mo := newMockObject("../../testdata/pod_list.json", mockPodListType)
mg := metricGenerator{}
podMetrics := mg.generatePodMetrics(mo.podList)
assert.Equal(t, 3, len(podMetrics))
expectLables := [][]map[string]string{
{
{
"host_ip": "10.151.41.8", "node_name": "test_node_0", "initialized": "true", "name": "log-manager-ds-nxm2k", "namespace": "default",
"phase": "running", "pod_scheduled": "true", "ready": "true", "service_name": "log-manager",
}, {
"host_ip": "10.151.41.8", "node_name": "test_node_0", "name": "log-manager-logrotate", "namespace": "default",
"pod_name": "log-manager-ds-nxm2k", "state": "running", "ready": "true", "service_name": "log-manager",
},
{
"host_ip": "10.151.41.8", "node_name": "test_node_0", "name": "log-manager-nginx", "namespace": "default",
"pod_name": "log-manager-ds-nxm2k", "state": "running", "ready": "true", "service_name": "log-manager",
},
},
{},
{
{
"host_ip": "10.1.3.29", "node_name": "test_node_1", "initialized": "true", "job_name": "it_it_batch052_infer_80-159_bs2_V1",
"name": "f1up4zk9ehfpjx2zc9gq8rv860uk4qv9dtk6awjz70r2uc9n75fp4wtjbxb32-taskrole-28", "namespace": "default",
"phase": "pending", "pod_bound": "true", "pod_scheduled": "true", "ready": "false",
},
},
}
for i, podMetric := range podMetrics {
promMetrics := mo.pc.getPodMetrics(podMetric)
for j, m := range promMetrics {
dm := &dto.Metric{}
m.Write(dm)
assert.Equal(t, float64(1), dm.GetGauge().GetValue())
for _, l := range dm.Label {
assert.Equal(t, expectLables[i][j][l.GetName()], l.GetValue())
}
}
}
}
func TestGenerateNodesMetrics(t *testing.T) {
mo := newMockObject("../../testdata/node_list.json", mockNodeListType)
mg := metricGenerator{}
nodeMetrics := mg.generateNodeMetrics(mo.nodeList)
assert.Equal(t, 1, len(nodeMetrics))
metrics := mo.pc.getPaiNodeMetrics(nodeMetrics[0])
expectLables := []map[string]string{
{
"host_ip": "10.151.41.8", "node_name": "test_node_0", "disk_pressure": "false", "memory_pressure": "false",
"ready": "true", "unschedulable": "false",
},
}
for i, m := range metrics {
dm := &dto.Metric{}
m.Write(dm)
assert.Equal(t, float64(1), dm.GetGauge().GetValue())
for _, l := range dm.Label {
assert.Equal(t, expectLables[i][l.GetName()], l.GetValue())
}
}
mo = newMockObject("../../testdata/pod_list.json", mockPodListType)
podMetrics := mg.generatePodMetrics(mo.podList)
npMap := mg.generateNodeToPodsMap(podMetrics)
gpuMetrics := mo.pc.getNodeGpuMetrics(nodeMetrics[0], npMap)
assert.Equal(t, 3, len(gpuMetrics))
type pair struct {
name string
num float64
}
expectValue := []pair{
{
name: "k8s_node_gpu_available",
num: 4,
},
{
name: "k8s_node_gpu_reserved",
num: 0,
},
{
name: "k8s_node_gpu_total",
num: 4,
},
}
for i, m := range gpuMetrics {
dm := &dto.Metric{}
m.Write(dm)
v := reflect.ValueOf(m.Desc())
n := reflect.Indirect(v).FieldByName("fqName").String()
assert.Equal(t, expectValue[i].name, n)
assert.Equal(t, expectValue[i].num, dm.GetGauge().GetValue())
}
}
func TestParseNoConditionPods(t *testing.T) {
mo := newMockObject("../../testdata/no_condition_pod.json", mockPodListType)
mg := metricGenerator{}
podMetrics := mg.generatePodMetrics(mo.podList)
assert.True(t, len(podMetrics) > 0)
promMetrics := mo.pc.getPodMetrics(podMetrics[0])
expectLables := []map[string]string{
{
"host_ip": "unscheduled", "node_name": "test_node_0", "initialized": "unknown", "name": "yarn-frameworklauncher-ds-2684q", "namespace": "default",
"phase": "failed", "pod_scheduled": "unknown", "ready": "unknown", "service_name": "frameworklauncher",
},
}
for i, m := range promMetrics {
dm := &dto.Metric{}
m.Write(dm)
for _, l := range dm.Label {
assert.Equal(t, expectLables[i][l.GetName()], l.GetValue())
}
}
}
func TestParseDLWSUnschedulableNodes(t *testing.T) {
mo := newMockObject("../../testdata/dlws_node_list_with_unschedulable.json", mockNodeListType)
mg := metricGenerator{}
nodeMetrics := mg.generateNodeMetrics(mo.nodeList)
promMetrics := mo.pc.getPaiNodeMetrics(nodeMetrics[0])
expectLables := []map[string]string{
{
"host_ip": "192.168.255.1", "node_name": "dltsp40-infra01", "disk_pressure": "false", "memory_pressure": "false",
"ready": "true", "unschedulable": "true",
},
}
for i, m := range promMetrics {
dm := &dto.Metric{}
m.Write(dm)
for _, l := range dm.Label {
assert.Equal(t, expectLables[i][l.GetName()], l.GetValue())
}
}
}
func TestCollectMetrics(t *testing.T) {
m := newMockK8sServer()
m.addResponseByFile("/api/v1/pods", "../../testdata/pod_list.json", http.MethodGet)
m.addResponseByFile("/api/v1/nodes", "../../testdata/node_list.json", http.MethodGet)
m.addResponse("/healthz", "ok", http.MethodGet)
url := m.start()
defer m.stop()
os.Setenv("KUBE_APISERVER_ADDRESS", url)
c, _ := NewK8sClient()
pc := NewPromMetricCollector(c, time.Minute)
pc.collect()
metrics := pc.getMetrics()
// 3 gpu metrics + 1 api server metric + 1 pai node metric +
// 4 pod/container related metrics + 5 error metrics + 3 histogram metrics
assert.Equal(t, 17, len(metrics))
}
|
package eden
import (
"bytes"
"crypto/tls"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"time"
)
// Checks the given Authorization header for an encoded
// JWT and verifies it is from a valid sender. Retrieves
// the employee NetId and area Guid and stores in the
// context. Intended to be used as middleware.
func Authorize(c *Context) {
// Parse JWT from Authorization header
var tokenString string
tokenString = c.Request.Header.Get("Authorization")
if len(tokenString) < 1 {
c.Fail(401, "No authorization header present")
return
}
// Find the directory with the RSA keys
dir := os.Getenv("KEYS_DIRECTORY")
if dir == "" {
dir = "./keys" // If none given, use the keys directory within the current directory
}
// Loop over available public key files
files, _ := ioutil.ReadDir(dir)
for _, f := range files {
name := f.Name()
// Only look at files with extension .pub
if name[len(name)-4:] == ".pub" {
// Once a public is found, decode and try to validate
// See documentation on the JWT library for how this works
// The function passed in is a function that looks up the key
decoded, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
key, err := ioutil.ReadFile(dir + "/" + name) // Read in public key
if err != nil {
return nil, err
}
return jwt.ParseRSAPublicKeyFromPEM(key)
})
// If there was no error in parsing the key and decoding the token
// and if the token is valid store employee and area guids
if err == nil && decoded.Valid {
c.User.NetId = fmt.Sprintf("%v", decoded.Claims["employee"])
c.User.Area = fmt.Sprintf("%v", decoded.Claims["area"])
return
}
}
}
// No public key was able to decode and validate the JWT
// Send a failed message and abort.
c.Fail(401, "You are not authorized to make this request")
return
}
// Sends an authenticated request to the given url with the
// specified http method. Data is a map of data to use as
// post data. Any get data should be put in the url.
func (c *Context) SendAuthenticatedRequest(method, urlStr string, data map[string]string) (*http.Response, error) {
token := jwt.New(jwt.SigningMethodRS256)
// Set claims
token.Claims["exp"] = time.Now().Add(time.Minute * 2).Unix() // Expire in two hours
token.Claims["nbf"] = time.Now().Unix() - 1 // Not valid before now - 1 second
token.Claims["iat"] = time.Now().Unix() // Issued at now
token.Claims["employee"] = c.User.NetId // Employee netId
token.Claims["area"] = c.User.Area // Area guid
// Find private key
keyFile := os.Getenv("PRIVATE_KEY_FILE")
if keyFile == "" {
keyFile = "./keys/key.pem" // if none specified, use key.pem in ./keys directory
}
// Parse private key from file
key, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, err
}
pri, err := jwt.ParseRSAPrivateKeyFromPEM(key)
if err != nil {
return nil, err
}
// Sign the JWT with the private key
tokenString, err := token.SignedString(pri)
if err != nil {
return nil, err
}
// Convert the data into a format http Client can use
postData := url.Values{}
for k, v := range data {
postData.Add(k, v)
}
// Encode data and add as request body or ignore if empty
var body io.Reader
if len(data) > 0 {
body = bytes.NewBufferString(postData.Encode())
} else {
body = nil
}
// Form request
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
return nil, err
}
// Give the token to the request to make it authorized
req.Header.Add("Authorization", tokenString)
// Add other necessary headers
req.Header.Add("Content-Length", strconv.Itoa(len(postData.Encode())))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// Create http client and send request, return response
tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
client := &http.Client{Transport: tr}
return client.Do(req)
}
|
package websocket
import (
"testing"
"time"
)
func BenchmarkTimerNew(b *testing.B) {
for i := 0; i < b.N; i++ {
timer := time.NewTimer(0)
<-timer.C
}
}
func BenchmarkTimerReset(b *testing.B) {
timer := time.NewTimer(0)
if !timer.Stop() {
<-timer.C
}
for i := 0; i < b.N; i++ {
timer.Reset(0)
<-timer.C
}
}
|
package webgl3d
// func (self *Scene) loadPendulum() *Scene {
// pendulum := NewSceneObject(NewGeometry().LoadCylinder(10, 38, 1, false).Translate(0, 0, +0.5), "FFFFFF", "base")
// pillar := NewSceneObject(NewGeometry().LoadCube(1, 1, 10, false).Translate(0, 9, 6), "FFFFFF", "pillar")
// arm := NewSceneObject(NewGeometry().LoadCylinder(0.3, 12, 10, false).Rotate(1, 0, 0, 90).Translate(0, 4.5, 0), "FFFFFF", "arm")
// rope := NewSceneObject(NewGeometry().LoadCylinder(0.1, 12, 7, false).Translate(0, 0, -3.5), "FFFFFF", "rope")
// ball := NewSceneObject(NewGeometry().LoadSphere(1, 36, 18, false).Translate(0, 0, -7), "FFFFFF", "ball")
// pendulum.AddChild(pillar).AddChild(arm).Translate(0, 0, 10).AddChild(rope.AddChild(ball))
// self.Add(pendulum)
// return self
// }
|
package measurement
import q "github.com/yamakii/analysis_pattern/domain/quantity"
type PhenomenonType struct {
}
type Person struct {
}
type Measurement struct {
PhenomenonType
Person
q.Quantity
}
// 使用例
var (
John = Person{}
height = PhenomenonType{}
// Johnのheightの測定結果
JothnHeight = Measurement{height, John, q.Quantity{6, q.Feet}}
)
|
package fmap
import (
"fmt"
"strings"
"github.com/lleo/go-functional-collections/key"
"github.com/lleo/go-functional-collections/key/hash"
)
// implements nodeI
// implements leafI
type collisionLeaf []KeyVal
func newCollisionLeaf(kvs []KeyVal) *collisionLeaf {
var lKvs collisionLeaf = make([]KeyVal, len(kvs))
copy(lKvs, kvs)
return &lKvs
}
func (l *collisionLeaf) copy() leafI {
//return newCollisionLeaf([]KeyVal(*l))
return newCollisionLeaf(*l)
}
func (l *collisionLeaf) hash() hash.Val {
return (*l)[0].Key.Hash()
}
func (l *collisionLeaf) String() string {
var kvstrs = make([]string, len(*l))
for i := 0; i < len(*l); i++ {
kvstrs[i] = (*l)[i].String()
}
var jkvstr = strings.Join(kvstrs, ",")
return fmt.Sprintf("collisionLeaf{hash:%s, kvs:[]KeyVal{%s}}",
(*l)[0].Key.Hash(), jkvstr)
}
func (l *collisionLeaf) get(key key.Hash) (interface{}, bool) {
for _, kv := range *l {
if kv.Key.Equals(key) {
return kv.Val, true
}
}
return nil, false
}
func (l *collisionLeaf) putResolve(
key key.Hash,
val interface{},
resolve ResolveConflictFunc,
) (leafI, bool) {
for i, kv := range *l {
if kv.Key.Equals(key) {
var nl = l.copy().(*collisionLeaf)
var newVal = resolve(kv.Key, kv.Val, val)
(*nl)[i].Val = newVal
return nl, false // replaced
}
}
var nl collisionLeaf = make([]KeyVal, len(*l)+1)
nl[len(*l)] = KeyVal{Key: key, Val: val}
return &nl, true
}
func (l *collisionLeaf) put(key key.Hash, val interface{}) (leafI, bool) {
for i, kv := range *l {
if kv.Key.Equals(key) {
var nl = l.copy().(*collisionLeaf)
(*nl)[i].Val = val
return nl, false // replaced
}
}
var nl collisionLeaf = make([]KeyVal, len(*l)+1)
nl[len(*l)] = KeyVal{Key: key, Val: val}
return &nl, true
}
func (l *collisionLeaf) del(key key.Hash) (leafI, interface{}, bool) {
for i, kv := range *l {
if kv.Key.Equals(key) {
var nl leafI
if len(*l) == 2 {
// think about the index... it works, really :)
nl = newFlatLeaf((*l)[1-i].Key, (*l)[1-i].Val)
} else {
var cl = l.copy().(*collisionLeaf)
*cl = append((*cl)[:i], (*cl)[i+1:]...)
nl = cl
}
return nl, kv.Val, true
}
}
return l, nil, false
}
func (l *collisionLeaf) keyVals() []KeyVal {
var r = make([]KeyVal, 0, len(*l))
r = append(r, *l...)
return r
}
func (l *collisionLeaf) walkPreOrder(fn visitFunc, depth uint) bool {
return fn(l, depth)
}
// equiv comparse this *collisionLeaf against another node by value.
func (l *collisionLeaf) equiv(other nodeI) bool {
var ol, ok = other.(*collisionLeaf)
if !ok {
return false
}
if len(*l) != len(*ol) {
return false
}
for _, kv := range *l {
var keyFound = false
for _, okv := range *ol {
if kv.Key.Equals(okv.Key) {
keyFound = true
if kv.Val != okv.Val {
return false
}
}
}
if !keyFound {
return false
}
}
//for i, kv := range *l {
//// This assumes the kvs are in the same order.
// if !kv.Key.Equals((*ol)[i].Key) {
// return false
// }
// if kv.Val != (*ol)[i].Val {
// return false
// }
//}
return true
}
func (l *collisionLeaf) count() int {
return len(*l)
}
|
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
// signal包实现了对输入信号的访问
func main() {
// 初始化一个信号channel
c := make(chan os.Signal, 1)
// 让signal包将输入信号转发到c。如果没有列出要传递的信号,会将所有输入信号传递到c;否则只传递列出的输入信号
// signal包不会为了向c发送信息而阻塞(就是说如果发送时c阻塞了,signal包会直接放弃)
// 调用者应该保证c有足够的缓存空间可以跟上期望的信号频率。对使用单一信号用于通知的通道,缓存为1就足够了
signal.Notify(c, syscall.SIGINT, syscall.SIGKILL)
s := <-c
fmt.Println("Got signal:", s)
// 让signal包停止向c转发信号
// 它会取消之前使用c调用的所有Notify的效果。当Stop返回后,会保证c不再接收到任何信号
signal.Stop(c)
} |
package cmd
import (
"fmt"
"github.com/rancher/kontainer-engine/store"
"github.com/rancher/kontainer-engine/utils"
"github.com/urfave/cli"
)
// EnvCommand defines the env command
func EnvCommand() cli.Command {
return cli.Command{
Name: "env",
Usage: "Set cluster as current context",
Action: env,
}
}
func env(ctx *cli.Context) error {
name := ctx.Args().Get(0)
if name == "" || name == "--help" {
return cli.ShowCommandHelp(ctx, "env")
}
clusters, err := store.GetAllClusterFromStore()
if err != nil {
return err
}
_, ok := clusters[name]
if !ok {
return fmt.Errorf("cluster %v can't be found", name)
}
config, err := getConfigFromFile()
if err != nil {
return err
}
config.CurrentContext = name
if err := setConfigToFile(config); err != nil {
return err
}
configFile := utils.KubeConfigFilePath()
fmt.Printf("Current context is set to %s\n", name)
fmt.Printf("run `export KUBECONFIG=%v` or `--kubeconfig %s` to use the config file\n", configFile, configFile)
return nil
}
|
package log
import (
"github.com/astroflow/astroflow-go"
)
var logger = astroflow.NewLogger()
func Config(options ...astroflow.LoggerOption) error {
return logger.Config(options...)
}
func With(fields ...interface{}) astroflow.Logger {
return logger.With(fields...)
}
func Debug(message string) {
logger.Debug(message)
}
func Info(message string) {
logger.Info(message)
}
func Warn(message string) {
logger.Warn(message)
}
func Error(message string) {
logger.Error(message)
}
func Fatal(message string) {
logger.Fatal(message)
}
// Msg log an event without level
func Msg(message string) {
logger.Msg(message)
}
// Track log an event without message nor level
func Track(fields ...interface{}) {
logger.Track(fields...)
}
|
package mapper
import (
"context"
dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// NamespaceMapper manages the mapping creation from the namespace's side
type NamespaceMapper struct {
ctx context.Context
client client.Client
apiReader client.Reader
operatorNs string
targetNs *corev1.Namespace
}
func NewNamespaceMapper(ctx context.Context, clt client.Client, apiReader client.Reader, operatorNs string, targetNs *corev1.Namespace) NamespaceMapper { //nolint:revive // argument-limit doesn't apply to constructors
return NamespaceMapper{ctx, clt, apiReader, operatorNs, targetNs}
}
// MapFromNamespace adds the labels to the targetNs if there is a matching Dynakube
func (nm NamespaceMapper) MapFromNamespace() (bool, error) {
updatedNamespace, err := nm.updateNamespace()
if err != nil {
return false, err
}
return updatedNamespace, nil
}
func (nm NamespaceMapper) updateNamespace() (bool, error) {
deployedDynakubes := &dynatracev1beta1.DynaKubeList{}
err := nm.client.List(nm.ctx, deployedDynakubes)
if err != nil {
return false, errors.Cause(err)
}
return updateNamespace(nm.targetNs, deployedDynakubes)
}
|
package db
import (
"testing"
"time"
ps "pitchfork-analysis/pitchforkscrapper"
"github.com/stretchr/testify/suite"
)
type DBTestSuite struct {
db *DBAccessor
suite.Suite
}
func (d *DBTestSuite) SetupSuite() {
var err error
d.db, err = NewDBAccessor("testPitchfork.db")
d.NoError(err)
}
func (d *DBTestSuite) TearDownTest() {
_, err := d.db.Exec("DELETE FROM album")
d.NoError(err, "Failed to clear album table")
}
func (d *DBTestSuite) TestAddAlbum() {
testAlbum := ps.Album{
Artist: "test",
Genre: ps.Rap,
Title: "testAlbum",
Score: 10,
Date: time.Now(),
}
err := d.db.AddAlbum(&testAlbum)
d.NoError(err, "Could not insert the album")
d.Equal(0, 0)
}
func (d *DBTestSuite) TestGetAllArtistAlbums() {
testAlbum1 := ps.Album{
Artist: "test1",
Genre: ps.Rap,
Title: "testAlbum1",
Score: 10,
Date: time.Now(),
}
testAlbum2 := ps.Album{
Artist: "test1",
Genre: ps.Rap,
Title: "testAlbum2",
Score: 10,
Date: time.Now(),
}
// insert album by different artist. This should not be returned
testAlbum3 := ps.Album{
Artist: "test2",
Genre: ps.Rap,
Title: "testAlbum1",
Score: 10,
Date: time.Now(),
}
err := d.db.AddAlbum(&testAlbum1)
d.NoError(err, "Could not insert the album")
err = d.db.AddAlbum(&testAlbum2)
d.NoError(err, "Could not insert the album")
err = d.db.AddAlbum(&testAlbum3)
d.NoError(err, "Could not insert the album")
albums, err := d.db.GetAllArtistAlbums(testAlbum1.Artist)
d.NoError(err, "Could not get artist albums")
d.Len(albums, 2, "Two albums were inserted both should be returned")
}
func (d *DBTestSuite) TestGetAllAlbums_ReturnedInCorrectDateOrder() {
// returned first
testAlbum1 := ps.Album{
Artist: "test1",
Genre: ps.Rap,
Title: "testAlbum1",
Score: 10,
Date: time.Now(),
}
// returned second
testAlbum2 := ps.Album{
Artist: "test2",
Genre: ps.Rap,
Title: "testAlbum2",
Score: 10,
Date: time.Now().Add(time.Hour * 1),
}
testAlbum3 := ps.Album{
Artist: "test3",
Genre: ps.Rap,
Title: "testAlbum1",
Score: 10,
Date: time.Now().Add(time.Hour * 2),
}
err := d.db.AddAlbum(&testAlbum1)
d.NoError(err, "Could not insert the album")
err = d.db.AddAlbum(&testAlbum2)
d.NoError(err, "Could not insert the album")
err = d.db.AddAlbum(&testAlbum3)
d.NoError(err, "Could not insert the album")
albums, err := d.db.GetAllAlbums()
d.NoError(err, "Could not get artist albums")
d.Len(albums, 3, "three albums were inserted all should be returned")
d.Equal("test1", albums[0].Artist, "should be returned earliest date first")
d.Equal("test2", albums[1].Artist)
d.Equal("test3", albums[2].Artist)
}
func (d *DBTestSuite) TestGetAllAlbums_NoAlbums_EmptySliceReturned() {
albums, err := d.db.GetAllAlbums()
d.NoError(err, "Could not get artist albums")
d.Len(albums, 0, "There should be no albums")
}
func (d *DBTestSuite) TestGetAllArtistAlbums_NoAlbums_EmptySliceReturned() {
testEmptyArtist := "fakeartist"
albums, err := d.db.GetAllArtistAlbums(testEmptyArtist)
d.NoError(err, "Could not get artist albums")
d.Len(albums, 0, "There should be no albums")
}
func (d *DBTestSuite) TestGetAllGenreAlbums_ReturnedInCorrectDateOrder() {
// returned first
testAlbum1 := ps.Album{
Artist: "test1",
Genre: ps.Rap,
Title: "testAlbum1",
Score: 10,
Date: time.Now(),
}
// returned second
testAlbum2 := ps.Album{
Artist: "test2",
Genre: ps.Rap,
Title: "testAlbum2",
Score: 10,
Date: time.Now().Add(time.Hour * 1),
}
testAlbum3 := ps.Album{
Artist: "test3",
Genre: ps.Rap,
Title: "testAlbum1",
Score: 10,
Date: time.Now().Add(time.Hour * 2),
}
err := d.db.AddAlbum(&testAlbum1)
d.NoError(err, "Could not insert the album")
err = d.db.AddAlbum(&testAlbum2)
d.NoError(err, "Could not insert the album")
err = d.db.AddAlbum(&testAlbum3)
d.NoError(err, "Could not insert the album")
albums, err := d.db.GetAllGenreAlbums(ps.Rap)
d.NoError(err, "Could not get artist albums")
d.Len(albums, 3, "three rap albums were inserted all should be returned")
d.Equal("test1", albums[0].Artist, "should be returned earliest date first")
d.Equal("test2", albums[1].Artist)
d.Equal("test3", albums[2].Artist)
}
func (d *DBTestSuite) TestGetAllGenreAlbums_NoAlbumsInGenre_NoneReturned() {
// returned first
testAlbum1 := ps.Album{
Artist: "test1",
Genre: ps.Rap,
Title: "testAlbum1",
Score: 10,
Date: time.Now(),
}
// returned second
testAlbum2 := ps.Album{
Artist: "test2",
Genre: ps.Rap,
Title: "testAlbum2",
Score: 10,
Date: time.Now().Add(time.Hour * 1),
}
testAlbum3 := ps.Album{
Artist: "test3",
Genre: ps.Rap,
Title: "testAlbum1",
Score: 10,
Date: time.Now().Add(time.Hour * 2),
}
err := d.db.AddAlbum(&testAlbum1)
d.NoError(err, "Could not insert the album")
err = d.db.AddAlbum(&testAlbum2)
d.NoError(err, "Could not insert the album")
err = d.db.AddAlbum(&testAlbum3)
d.NoError(err, "Could not insert the album")
albums, err := d.db.GetAllGenreAlbums(ps.Electronic)
d.NoError(err, "Could not get artist albums")
d.Len(albums, 0, "three rap albums were inserted none should be returned")
}
func TestDBTestSuite(t *testing.T) {
suite.Run(t, new(DBTestSuite))
}
|
//go:build darwin
package main
import (
"fmt"
"os"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
"github.com/cloudflare/cloudflared/logger"
)
const (
launchdIdentifier = "com.cloudflare.cloudflared"
)
func runApp(app *cli.App, graceShutdownC chan struct{}) {
app.Commands = append(app.Commands, &cli.Command{
Name: "service",
Usage: "Manages the cloudflared launch agent",
Subcommands: []*cli.Command{
{
Name: "install",
Usage: "Install cloudflared as an user launch agent",
Action: cliutil.ConfiguredAction(installLaunchd),
},
{
Name: "uninstall",
Usage: "Uninstall the cloudflared launch agent",
Action: cliutil.ConfiguredAction(uninstallLaunchd),
},
},
})
_ = app.Run(os.Args)
}
func newLaunchdTemplate(installPath, stdoutPath, stderrPath string) *ServiceTemplate {
return &ServiceTemplate{
Path: installPath,
Content: fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>%s</string>
<key>ProgramArguments</key>
<array>
<string>{{ .Path }}</string>
{{- range $i, $item := .ExtraArgs}}
<string>{{ $item }}</string>
{{- end}}
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardOutPath</key>
<string>%s</string>
<key>StandardErrorPath</key>
<string>%s</string>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>ThrottleInterval</key>
<integer>5</integer>
</dict>
</plist>`, launchdIdentifier, stdoutPath, stderrPath),
}
}
func isRootUser() bool {
return os.Geteuid() == 0
}
func installPath() (string, error) {
// User is root, use /Library/LaunchDaemons instead of home directory
if isRootUser() {
return fmt.Sprintf("/Library/LaunchDaemons/%s.plist", launchdIdentifier), nil
}
userHomeDir, err := userHomeDir()
if err != nil {
return "", err
}
return fmt.Sprintf("%s/Library/LaunchAgents/%s.plist", userHomeDir, launchdIdentifier), nil
}
func stdoutPath() (string, error) {
if isRootUser() {
return fmt.Sprintf("/Library/Logs/%s.out.log", launchdIdentifier), nil
}
userHomeDir, err := userHomeDir()
if err != nil {
return "", err
}
return fmt.Sprintf("%s/Library/Logs/%s.out.log", userHomeDir, launchdIdentifier), nil
}
func stderrPath() (string, error) {
if isRootUser() {
return fmt.Sprintf("/Library/Logs/%s.err.log", launchdIdentifier), nil
}
userHomeDir, err := userHomeDir()
if err != nil {
return "", err
}
return fmt.Sprintf("%s/Library/Logs/%s.err.log", userHomeDir, launchdIdentifier), nil
}
func installLaunchd(c *cli.Context) error {
log := logger.CreateLoggerFromContext(c, logger.EnableTerminalLog)
if isRootUser() {
log.Info().Msg("Installing cloudflared client as a system launch daemon. " +
"cloudflared client will run at boot")
} else {
log.Info().Msg("Installing cloudflared client as an user launch agent. " +
"Note that cloudflared client will only run when the user is logged in. " +
"If you want to run cloudflared client at boot, install with root permission. " +
"For more information, visit https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/run-tunnel/run-as-service")
}
etPath, err := os.Executable()
if err != nil {
log.Err(err).Msg("Error determining executable path")
return fmt.Errorf("Error determining executable path: %v", err)
}
installPath, err := installPath()
if err != nil {
log.Err(err).Msg("Error determining install path")
return errors.Wrap(err, "Error determining install path")
}
extraArgs, err := getServiceExtraArgsFromCliArgs(c, log)
if err != nil {
errMsg := "Unable to determine extra arguments for launch daemon"
log.Err(err).Msg(errMsg)
return errors.Wrap(err, errMsg)
}
stdoutPath, err := stdoutPath()
if err != nil {
log.Err(err).Msg("error determining stdout path")
return errors.Wrap(err, "error determining stdout path")
}
stderrPath, err := stderrPath()
if err != nil {
log.Err(err).Msg("error determining stderr path")
return errors.Wrap(err, "error determining stderr path")
}
launchdTemplate := newLaunchdTemplate(installPath, stdoutPath, stderrPath)
templateArgs := ServiceTemplateArgs{Path: etPath, ExtraArgs: extraArgs}
err = launchdTemplate.Generate(&templateArgs)
if err != nil {
log.Err(err).Msg("error generating launchd template")
return err
}
plistPath, err := launchdTemplate.ResolvePath()
if err != nil {
log.Err(err).Msg("error resolving launchd template path")
return err
}
log.Info().Msgf("Outputs are logged to %s and %s", stderrPath, stdoutPath)
err = runCommand("launchctl", "load", plistPath)
if err == nil {
log.Info().Msg("MacOS service for cloudflared installed successfully")
}
return err
}
func uninstallLaunchd(c *cli.Context) error {
log := logger.CreateLoggerFromContext(c, logger.EnableTerminalLog)
if isRootUser() {
log.Info().Msg("Uninstalling cloudflared as a system launch daemon")
} else {
log.Info().Msg("Uninstalling cloudflared as a user launch agent")
}
installPath, err := installPath()
if err != nil {
return errors.Wrap(err, "error determining install path")
}
stdoutPath, err := stdoutPath()
if err != nil {
return errors.Wrap(err, "error determining stdout path")
}
stderrPath, err := stderrPath()
if err != nil {
return errors.Wrap(err, "error determining stderr path")
}
launchdTemplate := newLaunchdTemplate(installPath, stdoutPath, stderrPath)
plistPath, err := launchdTemplate.ResolvePath()
if err != nil {
log.Err(err).Msg("error resolving launchd template path")
return err
}
err = runCommand("launchctl", "unload", plistPath)
if err != nil {
log.Err(err).Msg("error unloading launchd")
return err
}
err = launchdTemplate.Remove()
if err == nil {
log.Info().Msg("Launchd for cloudflared was uninstalled successfully")
}
return err
}
|
package most_common_word
import (
"strings"
)
func mostCommonWord(paragraph string, banned []string) string {
buf := make([]byte, len(paragraph))
for i, c := range paragraph {
switch c {
case ',', '!', '?', '\'', ';', '.':
buf[i] = ' '
default:
buf[i] = toLower(byte(c))
}
}
bannedMap := make(map[string]bool)
for _, word := range banned {
bannedMap[word] = true
}
countMap := make(map[string]int)
max := 0
var res string
for _, word := range strings.Split(string(buf), " ") {
if len(word) == 0 {
continue
}
if _, ok := bannedMap[word]; ok {
continue
}
countMap[word]++
if v := countMap[word]; v > max {
res = word
max = v
}
}
return res
}
func toLower(c byte) byte {
if c >= 'A' && c <= 'Z' {
return c - 'A' + 'a'
}
return c
}
|
package client
import (
"encoding/binary"
"encoding/json"
"io"
"time"
"github.com/lthibault/log"
"github.com/urfave/cli/v2"
"github.com/libp2p/go-libp2p-core/peer"
pubsub "github.com/libp2p/go-libp2p-pubsub"
)
func subscribe() *cli.Command {
return &cli.Command{
Name: "subscribe",
Aliases: []string{"sub"},
Flags: subFlags(),
Action: subAction(),
}
}
func subFlags() []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "topic",
Aliases: []string{"t"},
Usage: "pubsub topic",
},
}
}
func subAction() cli.ActionFunc {
return func(c *cli.Context) error {
t, err := root.Join(c.String("topic"))
if err != nil {
return err
}
defer t.Close()
sub, err := t.Subscribe(ctx)
if err != nil {
return err
}
w := messagePrinter{
topic: c.String("topic"),
enc: jsonEncoder(c.App.Writer, c.Bool("prettyprint")),
}
for msg := range sub.C {
if err = w.PrintMessage(msg); err != nil {
break
}
}
return err
}
}
func jsonEncoder(w io.Writer, pretty bool) (enc *json.Encoder) {
if enc = json.NewEncoder(w); pretty {
enc.SetIndent("", " ")
}
return
}
type messagePrinter struct {
topic string
enc *json.Encoder
}
func (m messagePrinter) PrintMessage(msg *pubsub.Message) error {
if m.topic == "" {
return m.enc.Encode(struct {
Seq uint64 `json:"seq"`
ID peer.ID `json:"id"`
TTL time.Duration `json:"ttl"`
}{
ID: msg.GetFrom(),
Seq: seqno(msg),
TTL: ttl(msg),
})
}
// TODO(enhancement): support s-exprs (or EDN) using github.com/polydawn/refmt
if err := m.enc.Encode(msg.GetData); err != nil {
log.New().
WithField("topic", m.topic).
WithField("raw", string(msg.GetData())).
Warn("failed to render message (currently, only JSON is supported)")
return err
}
return nil
}
func seqno(msg *pubsub.Message) uint64 {
return binary.BigEndian.Uint64(msg.GetSeqno())
}
func ttl(msg *pubsub.Message) time.Duration {
d, _ := binary.Varint(msg.GetData())
return time.Duration(d)
}
|
// Funcao deveria retornar inteiro, porem retorna string
package main;
func retornoInteiro(a, b, c string) int {
return "123";
}; |
package main
import (
"encoding/json"
"testing"
"github.com/aws/aws-lambda-go/events"
)
func requestEvent(reqID, orgID, covID string) events.APIGatewayProxyRequest {
req := EligibilityRequest{
ResourceType: "EligibilityRequest",
ID: reqID,
Patient: ReferenceData{Reference: "deceased"},
Organization: ReferenceData{Reference: orgID},
Insurer: ReferenceData{Reference: "cygna"},
Coverage: ReferenceData{Reference: covID},
}
body, _ := json.Marshal(&req)
return events.APIGatewayProxyRequest{
Body: string(body),
}
}
func TestHandler(t *testing.T) {
t.Run("Bad Request", func(t *testing.T) {
respEvt, err := handler(events.APIGatewayProxyRequest{
Body: "BadRequest",
})
if err == nil {
t.Fatal("Error failed to trigger with a bad request")
}
if respEvt.StatusCode != 400 {
t.Fatalf("Response statusCode %d should be 400", respEvt.StatusCode)
}
})
t.Run("Successful Request", func(t *testing.T) {
respEvt, err := handler(requestEvent("test-1", "provider-1", "coverage-1"))
if err != nil {
t.Fatal("Everything should be ok")
}
if respEvt.StatusCode != 200 {
t.Fatalf("Response statusCode %d should be 200", respEvt.StatusCode)
}
})
}
|
package main
import (
"fmt"
)
type Node struct {
val int
next *Node
}
type Link struct {
head *Node
}
func (l Link) String() (s string) {
p := l.head
s = fmt.Sprintf("%d -> ", p.val)
for p.next != nil {
s += fmt.Sprintf("%d -> ", p.next.val)
p = p.next
}
return s
}
func main() {
l := Link{
head: &Node{
val: 1,
next: &Node{
val: 2,
next: &Node{
val: 3,
next: &Node{
val: 4,
next: nil,
},
},
},
},
}
fmt.Println(l)
ret := reverse(l)
fmt.Println(ret)
}
func reverse(l Link) Link {
if l.head == nil || l.head.next == nil {
return l
}
var p, q, r *Node
p = l.head
q = l.head.next
l.head.next = nil
for q != nil {
r = q.next
q.next = p
p = q
q = r
}
return Link{
head: p,
}
}
|
package internal
import (
"encoding/json"
"../pkg/device"
"../pkg/unit"
"net/http"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"strconv"
"log"
"os"
)
var Devices map[string]*device.Device = make(map[string]*device.Device)
var Units map[string]*unit.Unit = make(map[string]*unit.Unit)
func DeviceList(w http.ResponseWriter, r *http.Request){
log.Print("Device List Requested")
data,_ := json.Marshal(Devices)
fmt.Fprintln(w,string(data))
}
func DeviceDetail(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
name := vars["name"]
log.Print("Device Detail of ",name," Requested")
if _,ok := Devices[name];!ok{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"Undefined Device"})
fmt.Fprintln(w,string(errMsg))
return
}
data,_ := json.Marshal(Devices[name])
fmt.Fprintln(w,string(data))
}
func UnitList(w http.ResponseWriter, r *http.Request){
log.Print("Unit List Requested")
data,_ := json.Marshal(Units)
fmt.Fprintln(w,string(data))
}
func UnitDetail(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
name := vars["name"]
if _,ok := Units[name];!ok{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"Undefined Unit"})
fmt.Fprintln(w,string(errMsg))
return
}
token := r.URL.Query().Get("token")
if len(token) != 0 {
log.Print("Keep Connection")
token ,err:= strconv.ParseUint(token,10,64)
if err!=nil{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"The token is invalid format"})
fmt.Fprintln(w,string(errMsg))
return
}
order := Units[name].Queue.Order(token)
if order == -1 {
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"The token wasn't issued"})
fmt.Fprintln(w,string(errMsg))
}
Units[name].Queue[order - 1].Alive()
msg,_ := json.Marshal(map[string]interface{}{"Order":order})
fmt.Fprintln(w,string(msg))
return
}else{
log.Print("Unit Detail Requested")
data,_ := json.Marshal(Units[name])
fmt.Fprintln(w,string(data))
}
}
func MakeUnit(w http.ResponseWriter, r *http.Request){
log.Print("Unit Making")
var data interface{}
body, _ := ioutil.ReadAll(r.Body)
println(string(body))
err := json.Unmarshal(body,&data)
if err!=nil{
println("[ERROR]",err.Error())
}
units,ok := data.(map[string]interface{})
if !ok{
return
}
for unitName,devices := range units {
devices,ok := devices.(map[string]interface{})
if !ok {
continue
}
Units[unitName]=unit.NewUnit(unitName)
for deviceName,operables := range devices{
device, check1 := Devices[deviceName]
operables,check2 := operables.([]interface{})
if !check1 || !check2 {
continue
}
for _,operableName := range operables {
operableName, check := operableName.(string)
if !check{
continue
}
operable,ok := device.Operables[operableName]
if !ok{
continue
}
Units[unitName].Operables[operableName]=operable
}
}
}
}
func MakeBooking(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
name := vars["name"]
if _,ok := Units[name];!ok{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"Undefined Unit"})
fmt.Fprintln(w,string(errMsg))
return
}
token := Units[name].Book()
data,_ := json.Marshal(map[string]interface{}{"Token":token})
fmt.Fprintln(w,string(data))
}
func Operate(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
unitName := vars["name"]
operableName := vars["operable"]
unit,ok := Units[unitName]
if !ok{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"Undefined Unit"})
fmt.Fprintln(w,string(errMsg))
return
}
operable,ok := unit.Operables[operableName]
if !ok{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"Undefined Operable"})
fmt.Fprintln(w,string(errMsg))
return
}
query := r.URL.Query()
fmt.Printf("%#v\n",query)
tokenStr := query.Get("token")
if len(tokenStr) == 0 {
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"The token is empty"})
fmt.Fprintln(w,string(errMsg))
return
}
token ,err:= strconv.ParseUint(tokenStr,10,64)
if err!=nil{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"The token is invalid format"})
fmt.Fprintln(w,string(errMsg))
return
}
cmd := query.Get("cmd")
if len(cmd) == 0 {
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"The cmd is empty"})
fmt.Fprintln(w,string(errMsg))
return
}
if unit.Queue.IsFront(token) {
res,err := operable.Operate(query.Get("cmd"),query.Get("arg"))
if err!=nil{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":err.Error()})
fmt.Fprintln(w,string(errMsg))
return
}
response,_ := json.Marshal(map[string]interface{}{"Response":res})
fmt.Fprintln(w,string(response))
return
}
}
func LogFetch(w http.ResponseWriter, r *http.Request){
fd, err := os.Open("/tmp/iot_gateway.log")
if err != nil{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"Internal Log Error"})
fmt.Fprintln(w,string(errMsg))
return
}
defer fd.Close()
offsetStr := r.URL.Query().Get("offset")
offset := 0
if len(offsetStr) > 0{
offset ,err = strconv.Atoi(offsetStr)
if err != nil {
offset = 0
}
}
fd.Seek(int64(offset),0)
bytes,err := ioutil.ReadAll(fd)
if err!=nil{
errMsg,_ := json.Marshal(map[string]interface{}{"Error":"Internal Reading Error"})
fmt.Fprintln(w,string(errMsg))
return
}
response,_ := json.Marshal(map[string]interface{}{"Log":string(bytes),"Offset":offset+len(bytes)})
fmt.Fprintln(w,string(response))
return
}
|
package midware
import (
"sync"
)
type data struct {
Consumer, Method string
}
// easy to add, delete and iterate on channels
// (uses only keys)
type tunnels map[chan data]bool
type logmod struct {
sync.RWMutex
tunnels tunnels
}
func (l *logmod) share(consumer, method string) error {
logData := data{
Consumer: consumer,
Method: method,
}
l.RLock()
for waiter := range l.tunnels {
waiter <- logData
}
l.RUnlock()
return nil
}
type Logger interface {
NewTunnel() chan data
DeleteTunnel(chan data)
}
func (l *logmod) NewTunnel() chan data {
ch := make(chan data)
l.Lock()
l.tunnels[ch] = true
l.Unlock()
return ch
}
func (l *logmod) DeleteTunnel(ch chan data) {
l.Lock()
delete(l.tunnels, ch)
l.Unlock()
}
|
package packet
import (
"bytes"
"compress/flate"
"compress/gzip"
"io"
)
const (
COMPRESS_LEVEL = flate.BestCompression
)
func Compress(baseData []byte) ([]byte, error) {
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write(baseData)
w.Close()
return b.Bytes(), nil
}
func Decompress(compressed []byte) ([]byte, error) {
var b = bytes.NewBuffer(compressed)
r, err := gzip.NewReader(b)
var targetBuffer bytes.Buffer
io.Copy(&targetBuffer, r)
r.Close()
return targetBuffer.Bytes(), err
}
|
package main
import (
"fmt"
)
func main() {
g := "Google"
rg := reverse(g)
fmt.Println(rg)
}
func reverse(s string) string {
ss := []byte(s)
sl := len(ss)
for i := 0; i < sl/2; i++ {
ss[i], ss[sl-i-1] = ss[sl-i-1], ss[i]
}
return string(ss)
}
|
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"time"
"github.com/blang/semver"
mholt "github.com/mholt/archiver"
"github.com/mitchellh/go-homedir"
"github.com/olekukonko/tablewriter"
"github.com/rhysd/go-github-selfupdate/selfupdate"
"github.com/spf13/cobra"
)
func main() {
rootCmd.AddCommand(doCmd)
rootCmd.AddCommand(lsCmd)
rootCmd.AddCommand(createCmd)
rootCmd.AddCommand(readCmd)
if err := rootCmd.Execute(); err != nil {
os.Exit(-1)
}
}
var version = "0.0.1"
var rootCmd = &cobra.Command{
Use: "cli",
Version: version,
Short: "cli short description",
Long: "cli long description",
}
var doCmd = &cobra.Command{
Use: "do",
Short: "do short description",
Long: "do long description",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Doing something here...")
var total int64
mholt.Walk(args[0], func(f mholt.File) error {
if f.IsDir() {
fmt.Printf(" Dir: %d - %s\n", f.Size(), f.Name())
return nil
}
fmt.Printf("%d - %s\n", f.Size(), f.Name())
total += f.Size()
fmt.Printf("total: %d\n", total)
return nil
})
fmt.Printf("\ntotal size: %d\n", total)
fmt.Println("done")
},
}
var createCmd = &cobra.Command{
Use: "create",
Short: "create short description",
Long: "create long description",
Run: func(cmd *cobra.Command, args []string) {
dir := GetCredentialsDirectory()
fmt.Println("remove it")
os.RemoveAll(dir)
createFile(dir, "credentials")
},
}
var readCmd = &cobra.Command{
Use: "read",
Short: "read short description",
Long: "read long description",
Run: func(cmd *cobra.Command, args []string) {
dir := filepath.Join(GetCredentialsDirectory(), "credentials")
content, err := ioutil.ReadFile(dir)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Read from file: " + string(content))
file, err := os.Create(dir)
defer file.Close()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
now := time.Now().String()
_, err = file.WriteString(now)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Write again: " + now)
},
}
func createFile(directory, filename string) string {
var err error
if _, err = os.Stat(directory); os.IsNotExist(err) {
fmt.Println("MkdirAll: " + directory)
err = os.MkdirAll(directory, 0755)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("MkdirAll done")
}
path := filepath.Join(directory, filename)
fmt.Println("path: " + path)
if _, err = os.Stat(path); os.IsNotExist(err) {
var file *os.File
file, err = os.Create(path)
defer file.Close()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
now := time.Now().String()
_, err = file.WriteString(now)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Write: " + now)
}
fmt.Println("return path")
return path
}
func GetCredentialsDirectory() string {
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("home path: " + home)
path := filepath.Join(home, ".bc-cli")
fmt.Println("cli path:" + path)
return path
}
var lsCmd = &cobra.Command{
Use: "ls",
Short: "ls short description",
Long: "ls long description",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
data := make([][]string, 0)
filepath.Walk(args[0], func(path string, info os.FileInfo, err error) error {
content := make([]string, 0)
content = append(content, strconv.FormatInt(info.Size(), 10))
content = append(content, path)
data = append(data, content)
return nil
})
DisplayTable(data, "SIZE", "PATH")
},
}
func DisplayTable(data [][]string, title ...string) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(title)
table.SetBorders(tablewriter.Border{Left: false, Top: false, Right: false, Bottom: false})
table.SetHeaderLine(false)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowSeparator("")
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoWrapText(false)
table.AppendBulk(data)
table.Render()
}
func selfUpdate() {
fmt.Println("self updating...")
latest, found, err := selfupdate.DetectLatest("HeroBcat/cli-releases")
if err != nil {
fmt.Println("Error occurred while detecting version:", err)
return
}
v := semver.MustParse(version)
if !found || latest.Version.LTE(v) {
fmt.Println("Current version is the latest")
return
}
exe, err := os.Executable()
if err != nil {
fmt.Println("Could not locate executable path")
return
}
if err := selfupdate.UpdateTo(latest.AssetURL, exe); err != nil {
fmt.Println("Error occurred while updating binary:", err)
return
}
fmt.Println("Successfully updated to version", latest.Version)
}
|
package engine
import (
"bytes"
"container/list"
"encoding/gob"
"io/ioutil"
"log"
)
type HMMParser struct {
scanner *Scanner
TagCounts map[string]int64
WordCounts map[string]map[string]int64
TagBigramCounts map[string]map[string]int64
TagForWordCounts map[string]map[string]int64
MostFreqTag string
MostFreqTagCount int64
NumTrainingBigrams int64
}
func NewHMMParser(filename string) HMMParser {
file, err := ioutil.ReadFile(filename)
if err != nil {
log.Panicln(err.Error())
}
scanner := NewScannerString(string(file))
return HMMParser{
scanner: scanner,
TagCounts: make(map[string]int64),
WordCounts: make(map[string]map[string]int64),
TagBigramCounts: make(map[string]map[string]int64),
TagForWordCounts: make(map[string]map[string]int64),
MostFreqTag: "",
MostFreqTagCount: 0,
NumTrainingBigrams: 0,
}
}
func (this *HMMParser) FParseTrainer() {
prevTag := this.scanner.Next()
this.scanner.Next()
for this.scanner.HasNext() {
currentTag := this.scanner.Next()
currentWord := this.scanner.Next()
this.f2AddOne(this.TagCounts, currentTag)
this.f3AddOne(this.WordCounts, currentTag, currentWord)
this.f3AddOne(this.TagBigramCounts, prevTag, currentTag)
this.f3AddOne(this.TagForWordCounts, currentWord, currentTag)
if this.TagCounts[currentTag] >= this.MostFreqTagCount {
this.MostFreqTagCount = this.TagCounts[currentTag]
this.MostFreqTag = currentTag
}
this.NumTrainingBigrams++
prevTag = currentTag
}
}
func (this *HMMParser) FWordSequence() *list.List {
l := list.New()
for this.scanner.HasNext() {
this.scanner.Next()
l.PushBack(this.scanner.Next())
}
return l
}
func (this *HMMParser) f2AddOne(m map[string]int64, key1 string) {
m[key1]++
}
func (this *HMMParser) f3AddOne(m map[string]map[string]int64, key1 string, key2 string) {
if _, exists := m[key1]; exists {
this.f2AddOne(m[key1], key2)
} else {
sm := make(map[string]int64)
sm[key2] = 1
m[key1] = sm
}
}
func (this *HMMParser) Save() {
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
err := enc.Encode(this)
if err != nil {
log.Panicln(err)
}
err = ioutil.WriteFile("hmm.dat", m.Bytes(), 0600)
if err != nil {
log.Panicln(err)
}
}
func (this *HMMParser) Load() {
n, err := ioutil.ReadFile("hmm.dat")
if err != nil {
log.Println(err.Error())
this.FParseTrainer()
this.Save()
} else {
var hmmParser HMMParser
p := bytes.NewBuffer(n)
dec := gob.NewDecoder(p)
err = dec.Decode(&hmmParser)
if err != nil {
log.Println(err.Error())
} else {
this.TagCounts = hmmParser.TagCounts
this.WordCounts = hmmParser.WordCounts
this.TagBigramCounts = hmmParser.TagBigramCounts
this.TagForWordCounts = hmmParser.TagForWordCounts
this.MostFreqTag = hmmParser.MostFreqTag
this.MostFreqTagCount = hmmParser.MostFreqTagCount
this.NumTrainingBigrams = hmmParser.NumTrainingBigrams
}
}
}
|
// Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// 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 common
const (
// MeasurementsHeadCluster is the cluster row identifier in the measurement file.
MeasurementsHeadCluster = "cluster"
// MeasurementsHeadProvider is the provider row identifier in the measurement file.
MeasurementsHeadProvider = "provider"
// MeasurementsHeadSeed is the seed row identifier in the measurement file.
MeasurementsHeadSeed = "seed"
// MeasurementsHeadTimestamp is the timestamp row identifier in the measurement file.
MeasurementsHeadTimestamp = "timestamp"
// MeasurementsHeadStatusCode is the status code row identifier in the measurement file.
MeasurementsHeadStatusCode = "status_code"
// MeasurementsHeadResponseTime is the response time row identifier in the measurement file.
MeasurementsHeadResponseTime = "response_time_ms"
// ReportOutputFormatText is the identifier for the report output format text.
ReportOutputFormatText = "text"
// ReportOutputFormatJSON is the identifier for the report output format json.
ReportOutputFormatJSON = "json"
// CliFlagLogLevel is the cli flag to specify the log level.
CliFlagLogLevel = "log-level"
// CliFlagReportOutput is the cli flag which passes the report file destination.
CliFlagReportOutput = "report"
// CliFlagReportFormat is the cli flag which passes the report output format.
CliFlagReportFormat = "format"
// CliFlagHelpTextReportFile is the help text for the cli flag which passes the report file destination.
CliFlagHelpTextReportFile = "path to the report file"
// CliFlagHelpTextReportFormat is the help text for the cli flag which passes the report output format.
CliFlagHelpTextReportFormat = "output format of the report: text|json"
// CliFlagHelpLogLevel is the help text for the cli flag which specify the log level.
CliFlagHelpLogLevel = "log level: error|info|debug"
// LogDebugAddPrefix is a prefix for controller add operations debug log outputs.
LogDebugAddPrefix = "[ADD]"
// LogDebugUpdatePrefix is a prefix for controller update operations debug log outputs.
LogDebugUpdatePrefix = "[UPDATE]"
// DefaultLogLevel define the default log level.
DefaultLogLevel = "info"
// RequestTimeOut is the timeout for a health check to the ApiServer.
RequestTimeOut int = 5000
)
|
package mqtt
import (
mqttclient "github.com/bernardolm/iot/sensors-publisher-go/mqtt"
log "github.com/sirupsen/logrus"
)
type mqtt struct{}
func (a *mqtt) Publish(topic string, message interface{}) error {
if message == nil {
return nil
}
log.WithField("topic", topic).WithField("message", message).WithField("publisher", "mqtt").
Debug("publishing")
mqttclient.Publish(topic, message)
return nil
}
func New() *mqtt {
return &mqtt{}
}
|
/*
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package p2p
import (
"github.com/aergoio/aergo/types"
"github.com/gofrs/uuid"
)
type V020Wrapper struct {
*types.P2PMessage
originalID string
}
func NewV020Wrapper(message *types.P2PMessage, originalID string) *V020Wrapper {
return &V020Wrapper{message, originalID}
}
func (m *V020Wrapper) Subprotocol() SubProtocol {
return SubProtocol(m.Header.Subprotocol)
}
func (m *V020Wrapper) Length() uint32 {
return m.Header.Length
}
func (m *V020Wrapper) Timestamp() int64 {
return m.Header.Timestamp
}
func (m *V020Wrapper) ID() MsgID {
return uuidStrToMsgID(m.Header.Id)
}
func (m *V020Wrapper) OriginalID() MsgID {
return uuidStrToMsgID(m.originalID)
}
func (m *V020Wrapper) Payload() []byte {
return m.Data
}
var _ Message = (*V020Wrapper)(nil)
func uuidStrToMsgID(str string) (id MsgID) {
uuid, err := uuid.FromString(str)
if err != nil {
return
}
copy(id[:], uuid[:])
return
} |
package utils
import (
"log"
"net"
"strconv"
"github.com/guoruibiao/ipservice/constants"
"net/http"
"io/ioutil"
"encoding/json"
"strings"
"github.com/pkg/errors"
)
func IpNToA(ip string) net.IP {
if len(ip) >= 18 {
runes := []rune(ip)
ip = string(runes[0:18])
}
ipInt64, err := strconv.ParseInt(ip, 10, 64)
if err != nil {
log.Fatalf("convert %s failed", ip)
}
var bytes [4]byte
bytes[0] = byte(ipInt64 & 0xFF)
bytes[1] = byte((ipInt64 >> 8) & 0xFF)
bytes[2] = byte((ipInt64 >> 16) & 0xFF)
bytes[3] = byte((ipInt64 >> 24) & 0xFF)
return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0])
}
func GetOfficialData(ip string) (*constants.Entry, error) {
if len(strings.Split(ip, "."))!=4 {
return nil, errors.New("ip:" + ip + " format error. Should be like xx.xx.xx.xx")
}
resp, err := http.Get(constants.IPIP_OFFICIAL_URL + ip)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var decoded []string
err = json.Unmarshal(body, &decoded)
if err != nil {
return nil, err
}
entry := &constants.Entry{
RegionName:decoded[1],
CityName:decoded[2],
}
return entry, nil
} |
// 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.
// +build linux darwin
package shell_test
import (
"bytes"
"context"
"github.com/google/gapid/core/log"
"github.com/google/gapid/core/os/shell"
)
func newCtx() context.Context {
ctx := context.Background()
ctx = log.PutClock(ctx, log.NoClock)
ctx = log.PutHandler(ctx, log.Normal.Handler(log.Stdout()))
ctx = log.Enter(ctx, "Example")
return ctx
}
// This example shows how to run a command, wait for it to complete and check if it succeeded.
func ExampleSilent() {
ctx := newCtx()
err := shell.Command("echo", "Hello from the shell").Run(ctx)
if err != nil {
log.F(ctx, true, "Unable to say hello: %v", err)
}
log.I(ctx, "Done")
// Output:
//I: [Example] Done
}
// This example shows how to run a command, with it's standard out and error being logged.
func ExampleVerbose() {
ctx := newCtx()
err := shell.Command("echo", "Hello", "from the shell").Verbose().Run(ctx)
if err != nil {
log.F(ctx, true, "Unable to say hello: %v", err)
}
// Output:
//I: [Example] Exec: echo Hello "from the shell"
//I: [Example] <echo> Hello from the shell
}
// This example shows how to run a command and capture it's output.
func ExampleCapture() {
ctx := newCtx()
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
echo := shell.Command("echo").Verbose().Capture(stdout, stderr)
echo.With("First echo").Run(ctx)
echo.With("Second echo").Run(ctx)
log.I(ctx, "<{<%s}>", stdout.String())
log.W(ctx, "<!{<%s}!>", stderr.String())
// Output:
//I: [Example] Exec: echo "First echo"
//I: [Example] <echo> First echo
//I: [Example] Exec: echo "Second echo"
//I: [Example] <echo> Second echo
//I: [Example] <{<First echo
//Second echo
//}>
//W: [Example] <!{<}!>
}
|
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
// https://adventofcode.com/2019/day/11
type Op struct {
code, params int
}
func (op Op) String() string {
return fmt.Sprintf("Op{code: %d, params: %d}", op.code, op.params)
}
var OpAdd Op = Op{code: 1, params: 3}
var OpMlt Op = Op{code: 2, params: 3}
var OpInp Op = Op{code: 3, params: 1}
var OpOut Op = Op{code: 4, params: 1}
var OpIft Op = Op{code: 5, params: 2}
var OpIff Op = Op{code: 6, params: 2}
var OpLss Op = Op{code: 7, params: 3}
var OpEql Op = Op{code: 8, params: 3}
var OpRlo Op = Op{code: 9, params: 1}
var OpHlt Op = Op{code: 99, params: 0}
const (
ModePos = 0
ModeImm = 1
ModeRel = 2
ColorBlack = 0
ColorWhite = 1
OrientationUp = 0
OrientationRt = 1
OrientationDn = 2
OrientationLt = 3
TurnLt = 0
TurnRt = 1
)
func check(err error) {
if err != nil {
panic(err)
}
}
func parseOp(opInt int) (Op, []int) {
code := opInt % 100
opInt /= 100 // shave off code
var op Op
switch code {
case OpAdd.code:
op = OpAdd
case OpMlt.code:
op = OpMlt
case OpInp.code:
op = OpInp
case OpOut.code:
op = OpOut
case OpIft.code:
op = OpIft
case OpIff.code:
op = OpIff
case OpLss.code:
op = OpLss
case OpEql.code:
op = OpEql
case OpRlo.code:
op = OpRlo
case OpHlt.code:
op = OpHlt
default:
panic(fmt.Sprintf("Unexpected Op code: %d", code))
}
modes := make([]int, op.params)
for i := 0; i < len(modes); i++ {
modes[i] = opInt % 10
opInt /= 10
}
return op, modes
}
func getParams(prog map[int]int, offset int, modes []int, relBase int) []int {
params := make([]int, len(modes))
for i := 0; i < len(params); i++ {
mode := modes[i]
switch mode {
case ModePos:
params[i] = prog[offset+i]
case ModeImm:
params[i] = offset + i
case ModeRel:
params[i] = prog[offset+i] + relBase
default:
panic(fmt.Sprintf("Unexpected param mode: %d", mode))
}
}
return params
}
func compute(prog map[int]int, input, output chan int) {
ptr, relBase := 0, 0
for {
op, modes := parseOp(prog[ptr])
if op.code == OpHlt.code {
close(output)
return
}
params := getParams(prog, ptr+1, modes, relBase)
switch op.code {
case OpAdd.code:
prog[params[2]] = prog[params[0]] + prog[params[1]]
case OpMlt.code:
prog[params[2]] = prog[params[0]] * prog[params[1]]
case OpInp.code:
prog[params[0]] = <-input
case OpOut.code:
output <- prog[params[0]]
case OpIft.code:
if prog[params[0]] != 0 {
ptr = prog[params[1]]
continue
}
case OpIff.code:
if prog[params[0]] == 0 {
ptr = prog[params[1]]
continue
}
case OpLss.code:
if prog[params[0]] < prog[params[1]] {
prog[params[2]] = 1
} else {
prog[params[2]] = 0
}
case OpEql.code:
if prog[params[0]] == prog[params[1]] {
prog[params[2]] = 1
} else {
prog[params[2]] = 0
}
case OpRlo.code:
relBase += prog[params[0]]
default:
panic(fmt.Sprintf("Unexpected OpCode: %d", op.code))
}
ptr += op.params + 1
}
}
type Point struct {
x, y int
}
func printCanvas(canvas map[Point]int) {
x_min, y_min, x_max, y_max := 0, 0, 0, 0
for p := range canvas {
if p.x < x_min {
x_min = p.x
}
if p.y < y_min {
y_min = p.y
}
if p.x > x_max {
x_max = p.x
}
if p.y > y_max {
y_max = p.y
}
}
for i := x_min; i <= x_max; i++ {
for j := y_min; j <= y_max; j++ {
if canvas[Point{i, j}] > 0 {
fmt.Printf("#")
} else {
fmt.Printf(" ")
}
}
fmt.Printf("\n")
}
}
func move(pos Point, orientation, turn int) (Point, int) {
newOrientation := orientation
switch turn {
case TurnLt:
if orientation == OrientationUp {
newOrientation = OrientationLt
} else {
newOrientation--
}
case TurnRt:
newOrientation++
newOrientation %= 4
default:
panic(fmt.Sprintf("Invalid turn: %s", turn))
}
newPos := pos
switch newOrientation {
case OrientationUp:
newPos.y++
case OrientationRt:
newPos.x++
case OrientationDn:
newPos.y--
case OrientationLt:
newPos.x--
default:
panic(fmt.Sprintf("Invalid orientation: %d", newOrientation))
}
return newPos, newOrientation
}
func main() {
if len(os.Args) != 2 {
panic("No input file specified!")
}
fname := os.Args[1]
file, err := ioutil.ReadFile(fname)
check(err)
ss := strings.Split(string(file), ",")
// use a map to allow prog to exand itself, write past initial size
prog := make(map[int]int, len(ss))
for i, s := range ss {
num, err := strconv.Atoi(strings.Trim(s, "\n "))
check(err)
prog[i] = num
}
input := make(chan int, 1)
output := make(chan int, 2)
canvas := make(map[Point]int)
pos := Point{0, 0}
orientation := OrientationUp
go compute(prog, input, output)
canvas[pos] = ColorWhite
input <- canvas[pos]
for color := range output {
switch color {
case ColorBlack:
canvas[pos] = ColorBlack
case ColorWhite:
canvas[pos] = ColorWhite
default:
panic(fmt.Sprintf("Invalid color: %d", color))
}
turn := <-output
pos, orientation = move(pos, orientation, turn)
input <- canvas[pos]
}
printCanvas(canvas)
}
|
package daemon
import (
"github.com/hyperhq/hyper/engine"
"github.com/hyperhq/runv/lib/glog"
)
func (daemon *Daemon) CmdRename(job *engine.Job) error {
oldname := job.Args[0]
newname := job.Args[1]
cli := daemon.DockerCli
err := cli.SendContainerRename(oldname, newname)
if err != nil {
return err
}
daemon.PodsMutex.RLock()
glog.V(2).Infof("lock read of PodList")
defer glog.V(2).Infof("unlock read of PodList")
defer daemon.PodsMutex.RUnlock()
var find bool = false
for _, p := range daemon.PodList {
for _, c := range p.Containers {
if c.Name == "/"+oldname {
c.Name = "/" + newname
find = true
}
}
if find == true {
break
}
}
v := &engine.Env{}
v.Set("ID", newname)
v.SetInt("Code", 0)
v.Set("Cause", "")
if _, err := v.WriteTo(job.Stdout); err != nil {
return err
}
return nil
}
|
// Copyright (C) 2016-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 brokercontext
import "context"
type correlationIDType int
const (
operationKey correlationIDType = iota
requestIDKey correlationIDType = iota
serviceNameKey correlationIDType = iota
instanceIDKey correlationIDType = iota
boshTaskIDKey correlationIDType = iota
)
func New(ctx context.Context, operation, requestID, serviceName, instanceID string) context.Context {
ctx = WithOperation(ctx, operation)
ctx = WithReqID(ctx, requestID)
ctx = WithServiceName(ctx, serviceName)
ctx = WithInstanceID(ctx, instanceID)
return ctx
}
func WithOperation(ctx context.Context, operation string) context.Context {
return context.WithValue(ctx, operationKey, operation)
}
func GetOperation(ctx context.Context) string {
operation, _ := ctx.Value(operationKey).(string)
return operation
}
func WithReqID(ctx context.Context, reqID string) context.Context {
return context.WithValue(ctx, requestIDKey, reqID)
}
func GetReqID(ctx context.Context) string {
reqID, _ := ctx.Value(requestIDKey).(string)
return reqID
}
func WithServiceName(ctx context.Context, serviceName string) context.Context {
return context.WithValue(ctx, serviceNameKey, serviceName)
}
func GetServiceName(ctx context.Context) string {
serviceName, _ := ctx.Value(serviceNameKey).(string)
return serviceName
}
func WithInstanceID(ctx context.Context, instanceID string) context.Context {
return context.WithValue(ctx, instanceIDKey, instanceID)
}
func GetInstanceID(ctx context.Context) string {
instanceID, _ := ctx.Value(instanceIDKey).(string)
return instanceID
}
func WithBoshTaskID(ctx context.Context, boshTaskID int) context.Context {
return context.WithValue(ctx, boshTaskIDKey, boshTaskID)
}
func GetBoshTaskID(ctx context.Context) int {
boshTaskID, _ := ctx.Value(boshTaskIDKey).(int)
return boshTaskID
}
|
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
)
func ToJSON(w io.Writer) error {
var result = json.NewEncoder(w).Encode(&struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}{
"Foo",
"Bar",
})
return result
}
func main() {
var b bytes.Buffer
w := bufio.NewWriter(&b)
if err := ToJSON(w); err != nil {
fmt.Fprintln(os.Stderr, "error writing json: %s", err)
}
w.Flush()
fmt.Println(string(b.Bytes()))
}
|
package main
import (
"fmt"
"os"
)
func main() {
file := os.Args[1]
err := os.Rename(file, "1.rename.txt")
if err != nil {
fmt.Println("not ok")
} else {
fmt.Println("ok")
}
}
|
package keepassrpc
import (
"encoding/json"
"fmt"
"log"
"strings"
"github.com/gorilla/websocket"
)
// MsgError represents an error in the KeePassRPC protocol
type MsgError struct {
Code string `json:"code"`
MessageParams []string `json:"messageParams"`
}
// MsgJSONRPC represents various stages of the JSON RPC protocol
type MsgJSONRPC struct {
Message []byte `json:"message"`
IV []byte `json:"iv"`
HMAC []byte `json:"hmac"`
}
// Message represents a single complete KeePassRPC message
type Message struct {
// Mandatory values
Protocol string `json:"protocol"`
Version uint32 `json:"version"`
JSONRPC *MsgJSONRPC `json:"jsonrpc,omitempty"`
Error *MsgError `json:"error,omitempty"`
SRP *MsgSRP `json:"srp,omitempty"`
Key *MsgKey `json:"key,omitempty"`
ClientID string `json:"clientTypeID,omitempty"`
ClientName string `json:"clientDisplayName,omitempty"`
ClientDesc string `json:"clientDisplayDescription,omitempty"`
Features []string `json:"features,omitempty"`
}
// ReadMessage reads a message from the server and JSON-decodes it
func ReadMessage(h *websocket.Conn) (*Message, error) {
var data Message
if DebugClient {
_, msg, err := h.ReadMessage()
if err != nil {
return nil, err
}
log.Println("<<<", string(msg))
if err := json.Unmarshal(msg, &data); err != nil {
return nil, err
}
} else {
if err := h.ReadJSON(&data); err != nil {
return nil, err
}
}
return &data, nil
}
// WriteMessage JSON-encodes a KeePassRPC message and sends it to the server
func WriteMessage(h *websocket.Conn, msg *Message) error {
if DebugClient {
out, err := json.Marshal(msg)
if err != nil {
return err
}
log.Println(">>>", string(out))
if err := h.WriteMessage(websocket.TextMessage, out); err != nil {
return err
}
} else {
if err := h.WriteJSON(&msg); err != nil {
return err
}
}
return nil
}
// DispatchError handles error protocol packets from the server
func DispatchError(err *MsgError) error {
return fmt.Errorf("%s: %s", err.Code, strings.Join(err.MessageParams, "\n"))
}
|
package database
import (
"database/sql"
"log"
// Wraps database/sql for postgres
_ "github.com/lib/pq"
"poker/connection"
"poker/gamelogic"
"poker/models"
)
func CreateDatabase(username string, password string, name string) (database *sql.DB, err error) {
log.Print("Connecting to the database server...")
// Save information about our database in a string
dbinfo := "user=" + username + " password=" + password + " dbname=" + name + " sslmode=disable"
// Open the database (using the postgres driver) and pass in the database info we saved earlier
db, err := sql.Open("postgres", dbinfo)
if err != nil {
return nil, err
}
// Check whether or not the database is running (db.Open only validates arguments)
err = db.Ping()
if err != nil {
return nil, err
}
return db, nil
}
func InitializeGames(env *models.Env, gameMap map[string]*models.GameListing) {
log.Print("Initializing game objects from database...")
for _, listing := range gameMap {
game, err := gamelogic.GameInit(listing.Ante, listing.MinBet, listing.MaxBet)
if err != nil {
log.Fatal(err)
}
listing.Game = game
// Create a new websockets hub
hub := connection.NewHub()
listing.Hub = hub
}
env.Games = gameMap
}
|
package globe
import (
"os"
"fmt"
"io/ioutil"
"bytes"
"testing"
)
var data = []byte(`
version: 1234
translations:
PICKLES:
en.US: Pickles
de.DE: Gurken
es.ES: Pepinillos
TOMATO:
en.US: Tomato
de.DE: Tomate
es.ES: Tomate
FRUIT:
en.US: Fruit
de.DE: Frucht
es.ES: Fruta
`)
var badData = []byte(`
PICKLES:
en.US:
- Pickles
- Guac
- de.DE: Gurken
- es.MX: Pepinillos
TOMATO:
- en.US
- Tomato
- de.DE
- Tomate
- es.ES
- Tomate
`)
func TestLoadDB(t *testing.T) {
_, err := LoadDB(data)
if err != nil {
t.Errorf("Failed to load globe DB with LoadDB: %s", err)
}
}
func TestLoadDBFromReader(t *testing.T) {
reader := bytes.NewReader(data)
_, err := LoadDBFromReader(reader)
if err != nil {
t.Errorf("Failed to load globe DB with LoadDBFromReader: %s", err)
}
}
func TestLoadDBFromFile(t *testing.T) {
tmpFile, err := ioutil.TempFile("/tmp", "test.*.yml")
name := tmpFile.Name()
if err != nil {
t.Errorf("Failed to open temporary file: %s", err)
}
defer os.Remove(name)
_, err = tmpFile.Write(data)
tmpFile.Close() // Close regardless
if err != nil {
t.Errorf("Failed to write temporary file: %s", err)
}
_, err = LoadDBFromFile(name)
if err != nil {
t.Errorf("Failed to load globe DB with LoadDBFromReader(%s): %s", name, err)
}
}
func TestLoadDBFail(t *testing.T) {
_, err := LoadDB(badData)
if err == nil {
t.Errorf("Failed to load globe DB with LoadDB: %s", err)
}
}
func TestLoadDBFromReaderFail(t *testing.T) {
reader := bytes.NewReader(badData)
_, err := LoadDBFromReader(reader)
if err == nil {
t.Errorf("Expected error from LoadDBFromReader: %s", err)
}
}
func TestLoadDBFromFileFail(t *testing.T) {
tmpFile, err := ioutil.TempFile("/tmp", "test.*.yml")
name := tmpFile.Name()
if err != nil {
t.Errorf("Failed to open temporary file: %s", err)
}
defer os.Remove(name)
_, err = tmpFile.Write(badData)
tmpFile.Close() // Close regardless
if err != nil {
t.Errorf("Failed to write temporary file: %s", err)
}
_, err = LoadDBFromFile(name)
if err == nil {
t.Errorf("Expected error from LoadDBFromReader(%s): %s", name, err)
}
}
func TestLookupAll(t *testing.T) {
g, err := LoadDB(data)
if err != nil {
t.Errorf("Failed to load globe DB with LoadDB: %s", err)
}
//fmt.Printf("Got: %#v\n", g.LookupAll("en.US"))
expected := map[string]string {
"PICKLES": "Pickles",
"TOMATO": "Tomato",
}
actual := g.LookupAll("en.US")
for k, v := range expected {
if actual[k] != v {
t.Errorf("Expected actual[%s] == <%s>, but got actual[%s] == <%s>.\n",
k, v, k, actual[k])
}
}
expected = map[string]string {
"PICKLES": "Gurken",
"TOMATO": "Tomate",
}
actual = g.LookupAll("de.DE")
for k, v := range expected {
if actual[k] != v {
t.Errorf("Expected actual[%s] == <%s>, but got actual[%s] == <%s>.\n",
k, v, k, actual[k])
}
}
}
func tryLookup(g *GlobeDB, str, lang string) {
fmt.Printf("Looking up %s, %s ... ", str, lang)
str, err := g.Lookup(str, lang)
if err != nil {
fmt.Printf("Error: %s\n", err)
return
}
fmt.Printf("Found: %s\n", str)
}
func ExampleLookups() {
globeDB, err := LoadDB(data)
if err != nil {
fmt.Printf("Failed to load Globetrotter db: %s\n", err)
return
}
tryLookup(globeDB, "PICKLES", "en.US")
tryLookup(globeDB, "PICKLES", "de.DE")
tryLookup(globeDB, "PICKLES", "es.MX")
tryLookup(globeDB, "TOMATO", "en.US")
tryLookup(globeDB, "TOMATO", "de.DE")
tryLookup(globeDB, "TOMATO", "es.ES")
tryLookup(globeDB, "FRUIT", "en.US")
tryLookup(globeDB, "FRUIT", "de.DE")
tryLookup(globeDB, "FRUIT", "es.ES")
tryLookup(globeDB, "PICKLES", "fr.FR")
tryLookup(globeDB, "HOT_POCKETS", "en.US")
// Output:
// Looking up PICKLES, en.US ... Found: Pickles
// Looking up PICKLES, de.DE ... Found: Gurken
// Looking up PICKLES, es.MX ... Error: Translation es.MX not found for string PICKLES
// Looking up TOMATO, en.US ... Found: Tomato
// Looking up TOMATO, de.DE ... Found: Tomate
// Looking up TOMATO, es.ES ... Found: Tomate
// Looking up FRUIT, en.US ... Found: Fruit
// Looking up FRUIT, de.DE ... Found: Frucht
// Looking up FRUIT, es.ES ... Found: Fruta
// Looking up PICKLES, fr.FR ... Error: Translation fr.FR not found for string PICKLES
// Looking up HOT_POCKETS, en.US ... Error: No such string HOT_POCKETS
}
|
package main
import (
"testing"
)
func TestCode(t *testing.T) {
var tests = []struct {
n int
a int
b int
output []int
}{
{
n: 3, a: 1, b: 2,
output: []int{2, 3, 4},
},
{
n: 4, a: 10, b: 100,
output: []int{30, 120, 210, 300},
},
}
for _, test := range tests {
got := manasaStones(test.n, test.a, test.b)
for i, v := range got {
if v != test.output[i] {
t.Errorf(
"For Stones=%v DiffA=%v DiffB=%v; Got %v while expecting %v",
test.n, test.a, test.b, got, test.output,
)
}
}
}
}
|
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package platform
import (
"bytes"
"context"
"regexp"
"strings"
"chromiumos/tast/common/testexec"
"chromiumos/tast/shutil"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: Crossystem,
Desc: "Checks the crossystem command's basic functionality",
Contacts: []string{
"mka@chromium.org",
"kasaiah.bogineni@intel.com", // Port author
"tast-users@chromium.org",
},
SoftwareDeps: []string{"crossystem"},
Attr: []string{"group:mainline", "group:labqual", "group:intel-gating"},
})
}
// Crossystem checks that the "crossystem" command's basic functionality.
// This includes commands that rely on the presence and correct
// initialization of the chromeos driver (drivers/platform/chromeos.c)
// in the kernel
func Crossystem(ctx context.Context, s *testing.State) {
const (
crossystemCmd = "crossystem"
alphaNum = `^[\d\w]+$`
num = `^[\d]+$`
hexNum = `^0x[\da-fA-F]+$`
bit = `^[01]$`
anything = "" // match everything that isn't an error or empty
)
cmdRegexMap := map[string]string{
"cros_debug": bit,
"debug_build": bit,
"devsw_boot": bit,
"devsw_cur": bit,
"fwid": anything,
"hwid": anything,
"loc_idx": num,
"mainfw_act": alphaNum,
"mainfw_type": alphaNum,
"ro_fwid": anything,
"tpm_fwver": hexNum,
"tpm_kernver": hexNum,
"wpsw_cur": bit,
}
checkOutput := func(pattern string, out []byte) bool {
if pattern == anything {
return strings.TrimSpace(string(out)) != "" && strings.TrimSpace(string(out)) != "(error)"
}
return regexp.MustCompile(pattern).Match(bytes.TrimSpace(out))
}
for subCommand, regExp := range cmdRegexMap {
cmd := testexec.CommandContext(ctx, crossystemCmd, subCommand)
output, err := cmd.Output(testexec.DumpLogOnError)
if err != nil {
s.Errorf("%q failed: %v", shutil.EscapeSlice(cmd.Args), err)
} else if !checkOutput(regExp, output) {
s.Errorf("%q printed %q, which isn't matched by %q", shutil.EscapeSlice(cmd.Args), output, regExp)
}
}
}
|
/*
*Copyright (c) 2019-2021, Alibaba Group Holding Limited;
*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 core_version
import (
"fmt"
config "gitlab.alibaba-inc.com/rds/polarstack-daemon/cmd/daemon/app/config"
"gitlab.alibaba-inc.com/rds/polarstack-daemon/polar-controller-manager/util"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/klog"
"strings"
"time"
)
// StartCheckCoreVersion
/**
* @Title: StartCheckCoreVersion
* @Description: 开始等待 检查 core version 的指令
**/
func StartCheckCoreVersion(client *clientset.Clientset) {
polarStackDaemonLabels = config.Conf.PolarStackDaemonPodLabels
coreVersionConfigMapLabel = config.Conf.CoreVersionConfigMapLabel
for {
klog.Infof("%s StartCheckCoreVersion ", logInfoTarget)
klog.Infof("%s polarStackDaemonLabels = %s ", logInfoTarget, polarStackDaemonLabels)
klog.Infof("%s coreVersionConfigMapLabel = %s ", logInfoTarget, coreVersionConfigMapLabel)
go startCheckCoreVersion(client)
request := <-CheckRequestQueue
// 请求仅为检测当前节点,再广播通知其它 polarstack-daemon 节点
if request == SingleCheckCoreVersionOperatorType {
continue
}
startNotifyOtherNode(client)
klog.Infof("%s StartCheckCoreVersion current host name:%s requestType:%s", logInfoTarget, hostName, request)
}
}
// startNotifyOtherNode
/**
* @Title: startNotifyOtherNode
* @Description: 开始通知其它节占主机
**/
func startNotifyOtherNode(client *clientset.Clientset) {
defer func() {
if err := recover(); err != nil {
klog.Errorf("%s failed to startNotifyOtherNode err:%v", logInfoTarget, err)
}
}()
var httpClient = &util.HttpClient{Timeout: 3 * time.Second}
// 获取 polarstack-daemon 节点的 ip
ips := getPolarStackDaemonNodeIps(client)
if nil == ips {
klog.Infof("%s StartCheckCoreVersion failed get daemon ips = nil", logInfoTarget)
return
}
for _, ip := range ips {
klog.Infof("%s hostName:[%s] get daemon ips", logInfoTarget, hostName)
header := make(map[string]string)
type source struct {
HostName string
}
url := "/innerCheckCoreVersion"
httpClient.Host = fmt.Sprintf("https://%s:%d", ip, config.Conf.Port)
resp, err := httpClient.HttpsPost(url, header, &source{
HostName: hostName,
})
if err != nil {
klog.Errorf("%s failed to post ip:%s, url:%s, err:%s", logInfoTarget, ip, url, err.Error())
continue
}
klog.Infof("%s success! ip:%s url:%s, httpStatusCode:[%d]", logInfoTarget, ip, url, resp.StatusCode)
}
}
// startCheckCoreVersion
/**
* @Title: startCheckCoreVersion
* @Description: 开始检查内核版本(具体实现)
**/
func startCheckCoreVersion(client *clientset.Clientset) {
defer func() {
if err := recover(); err != nil {
klog.Errorf("%s startCheckCoreVersion failed: err:%s", logInfoTarget, err)
}
}()
// 获取所有 core version 的 configMap
coreVersions, err := getAllCoreVersionConfigMapByLabels(client, coreVersionConfigMapLabel)
if err != nil {
klog.Errorf("%s getAllCoreVersionConfigMapByLabels failed. err:%v", logInfoTarget, err)
return
}
klog.Infof("%s success get [%d] core version config, ready to check now.", logInfoTarget, len(coreVersions.Items))
existingVersions := getExistingVersions(coreVersions)
klog.Infof("%s check done. now will update the host core version configMap. %s", logInfoTarget, existingVersions)
versionConfigMap, err := getHostCoreVersionConfigMap(client)
if err != nil {
klog.Errorf("%s failed to get core version configMap. err:%s", logInfoTarget, err.Error())
return
}
// 将末尾,号去除
if len(existingVersions) > 0 {
existingVersions = strings.TrimRight(existingVersions, ",")
} else {
klog.Warningf("%s existingVersions is empty.", logInfoTarget)
}
versionConfigMap.Data["existingVersions"] = existingVersions
versionConfigMap.Data["checkTime"] = time.Now().Format(timeFormat)
_, err = updateHostCoreVersionConfigMap(client, versionConfigMap)
if err != nil {
klog.Errorf("%s failed to update host core version configMap. err:%s", logInfoTarget, err.Error())
return
}
klog.Infof("%s Success! already update [%s].Data to versions:%s", logInfoTarget, versionConfigMap.Name, existingVersions)
}
// getExistingVersions
/**
* @Title: getExistingVersions
* @Description: 获取本主机上存在的 core version
**/
func getExistingVersions(coreVersions *v1.ConfigMapList) (existingVersions string) {
util.ClearImagesCache()
for _, coreVersion := range coreVersions.Items {
images, err := getAllImagesByVersionConfigMap(&coreVersion)
if err != nil {
klog.Errorf("%s failed to getAllImagesByVersionConfigMap err:%s", logInfoTarget, err.Error())
continue
}
if len(images) == 0 {
klog.Errorf("%s coreVersion.Name:%s configMap.Data images is empty, maybe not a core version configMap.", logInfoTarget, coreVersion.Name)
continue
}
coreVersionIsExists := true
for _, image := range images {
if !util.ImageIsExists(image, logInfoTarget) {
klog.Infof("%s image[%s] does not exist on current host, configMap:%s", logInfoTarget, image, coreVersion.Name)
coreVersionIsExists = false
break
}
}
// 所有镜像存在时,汇总后更新到主机的 configMap 中
if coreVersionIsExists {
// get core version
versionName, _ := getCoreVersionNameByVersionConfigMap(&coreVersion)
if len(versionName) == 0 {
klog.Errorf("%s why this version name is empty? configMap.Name is: %s", logInfoTarget, coreVersion.Name)
continue
}
existingVersions += versionName + ","
klog.Infof("%s The version name %s exists on current host", logInfoTarget, versionName)
} else {
klog.Infof("%s this version does not exist on current host, configMap.Name:%s", logInfoTarget, coreVersion.Name)
}
}
util.ClearImagesCache()
return
}
// GetDaemonNodeIps
/**
* @Title: GetDaemonNodeIps
* @Description: 获取 polarstack-daemon 布属的节点 ip 列表
**/
func getPolarStackDaemonNodeIps(client *clientset.Clientset) (ips []string) {
polarStacks, err := client.CoreV1().Pods(NameSpace).List(metav1.ListOptions{LabelSelector: polarStackDaemonLabels})
if nil != err {
klog.Errorf("%s getPolarStackDaemonNodeIps failed err: %s", logInfoTarget, err)
return
}
for _, daemon := range polarStacks.Items {
if strings.ToLower(hostName) != strings.ToLower(daemon.Spec.NodeName) {
ips = append(ips, daemon.Status.PodIP)
} else {
klog.Infof("current host:[%s] not need to notify", daemon.Spec.NodeName)
}
}
return
}
|
/*
* Copyright (c) 2016 Alex Yatskov <alex@foosoft.net>
* Author: Alex Yatskov <alex@foosoft.net>
*
* 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 frontmatter
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"io"
"strings"
"github.com/naoina/toml"
"gopkg.in/yaml.v2"
)
func Parse(input io.Reader) (map[string]interface{}, *bytes.Buffer, error) {
const (
yamlOpener = "---"
yamlCloser = "---"
tomlOpener = "+++"
tomlCloser = "+++"
jsonOpener = "{"
jsonCloser = "}"
)
var (
body, front bytes.Buffer
closer string
)
meta := make(map[string]interface{})
scanner := bufio.NewScanner(input)
header := false
first := true
for scanner.Scan() {
line := scanner.Text()
if first {
first = false
if len(closer) == 0 {
switch strings.TrimSpace(line) {
case tomlOpener:
header = true
closer = tomlCloser
case yamlOpener:
header = true
closer = yamlCloser
case jsonOpener:
header = true
closer = jsonCloser
front.WriteString(jsonOpener)
}
}
if header {
continue
}
}
if header {
switch strings.TrimSpace(line) {
case closer:
header = false
if closer == jsonCloser {
front.WriteString(jsonCloser)
}
default:
front.Write([]byte(line + "\n"))
}
} else {
body.Write([]byte(line + "\n"))
}
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
if header {
return nil, nil, errors.New("unterminated front matter block")
}
switch closer {
case tomlCloser:
if err := toml.Unmarshal(front.Bytes(), meta); err != nil {
return nil, nil, err
}
case yamlCloser:
if err := yaml.Unmarshal(front.Bytes(), meta); err != nil {
return nil, nil, err
}
case jsonCloser:
if err := json.Unmarshal(front.Bytes(), meta); err != nil {
return nil, nil, err
}
}
return meta, &body, nil
}
|
package goutils
import (
"fmt"
"github.com/dgrijalva/jwt-go"
)
func CreateToken(secret string, data string) (string, error) {
//time.Now().Add(time.Minute * 15)
var err error
//Creating Access Token
atClaims := jwt.MapClaims{}
atClaims["data"] = data
//atClaims["user_id"] = userid
//atClaims["exp"] = expiresin.Unix()
at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
token, err := at.SignedString([]byte(secret))
if err != nil {
return "", err
}
return token, nil
}
func ParseToken(secret string, token string) (string, error) {
//map[string]interface{}
atClaims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(token, &atClaims, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
fmt.Printf("%#v\n", err)
return "", err
}
return atClaims["data"].(string), nil
}
|
package playdata
import (
"database/sql"
"sync"
"time"
)
// GCP Functions may keep global variables across frequent access
type GlobalCache struct {
mutex *sync.Mutex
playsCache *PayloadPlays
playsCacheTime time.Time
// Attempt to reuse database connection
dbPool *sql.DB
}
func withLock(g *GlobalCache, logic func()) {
g.mutex.Lock()
logic()
g.mutex.Unlock()
}
func GlobalCache_GetDb(g *GlobalCache) *sql.DB {
var dbCache *sql.DB
withLock(g, func() {
if g.dbPool != nil {
dbCache = g.dbPool
}
})
return dbCache
}
// Possible we should execute the DB open under lock to avoid leak
func GlobalCache_SetDb(g *GlobalCache, db *sql.DB) {
withLock(g, func() {
g.dbPool = db
})
}
func GlobalCacheAvailable(g *GlobalCache) *PayloadPlays {
var playsCache *PayloadPlays
withLock(g, func() {
if g.playsCache != nil && g.playsCacheTime.After(time.Now()) {
playsCache = g.playsCache
}
})
return playsCache
}
func GlobalCacheSet(g *GlobalCache, playsCache *PayloadPlays) {
withLock(g, func() {
g.playsCache = playsCache
g.playsCacheTime = time.Now().Add(1 * time.Hour) // Could make this env
})
}
var Cache *GlobalCache
|
package main
import (
"fmt"
"io/ioutil"
"time"
"github.com/bitly/go-simplejson"
"github.com/xuri/excelize"
)
func main() {
row := 1
dat, _ := ioutil.ReadFile("/Users/zhuxu/Documents/weekreport/test.json")
// fmt.Println(string(dat))
json, err := simplejson.NewJson(dat)
if err != nil {
fmt.Println("error")
}
t := time.Now()
const day_secs = 24 * 3600
weekday_today := int64(t.Weekday())
if (weekday_today > 5) {
weekday_today = 5
}
weekday1 := time.Unix(t.Unix() - day_secs * (weekday_today - 1), 0)
weekday5 := time.Unix(t.Unix() + day_secs * (5 - weekday_today), 0)
day1 := weekday1.Format("01.02")
day5 := weekday5.Format("01.02")
fmt.Println(day1)
fmt.Println(day5)
xlsx := excelize.NewFile()
style, err := xlsx.NewStyle(`{"alignment":{"horizontal":"top","ident":1,"justify_last_line":true,"reading_order":0,"relative_indent":1,"vertical":"top","wrap_text":false},"border":[{"type":"left","color":"DDDDDD","style":1}, {"type":"right","color":"DDDDDD","style":1}, {"type":"top","color":"DDDDDD","style":1}, {"type":"bottom","color":"DDDDDD","style":1}]}`)
if err != nil {
fmt.Println(err)
}
xlsx.SetCellStyle("Sheet1", "A1", "H50", style)
style_boldfill, _ := xlsx.NewStyle(`{"font":{"bold":true,"italic":false},"fill":{"type":"pattern","color":["#F0F0F0"], "pattern":1},"border":[{"type":"left","color":"DDDDDD","style":1}, {"type":"right","color":"DDDDDD","style":1}, {"type":"top","color":"DDDDDD","style":1}, {"type":"bottom","color":"DDDDDD","style":1}]}`)
style_bold, _ := xlsx.NewStyle(`{"font":{"bold":true,"italic":false},"alignment":{"horizontal":"top","ident":1,"justify_last_line":true,"reading_order":0,"relative_indent":1,"vertical":"top","wrap_text":false},"border":[{"type":"left","color":"DDDDDD","style":1}, {"type":"right","color":"DDDDDD","style":1}, {"type":"top","color":"DDDDDD","style":1}, {"type":"bottom","color":"DDDDDD","style":1}]}`)
style_border, _ := xlsx.NewStyle(`{"font":{"bold":false,"italic":false},"alignment":{"horizontal":"top","ident":1,"justify_last_line":true,"reading_order":0,"relative_indent":1,"vertical":"top","wrap_text":false},"border":[{"type":"left","color":"DDDDDD","style":1}, {"type":"right","color":"DDDDDD","style":1}, {"type":"top","color":"DDDDDD","style":1}, {"type":"bottom","color":"DDDDDD","style":1}]}`)
// Create a new sheet.
xlsx.NewSheet(1, "Sheet1")
xlsx.SetCellValue("Sheet1", fmt.Sprintf("A%d", row), fmt.Sprintf("个人周报[%s-%s]", day1, day5))
xlsx.MergeCell("sheet1", fmt.Sprintf("A%d", row), fmt.Sprintf("H%d", row))
xlsx.SetCellStyle("Sheet1", "A1", "A1", style_boldfill)
row ++
content := "本周总结:\n"
this_week, _ := json.Get("this_week").Array()
for i := 0; i < len(this_week); i++ {
content += fmt.Sprintf("%d、%s\n", i + 1, this_week[i].(string))
}
content += "\n下周计划:\n"
next_week, _ := json.Get("next_week").Array()
for i := 0; i < len(next_week); i ++ {
// fmt.Println(next_week[i])
content += fmt.Sprintf("%d、%s\n", i + 1, next_week[i].(string))
}
fmt.Println(content)
xlsx.SetCellStyle("Sheet1", "A2", "A2", style_border)
xlsx.SetCellValue("Sheet1", fmt.Sprintf("A%d", row), content)
xlsx.MergeCell("sheet1", fmt.Sprintf("A%d", row), fmt.Sprintf("H%d", row))
row ++
xlsx.SetCellValue("Sheet1", fmt.Sprintf("A%d", row), "项目")
xlsx.SetCellValue("Sheet1", fmt.Sprintf("B%d", row), "项目内容")
xlsx.SetCellValue("Sheet1", fmt.Sprintf("C%d", row), "人员")
xlsx.SetCellValue("Sheet1", fmt.Sprintf("D%d", row), "分解")
xlsx.SetCellValue("Sheet1", fmt.Sprintf("E%d", row), "计划时间")
xlsx.SetCellValue("Sheet1", fmt.Sprintf("F%d", row), "")
xlsx.SetCellValue("Sheet1", fmt.Sprintf("G%d", row), "状态")
xlsx.SetCellValue("Sheet1", fmt.Sprintf("H%d", row), "备注")
xlsx.MergeCell("sheet1", fmt.Sprintf("E%d", row), fmt.Sprintf("F%d", row))
xlsx.SetCellStyle("Sheet1", fmt.Sprintf("A%d", row), fmt.Sprintf("H%d", row), style_bold)
row ++
projects, _ := json.Get("projects").Array()
for i := 0; i < len(projects); i ++ {
project, _ := projects[i].(map[string]interface{})
xlsx.SetCellValue("Sheet1", fmt.Sprintf("A%d", row), project["title"])
fmt.Println(project["content"])
xlsx.SetCellValue("Sheet1", fmt.Sprintf("B%d", row), fmt.Sprintf("%s", project["content"]))
xlsx.SetCellValue("Sheet1", fmt.Sprintf("C%d", row), project["staffs"])
xlsx.SetCellStyle("Sheet1", fmt.Sprintf("A%d", row), fmt.Sprintf("A%d", row), style_bold)
details, _ := project["details"].([]interface{})
for j := 0; j < len(details); j ++ {
detail, _ := details[j].(map[string]interface{})
xlsx.SetCellValue("Sheet1", fmt.Sprintf("D%d", row + j), detail["title"])
xlsx.SetCellValue("Sheet1", fmt.Sprintf("E%d", row + j), detail["start_time"])
xlsx.SetCellValue("Sheet1", fmt.Sprintf("F%d", row + j), detail["end_time"])
xlsx.SetCellValue("Sheet1", fmt.Sprintf("G%d", row + j), detail["status"])
xlsx.SetCellValue("Sheet1", fmt.Sprintf("H%d", row + j), detail["comment"])
xlsx.SetCellStyle("Sheet1", fmt.Sprintf("B%d", row + j), fmt.Sprintf("H%d", row + j), style)
}
xlsx.MergeCell("sheet1", fmt.Sprintf("A%d", row), fmt.Sprintf("A%d", row + len(details) - 1))
xlsx.MergeCell("sheet1", fmt.Sprintf("B%d", row), fmt.Sprintf("B%d", row + len(details) - 1))
xlsx.MergeCell("sheet1", fmt.Sprintf("C%d", row), fmt.Sprintf("C%d", row + len(details) - 1))
// xlsx.SetColWidth("Sheet1", "A", "C", 80)
row = row + len(details)
}
// Set active sheet of the workbook.
xlsx.SetActiveSheet(1)
// Save xlsx file by the given path.
res := xlsx.SaveAs("./Workbook.xlsx")
if res != nil {
fmt.Println(res)
}
}
|
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func multiples(x, n int) (r int) {
var c uint
r = n
for (r << 1) <= x {
r <<= 1
c++
}
for c > 0 {
c--
for r+(n<<c) <= x {
r += n << c
}
}
for r < x {
r += n
}
return r
}
func main() {
var x, n int
data, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer data.Close()
scanner := bufio.NewScanner(data)
for scanner.Scan() {
fmt.Sscanf(scanner.Text(), "%d,%d", &x, &n)
fmt.Println(multiples(x, n))
}
}
|
package utils
import (
"path/filepath"
"os"
"fmt"
"io"
"io/ioutil"
)
// checkDirPath 会检查目录路径。
func CheckDirPath(dirPath string) (absDirPath string, err error) {
if dirPath == "" {
err = fmt.Errorf("invalid dir path: %s", dirPath)
return
}
if filepath.IsAbs(dirPath) {
absDirPath = dirPath
} else {
absDirPath, err = filepath.Abs(dirPath)
if err != nil {
return
}
}
var dir *os.File
dir, err = os.Open(absDirPath)
if err != nil && !os.IsNotExist(err) {
return
}
if dir == nil {
err = os.MkdirAll(absDirPath, 0700)
if err != nil && !os.IsExist(err) {
return
}
} else {
var fileInfo os.FileInfo
fileInfo, err = dir.Stat()
if err != nil {
return
}
if !fileInfo.IsDir() {
err = fmt.Errorf("not directory: %s", absDirPath)
return
}
}
return
}
func SaveFile(dirPath, fileName string, b []byte) (err error) {
// 检查和准备数据。
var absDirPath string
if absDirPath, err = CheckDirPath(dirPath); err != nil {
return err
}
// 创建图片文件。
filePath := filepath.Join(absDirPath, fileName)
file, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("couldn't create file: %s (path: %s)", err, filePath)
}
defer file.Close()
_, err = file.Write(b)
return err
}
func AppendFile(dirPath, fileName string, b []byte) (err error) {
// 检查和准备数据。
var absDirPath string
if absDirPath, err = CheckDirPath(dirPath); err != nil {
return err
}
// 创建图片文件。
filePath := filepath.Join(absDirPath, fileName)
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0700)
if err != nil {
return fmt.Errorf("couldn't open file: %s (path: %s)", err, filePath)
}
defer file.Close()
_, err = file.Write(b)
return err
}
func SaveFileByReader(dirPath, fileName string, reader io.Reader) (err error) {
b, err := ioutil.ReadAll(reader)
if err != nil {
return
}
return SaveFile(dirPath, fileName, b)
}
func AppendFileByReader(dirPath, fileName string, reader io.Reader) (err error) {
b, err := ioutil.ReadAll(reader)
if err != nil {
return
}
return AppendFile(dirPath, fileName, b)
}
|
package email
import (
"fmt"
"net/smtp"
)
type User struct {
Username string
Password string
Server string
Port int
}
func (u *User) SendMail(from string, content []byte, to ...string) error {
auth := smtp.PlainAuth("", u.Username, u.Password, u.Server)
return smtp.SendMail(fmt.Sprintf("%s:%d", u.Server, u.Port),
auth, from, to, content)
}
|
package xredis
import (
"testing"
"time"
"fmt"
"os"
"io/ioutil"
"encoding/json"
"log"
)
func init() {
//f, _ := os.OpenFile("sample.json",os.O_RDONLY, 0777)
f, _ := os.OpenFile("sample.json",os.O_RDONLY, 0777)
defer f.Close()
configStr, _ := ioutil.ReadAll(f)
var configs map[string]RedisConfig
err := json.Unmarshal([]byte(configStr), &configs)
if err!= nil {
log.Println("decode config error :",err)
}
if false {
v, _ := json.MarshalIndent(configs, "", "\t")
log.Println(string(v))
}
err = InitWithConfig(configs)
if err != nil {
panic(err)
}
RegisterCallBack(func (c *RedisConn, timeused time.Duration, err error, cmd string, args...interface{}){
fmt.Printf("callback conf:%v info:%v cmd:%v args:%v\n", c.Conf, c.Conf.GetInfo(), cmd, args)
})
}
func TestStr(t *testing.T){
Set("topic", "abc", "key1", "value1")
Set("topic", "abc", "key2", "value2")
v, _ := Get("topic", "abc", "key1")
if v!="value1" {
t.Error("str set err")
}
values, _ := MGet("topic", "abc", []string{"key1", "key2"})
fmt.Println("MGet values:", values)
Del("topic", "abc", "key1")
vdel, _ := Get("topic", "abc", "key1")
if vdel!="" {
t.Error("str del err")
}
//incr incrby decr decrby ttl
db := "topic"
Set(db, nil , "key2", "5")
v0, err := Incr(db, nil, "key2")
fmt.Println("v", v, err)
if v0 != 6 {
t.Error("Incr err")
}
v2, err := Decr(db, nil, "key2")
if v2 != 5 {
t.Error("Incr err")
}
v3, _ := IncrBy(db, nil, "key2", 5)
if v3 != 10{
t.Error("IncrBy err", v3)
}
v4, _ := DecrBy(db, nil, "key2", 5)
if v4 != 5 {
t.Error("DecrBy err", v4)
}
}
func TestZset(t *testing.T) {
fmt.Println("run test~~~")
db := "topic"
Del(db, nil, "zset")
ZAdd(db, nil, "zset", 100, "abc", 200, "bac")
cnt, _ := ZCard(db, nil, "zset")
if cnt != 2 {
t.Error("zadd or zcard err")
}
ret, _ := ZRevRangeByScore(db, nil, "zset", "+inf", "-inf", true)
fmt.Println(ret)
ret2, _ := ZRange(db, nil, "zset", 0, -1)
fmt.Println("zrange", ret2)
ret3, _ := ZRevRange(db, nil, "zset", 0, -1)
fmt.Println("zrevrange", ret3)
retset1, _ := ZRangeWithScore(db, nil, "zset", 0, -1)
fmt.Println("ZRangeWithScore", retset1)
retset2, _ := ZRevRangeWithScore(db, nil, "zset", 0, -1)
fmt.Println("ZRevRangeWithScore", retset2)
ZRem(db, nil, "zset", "abc")
cnt, _ = ZCard(db, nil, "zset")
if cnt != 1 {
t.Error("zrem err")
}
ret4, _ := ZIncrBy(db, nil, "zset", 10.5, "incrv")
if ret4 != 10.5 {
t.Error("ZIncrBy err")
}
}
func TestList(t *testing.T) {
fmt.Println("run test~~~")
db := "topic"
Del(db, nil, "list")
LPush(db, nil, "list", "b")
LPush(db, nil, "list", "a")
ret, _ := LRange(db, nil, "list", 0, 2)
fmt.Println(ret)
if len(ret) != 2 {
t.Error("list rpush err or range err")
}
l, _:= LLen(db,nil,"list")
if l != 2 {
t.Error("LLen err")
}
v2, _ := LIndex(db,nil, "list", 0)
fmt.Println("v2", v2)
if v2 !="a" {
t.Error("LIndex err")
}
v1, _ := LPop(db,nil, "list")
fmt.Println("v1", v1)
if v1 !="a" {
t.Error("LPop err")
}
LPush(db, nil, "list", "a")
RPush(db, nil, "list", "c")
v, _ := RPop(db,nil, "list")
fmt.Println("v", v)
if v !="c" {
t.Error("rpush or rpop err")
}
}
func TestSet(t *testing.T) {
fmt.Println("run set test~~~")
db := "topic"
Del(db, nil, "set")
v, err := SAdd(db, nil, "set", "a")
fmt.Println("sadd 1", v, err)
v, err = SAdd(db, nil, "set", "a")
fmt.Println("sadd 2", v, err)
isMem, _ := SIsMember(db, nil, "set", "a")
if !isMem {
t.Error("SAdd err")
}
cnt, _ := SCard(db, nil, "set")
if cnt != 1 {
t.Error("SCard err")
}
SRem(db, nil, "set", "a")
isMem, _ = SIsMember(db, nil, "set", "a")
if isMem {
t.Error("Srem err")
}
v2,_ := SPop(db, nil, "set")
fmt.Println("spop", v2)
SAdd(db, nil, "set", "a", "b", "c")
idx, list, err := SScan(db, nil, "set", 0, 1)
fmt.Println("sscan", idx, list, err)
}
func TestHash(t *testing.T) {
fmt.Println("run test~~~")
db := "topic"
Del(db, nil, "hash")
HSet(db, nil, "hash", "key1", "v1")
v, err := HGet(db, nil, "hash", "key1")
fmt.Println("v", v, err)
if v != "v1"{
t.Error("HGet err")
}
all, _ := HGetAll(db, nil, "hash")
fmt.Println("all", all)
keys, _ := HKeys(db, nil, "hash")
fmt.Println("keys", keys)
vals, _ := HVals(db, nil, "hash")
fmt.Println("vals", vals)
HSet(db, nil, "hash", "key2", "1")
l, _ := HLen(db, nil, "hash")
if l != 2 {
t.Error("HLen err")
}
HIncrBy(db, nil, "hash", "key2", 1)
v2, _ := HGet(db, nil, "hash", "key2")
if v2 != "2"{
t.Error("HIncrBy err")
}
HDel(db, nil, "hash", "key1")
l, err = HLen(db, nil, "hash")
if l != 1 {
t.Error("HDel err")
}
HMSet(db, nil, "hash", map[string]string{"key1":"v1", "key2":"v22"})
values, err := HMGet(db, nil, "hash", "key1", "key2","key3")
fmt.Println("test HMGet", values, err)
} |
package testbed
import (
"fmt"
"os"
"os/exec"
"path/filepath"
)
//findContrib tries to find gin-repo/contrib, needs to be
//called with a current work directory below gin-repo/
func findContrib() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", nil
}
for {
cd := filepath.Join(dir, "contrib")
fmt.Fprintf(os.Stderr, "checking %q\n", cd)
_, err := os.Stat(cd)
if err == nil {
return cd, nil
} else if dir == "." || dir == "/" {
return "", fmt.Errorf("Could not find %q in hierarchy", "contrib")
}
dir = filepath.Dir(dir)
}
}
//MkData creates test data the temporary directory
//under tmpdir. Returns the path to that newly
//create temporary directory
func MkData(tmpdir string) (string, error) {
datadir := filepath.Join(tmpdir, "grd-data")
err := os.MkdirAll(datadir, 0755)
if err != nil {
return "", fmt.Errorf("could not create tmp dir: %v\n", err)
}
fmt.Fprintf(os.Stderr, "[D] using : %q\n", datadir)
contrib, err := findContrib()
if err != nil {
return "", fmt.Errorf("could not find contrib dir!\n")
}
mkdata := filepath.Join(contrib, "mkdata.py")
datafile := filepath.Join(contrib, "data.yml")
cmd := exec.Command(mkdata, datafile)
cmd.Dir = datadir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return "", fmt.Errorf("could not run mkdata: %v\n", err)
}
return datadir, nil
}
|
package raft
//
// RequestVote RPC arguments structure.
// field names must start with capital letters!
//
type RequestVoteArgs struct {
// Your data here (2A, 2B).
Term int
CandidateID int
LastLogIndex int
LastLogTerm int
}
//
// RequestVote RPC reply structure.
// field names must start with capital letters!
//
type RequestVoteReply struct {
// Your data here (2A).
Term int
VoteGranted bool
}
//
// RequestVote RPC handler.
//
func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {
// Your code here (2A, 2B).
rf.mu.Lock()
DPrintfElection("id: %d received requestVote from: %d, rpc term: %d, cur Term: %d", rf.id, args.CandidateID, args.Term, rf.CurrentTerm)
sendStale := false
reply.Term = rf.CurrentTerm
if args.Term < rf.CurrentTerm {
reply.VoteGranted = false
rf.mu.Unlock()
return
} else if args.Term > rf.CurrentTerm {
DPrintfElection("id: %d, term smaller than rpc request", rf.id)
rf.VotedFor = NULL
if rf.state != FOLLOWER {
sendStale = true
}
rf.convertToFollower(args.Term)
}
if (rf.VotedFor == NULL || rf.VotedFor == args.CandidateID) && logUpToDate(args, rf) {
rf.VotedFor = args.CandidateID
reply.VoteGranted = true
} else {
reply.VoteGranted = false
}
rf.mu.Unlock()
if sendStale {
rf.stale()
}
return
}
// logUpToDate returns true if the candidate has up-to-date log
func logUpToDate(args *RequestVoteArgs, rf *Raft) bool {
if args.LastLogTerm != rf.getLastLogTerm() {
return args.LastLogTerm > rf.getLastLogTerm()
} else {
return args.LastLogIndex >= rf.getLastLogIndex()
}
}
//
// example code to send a RequestVote RPC to a server.
// server is the index of the target server in rf.peers[].
// expects RPC arguments in args.
// fills in *reply with RPC reply, so caller should
// pass &reply.
// the types of the args and reply passed to Call() must be
// the same as the types of the arguments declared in the
// handler function (including whether they are pointers).
//
// The labrpc package simulates a lossy network, in which servers
// may be unreachable, and in which requests and replies may be lost.
// Call() sends a request and waits for a reply. If a reply arrives
// within a timeout interval, Call() returns true; otherwise
// Call() returns false. Thus Call() may not return for a while.
// A false return can be caused by a dead server, a live server that
// can't be reached, a lost request, or a lost reply.
//
// Call() is guaranteed to return (perhaps after a delay) *except* if the
// handler function on the server side does not return. Thus there
// is no need to implement your own timeouts around Call().
//
// look at the comments in ../labrpc/labrpc.go for more details.
//
// if you're having trouble getting RPC to work, check that you've
// capitalized all field names in structs passed over RPC, and
// that the caller passes the address of the reply struct with &, not
// the struct itself.
//
func (rf *Raft) callRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {
ok := rf.peers[server].Call("Raft.RequestVote", args, reply)
return ok
}
// AppendEntries handlers
//AppendEntriesArgs is arguement for AppendEntries
type AppendEntriesArgs struct {
Term int
LeaderID int
PrevLogIndex int
PrevLogTerm int
Entries []RaftLog
LeaderCommit int
}
//AppendEntriesReply is reply for AppendEntries
type AppendEntriesReply struct {
// Your data here (2A).
Term int
Succcess bool
ConflictTerm int
ConflictIdx int
}
// AppendEntries is an RPC call
func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) {
rf.mu.Lock()
DPrintf("%d recieved appendentry from: %d, RPC term: %d, current term: %d", rf.id, args.LeaderID, args.Term, rf.CurrentTerm)
reply.ConflictIdx = NULL
reply.ConflictTerm = NULL
reply.Term = rf.CurrentTerm
if args.Term < rf.CurrentTerm {
DPrintf("%d recieved appendentry from: %d, but RPC term: %d is smaller than current term: %d, ignore!", rf.id, args.LeaderID, args.Term, rf.CurrentTerm)
reply.Succcess = false
rf.mu.Unlock()
return
}
if rf.state == LEADER && args.Term == rf.CurrentTerm { // 2 leaders
DPrintf("Houston, we fucked up!")
}
if args.Term > rf.CurrentTerm {
rf.VotedFor = args.LeaderID
}
curState := rf.state
rf.convertToFollower(args.Term)
if rf.getLastLogIndex() < args.PrevLogIndex { // Log inconsistant
DPrintfAgreement("Log inconsistant")
reply.Succcess = false
reply.ConflictIdx = rf.getLastLogIndex()
reply.ConflictTerm = rf.getLog(rf.getLastLogIndex()).Term
} else if rf.getLog(args.PrevLogIndex).Term != args.PrevLogTerm {
DPrintfAgreement("Log inconsistant")
reply.Succcess = false
idx := args.PrevLogIndex
for !rf.isLogBegining(idx) && rf.getLog(idx).Term > args.PrevLogTerm {
// find first term smaller or equal to args.PrevLogTerm
idx--
}
reply.ConflictTerm = rf.getLog(idx).Term
for !rf.isLogBegining(idx) && rf.getLog(idx).Term == reply.ConflictTerm {
// find first index of this term
idx--
}
if rf.isLogBegining(idx) {
reply.ConflictIdx = idx
} else {
reply.ConflictIdx = idx + 1
}
} else {
idx := args.PrevLogIndex
for i := 0; i < len(args.Entries); i++ {
idx++
if idx < rf.logLen() {
if rf.getLog(idx).Term == args.Entries[i].Term {
continue
} else {
// confict, then delete everything after idx
rf.Log = rf.Log[:idx]
}
}
// append
rf.appendLog(args.Entries[i:]...)
DPrintfAgreement("id %d, term : %d, commitIndex: %d, log appended", rf.id, rf.CurrentTerm, rf.commitIndex)
break
}
if args.LeaderCommit > rf.commitIndex {
rf.commitIndex = Min(args.LeaderCommit, rf.getLastLogIndex())
DPrintfAgreement("id %d, term : %d, commitIndex updated: %d", rf.id, rf.CurrentTerm, rf.commitIndex)
rf.applyLogs(rf.commitIndex)
}
reply.Succcess = true
}
rf.mu.Unlock()
if curState == FOLLOWER {
DPrintfElection("%d recieved appendentry from: %d, current state: %d, rpc term: %d, current term: %d, signal heartbeat", rf.id, args.LeaderID, rf.state, args.Term, rf.CurrentTerm)
send(rf.heartBeatSignal) // signal follower to reset timer
} else {
// stale leader and candidate
DPrintfElection("%d recieved appendentry from: %d, current state: %d, rpc term: %d, current term: %d, convert to follower", rf.id, args.LeaderID, rf.state, args.Term, rf.CurrentTerm)
rf.stale() // change to follower and signal control to ignore timeout
}
return
}
func (rf *Raft) callAppendEntries(server int, args *AppendEntriesArgs, reply *AppendEntriesReply) bool {
ok := rf.peers[server].Call("Raft.AppendEntries", args, reply)
return ok
}
|
package conf
import "strconv"
type Redis struct {
Addr string `json:"addr"`
Auth string `json:"auth"`
DB int `json:"db"`
}
func (rc *Redis) String() string {
return rc.Addr + "@" + rc.Auth + "/" + strconv.Itoa(rc.DB)
}
|
package wb_util
func FindIntPos(s int, array []int) int {
for p, v := range array {
if v == s {
return p
}
}
return -1
}
func FindStrPos(s string, array []string) int {
for p, v := range array {
if v == s {
return p
}
}
return -1
}
|
package v7
import (
"code.cloudfoundry.org/cli/actor/actionerror"
"code.cloudfoundry.org/cli/actor/sharedaction"
"code.cloudfoundry.org/cli/actor/v7action"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/flag"
"code.cloudfoundry.org/cli/command/v7/shared"
"code.cloudfoundry.org/clock"
)
//go:generate counterfeiter . UpdateServiceBrokerActor
type DeleteServiceBrokerActor interface {
GetServiceBrokerByName(serviceBrokerName string) (v7action.ServiceBroker, v7action.Warnings, error)
DeleteServiceBroker(serviceBrokerGUID string) (v7action.Warnings, error)
}
type DeleteServiceBrokerCommand struct {
RequiredArgs flag.ServiceBroker `positional-args:"yes"`
usage interface{} `usage:"CF_NAME delete-service-broker SERVICE_BROKER [-f]\n\n"`
Force bool `short:"f" description:"Force deletion without confirmation"`
relatedCommands interface{} `related_commands:"delete-service, purge-service-offering, service-brokers"`
UI command.UI
Config command.Config
Actor DeleteServiceBrokerActor
SharedActor command.SharedActor
}
func (cmd *DeleteServiceBrokerCommand) Setup(config command.Config, ui command.UI) error {
cmd.UI = ui
cmd.Config = config
sharedActor := sharedaction.NewActor(config)
cmd.SharedActor = sharedActor
ccClient, uaaClient, err := shared.GetNewClientsAndConnectToCF(config, ui, "")
if err != nil {
return err
}
cmd.Actor = v7action.NewActor(ccClient, config, sharedActor, uaaClient, clock.NewClock())
return nil
}
func (cmd DeleteServiceBrokerCommand) Execute(args []string) error {
err := cmd.SharedActor.CheckTarget(false, false)
if err != nil {
return err
}
serviceBrokerName := cmd.RequiredArgs.ServiceBroker
if !cmd.Force {
confirmed, promptErr := cmd.UI.DisplayBoolPrompt(false, "Really delete the service broker {{.ServiceBroker}}?", map[string]interface{}{
"ServiceBroker": serviceBrokerName,
})
if promptErr != nil {
return promptErr
}
if !confirmed {
cmd.UI.DisplayText("'{{.ServiceBroker}}' has not been deleted.", map[string]interface{}{
"ServiceBroker": serviceBrokerName,
})
return nil
}
}
cmd.UI.DisplayTextWithFlavor("Deleting service broker {{.ServiceBroker}}...",
map[string]interface{}{
"ServiceBroker": serviceBrokerName,
})
serviceBroker, warnings, err := cmd.Actor.GetServiceBrokerByName(serviceBrokerName)
cmd.UI.DisplayWarnings(warnings)
if err != nil {
if _, ok := err.(actionerror.ServiceBrokerNotFoundError); ok {
cmd.UI.DisplayText("Service broker '{{.ServiceBroker}}' does not exist.", map[string]interface{}{
"ServiceBroker": serviceBrokerName,
})
cmd.UI.DisplayOK()
return nil
}
return err
}
warnings, err = cmd.Actor.DeleteServiceBroker(serviceBroker.GUID)
cmd.UI.DisplayWarnings(warnings)
if err != nil {
return err
}
cmd.UI.DisplayOK()
return nil
}
|
package main
import (
"bytes"
"flag"
"io/ioutil"
"testing"
"github.com/stretchr/testify/assert"
)
type intsArg struct {
rootModel string
title string
output string
project string
filter string
modules string
exclude []string
clustered bool
epa bool
}
func comparePUML(t *testing.T, expected, actual map[string]string) {
for name, goldenFile := range expected {
golden, err := ioutil.ReadFile(goldenFile)
assert.Nil(t, err)
if string(golden) != actual[name] {
err := ioutil.WriteFile("tests/"+name+".puml", []byte(actual[name]), 0777)
assert.Nil(t, err)
}
assert.Equal(t, string(golden), actual[name])
}
assert.Equal(t, len(expected), len(actual))
}
func TestGenerateIntegrationsWithTestFile(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "indirect_1.sysl",
output: "%(epname).png",
project: "Project",
}
expected := map[string]string{
"all.png": "tests/indirect_1-all-golden.puml",
"indirect_arrow.png": "tests/indirect_1-indirect_arrow-golden.puml",
"my_callers.png": "tests/indirect_1-my_callers-golden.puml",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationsWithTestFileAndFilters(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_test.sysl",
output: "%(epname).png",
project: "Project",
filter: "test",
}
expected := map[string]string{}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
// Then
assert.Equal(t, expected, result)
}
func TestGenerateIntegrationsWithImmediatePredecessors(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_immediate_predecessors_test.sysl",
output: "%(epname).png",
project: "Project",
}
expected := map[string]string{
"immediate_predecessors.png": "tests/immediate_predecessors-golden.puml",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationsWithExclude(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_excludes_test.sysl",
output: "%(epname).png",
project: "Project",
}
expected := map[string]string{
"excludes.png": "tests/excludes-golden.puml",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationsWithPassthrough(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_passthrough_test.sysl",
output: "%(epname).png",
project: "Project",
}
expected := map[string]string{
"passthrough.png": "tests/passthrough-golden.puml",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
// Then
comparePUML(t, expected, result)
}
func TestDoGenerateIntegrations(t *testing.T) {
type args struct {
flags *flag.FlagSet
args []string
}
argsData := []string{"ints"}
test := struct {
name string
args args
wantStdout string
wantStderr string
}{
"Case-Do generate integrations",
args{
flag.NewFlagSet(argsData[0], flag.PanicOnError),
argsData,
},
"",
"",
}
t.Run(test.name, func(t *testing.T) {
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
DoGenerateIntegrations(test.args.args)
assert.Equal(t, test.wantStdout, stdout.String())
assert.Equal(t, test.wantStderr, stderr.String())
})
}
func TestGenerateIntegrationsWithCluster(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_with_cluster.sysl",
output: "%(epname).png",
project: "Project",
clustered: true,
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
expected := map[string]string{
"cluster.png": "tests/cluster-golden.puml",
}
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationsWithEpa(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_with_epa.sysl",
output: "%(epname).png",
project: "Project",
epa: true,
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
expected := map[string]string{
"epa.png": "tests/epa-golden.puml",
}
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationsWithIndirectArrow(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "indirect_2.sysl",
output: "%(epname).png",
project: "Project",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
expected := map[string]string{
"all_indirect_2.png": "tests/all_indirect_2-golden.puml",
"no_passthrough.png": "tests/no_passthrough-golden.puml",
"passthrough_b.png": "tests/passthrough_b-golden.puml",
"passthrough_c.png": "tests/passthrough_c-golden.puml",
"passthrough_d.png": "tests/passthrough_d-golden.puml",
"passthrough_c_e.png": "tests/passthrough_c_e-golden.puml",
}
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationsWithRestrictBy(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_with_restrict_by.sysl",
output: "%(epname).png",
project: "Project",
epa: true,
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
expected := map[string]string{
"with_restrict_by.png": "tests/with_restrict_by-golden.puml",
"without_restrict_by.png": "tests/without_restrict_by-golden.puml",
}
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationsWithFilter(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_with_filter.sysl",
output: "%(epname).png",
project: "Project",
filter: "matched",
}
expected := map[string]string{
"matched.png": "tests/matched-golden.puml",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationWithOrWithoutPassThrough(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_with_or_without_passthrough.sysl",
output: "%(epname).png",
project: "Project",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
expected := map[string]string{
"with_passthrough.png": "tests/with_passthrough-golden.puml",
"without_passthrough.png": "tests/without_passthrough-golden.puml",
"with_systema.png": "tests/with_systema-golden.puml",
}
// Then
comparePUML(t, expected, result)
}
func TestPassthrough2(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "passthrough_1.sysl",
output: "%(epname).png",
project: "Project",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
expected := map[string]string{
"pass_1_all.png": "tests/pass_1_all-golden.puml",
"pass_1_sys_a.png": "tests/pass_1_sys_a-golden.puml",
"pass_b.png": "tests/pass_b-golden.puml",
"pass_b_c.png": "tests/pass_b_c-golden.puml",
"pass_f.png": "tests/pass_f-golden.puml",
"pass_D.png": "tests/pass_D-golden.puml",
"pass_e.png": "tests/pass_e-golden.puml",
}
// Then
comparePUML(t, expected, result)
}
func TestGenerateIntegrationsWithPubSub(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "integration_with_pubsub.sysl",
output: "%(epname).png",
project: "Project",
epa: true,
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
expected := map[string]string{
"pubsub.png": "tests/pubsub-golden.puml",
}
// Then
comparePUML(t, expected, result)
}
func TestAllStmts(t *testing.T) {
// Given
args := &intsArg{
rootModel: "./tests/",
modules: "ints_stmts.sysl",
output: "%(epname).png",
project: "Project",
}
// When
result := GenerateIntegrations(args.rootModel, args.title, args.output,
args.project, args.filter, args.modules, args.exclude, args.clustered, args.epa)
expected := map[string]string{
"all_stmts.png": "tests/all_stmts-golden.puml",
}
// Then
comparePUML(t, expected, result)
}
|
package global
// 全局Flags
// 配置文件路径
var GFlagConf string
// 加密类型
var GFlagCrypto string
// 节点地址
var GFlagHost string
// 账户目录
var GFlagKeys string
// 链名
var GFlagBCName string
|
package handler
import (
req_model "github.com/caos/zitadel/internal/auth_request/model"
"github.com/caos/zitadel/internal/errors"
es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/eventstore/spooler"
"github.com/caos/zitadel/internal/user/repository/eventsourcing"
user_events "github.com/caos/zitadel/internal/user/repository/eventsourcing"
view_model "github.com/caos/zitadel/internal/user/repository/view/model"
)
type UserSession struct {
handler
userEvents *user_events.UserEventstore
}
const (
userSessionTable = "auth.user_sessions"
)
func (u *UserSession) ViewModel() string {
return userSessionTable
}
func (u *UserSession) EventQuery() (*models.SearchQuery, error) {
sequence, err := u.view.GetLatestUserSessionSequence()
if err != nil {
return nil, err
}
return eventsourcing.UserQuery(sequence.CurrentSequence), nil
}
func (u *UserSession) Reduce(event *models.Event) (err error) {
var session *view_model.UserSessionView
switch event.Type {
case es_model.UserPasswordCheckSucceeded,
es_model.UserPasswordCheckFailed,
es_model.MfaOtpCheckSucceeded,
es_model.MfaOtpCheckFailed,
es_model.SignedOut:
eventData, err := view_model.UserSessionFromEvent(event)
if err != nil {
return err
}
session, err = u.view.UserSessionByIDs(eventData.UserAgentID, event.AggregateID)
if err != nil {
if !errors.IsNotFound(err) {
return err
}
session = &view_model.UserSessionView{
CreationDate: event.CreationDate,
ResourceOwner: event.ResourceOwner,
UserAgentID: eventData.UserAgentID,
UserID: event.AggregateID,
State: int32(req_model.UserSessionStateActive),
}
}
return u.updateSession(session, event)
case es_model.UserPasswordChanged,
es_model.MfaOtpRemoved,
es_model.UserProfileChanged,
es_model.UserLocked,
es_model.UserDeactivated:
sessions, err := u.view.UserSessionsByUserID(event.AggregateID)
if err != nil {
return err
}
for _, session := range sessions {
if err := u.updateSession(session, event); err != nil {
return err
}
}
return nil
case es_model.UserRemoved:
return u.view.DeleteUserSessions(event.AggregateID, event.Sequence)
default:
return u.view.ProcessedUserSessionSequence(event.Sequence)
}
}
func (u *UserSession) OnError(event *models.Event, err error) error {
logging.LogWithFields("SPOOL-sdfw3s", "id", event.AggregateID).WithError(err).Warn("something went wrong in user session handler")
return spooler.HandleError(event, err, u.view.GetLatestUserSessionFailedEvent, u.view.ProcessedUserSessionFailedEvent, u.view.ProcessedUserSessionSequence, u.errorCountUntilSkip)
}
func (u *UserSession) updateSession(session *view_model.UserSessionView, event *models.Event) error {
session.AppendEvent(event)
if err := u.fillUserInfo(session, event.AggregateID); err != nil {
return err
}
return u.view.PutUserSession(session)
}
func (u *UserSession) fillUserInfo(session *view_model.UserSessionView, id string) error {
user, err := u.view.UserByID(id)
if err != nil {
return err
}
session.UserName = user.UserName
session.LoginName = user.PreferredLoginName
session.DisplayName = user.DisplayName
return nil
}
|
package kitworker
import (
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/metrics"
"github.com/go-kit/kit/tracing/opentracing"
httptransport "github.com/go-kit/kit/transport/http"
stdopentracing "github.com/opentracing/opentracing-go"
)
// ServerOption holds the required parameters for configuring a server
type ServerOption struct {
// Host holds the host's name
Host string
// Tracer holds the collector for zipkin tracing
Tracer stdopentracing.Tracer
// LogErrors configures whether server should log error responses or not
LogErrors bool
// LogRequests configures if the server should log incoming requests or not
LogRequests bool
// Latency holds the metric metric for request latency metric collection, if
// not set Latency metrics will not be collected
Latency metrics.Histogram
// Counter holds the metrics.Counter metric for request count metric
// collection, if not set RequestCountMetrics will not be collected
Counter metrics.Counter
// ServerOptions holds custom httptransport.ServerOption array, will be
// appended to the end of the autogenerated
ServerOptions []httptransport.ServerOption
// Middlewares holds custom endpoint.Middleware array will be appended to
// the end of the autogenerated Middlewares
Middlewares []endpoint.Middleware
}
// Configure prepares middlewares and serverOptions from the client options
//
// If required:
// Adds RequestLatencyMiddleware
// Adds RequestCountMiddleware
// Adds RequestLoggingMiddleware
// Adds Zipkin Tracing
// Adds httptransport.ServerErrorLogger
func (s ServerOption) Configure(moduleName, funcName string, logger log.Logger) ([]endpoint.Middleware, []httptransport.ServerOption) {
var serverOpts []httptransport.ServerOption
var middlewares []endpoint.Middleware
if s.Latency != nil {
middlewares = append(middlewares, RequestLatencyMiddleware(funcName, s.Latency))
}
if s.Counter != nil {
middlewares = append(middlewares, RequestCountMiddleware(funcName, s.Counter))
}
if s.LogRequests {
middlewares = append(middlewares, RequestLoggingMiddleware(funcName, logger))
}
// enable tracing if required
if s.Tracer != nil {
middlewares = append(middlewares, opentracing.TraceServer(s.Tracer, funcName))
}
// log server errors
if s.LogErrors {
serverOpts = append(serverOpts, httptransport.ServerErrorLogger(logger))
}
// If any custom middlewares are passed include them
if len(s.Middlewares) > 0 {
middlewares = append(middlewares, s.Middlewares...)
}
// If any server options are passed include them in server creation
if len(s.ServerOptions) > 0 {
serverOpts = append(serverOpts, s.ServerOptions...)
}
return middlewares, serverOpts
}
|
package models
import (
//"errors"
//"fmt"
//"github.com/revel/revel"
//"github.com/revel/revel/cache"
//"time"
//"github.com/jinzhu/gorm"
)
type GameTemplate struct{
BaseModel
Name string `gorm:"not null"`
Type int
Subtype int
Subname string
RuleLabel string
Var1Label string
Var1Help string
Var1Type int
Var1Range string
Var1Select string
Var2Label string
Var2Help string
Var2Type int
Var2Range string
Var2Select string
}
type Game struct{
BaseModel
User *User `gorm:"not null"`
UserID int32
Topic *Topic `gorm:"not null"`
PostID uint
GameTemplate *GameTemplate `gorm:"not null"`
GameTemplateID uint
Status int
Reward int
GameTime int
PlayerNum int
ShowResult bool
}
type UserGame struct{
BaseModel
User *User `gorm:"not null"`
UserID uint
Game *Game `gorm:"not null"`
GameID uint
Var1 int
Var2 int
IsWin int
}
func FindGame(id, skip, limit int) (games []Game) {
var pageInfo = Pagination{}
pageInfo.Query = db.Model(&Game{}).Preload("GameTemplate")
pageInfo.Query = pageInfo.Query.Where("post_id = ? ", id).Order("id asc")
pageInfo.Offset(skip, limit).Find(&games)
return
}
func FindGameTemplate() (templates []GameTemplate){
db.Model(&GameTemplate{}).Group("type").Order("id asc").Find(&templates)
return
} |
package screen
import "github.com/go-gl/gl/v4.5-compatibility/gl"
type VAO struct {
handle uint32
vbo *VBO
ebo *EBO
}
func (v *VAO) Init(vertices []float32, indices []uint32) *VAO {
var vao uint32
gl.GenVertexArrays(1, &vao)
gl.BindVertexArray(vao)
v.handle = vao
v.vbo = new(VBO).Init(vertices, gl.STATIC_DRAW)
v.ebo = new(EBO).Init(indices, gl.STATIC_DRAW)
// size of one whole vertex (sum of attrib sizes)
var stride int32 = 3*4 + 3*4 + 2*4
var offset int = 0
// position
gl.VertexAttribPointer(0, 3, gl.FLOAT, false, stride, gl.PtrOffset(offset))
gl.EnableVertexAttribArray(0)
offset += 3 * 4
// color
gl.VertexAttribPointer(1, 3, gl.FLOAT, false, stride, gl.PtrOffset(offset))
gl.EnableVertexAttribArray(1)
offset += 3 * 4
// texture position
gl.VertexAttribPointer(2, 2, gl.FLOAT, false, stride, gl.PtrOffset(offset))
gl.EnableVertexAttribArray(2)
offset += 2 * 4
// unbind the VAO (safe practice so we don't accidentally (mis)configure it later)
gl.BindVertexArray(0)
return v
}
func (v *VAO) Bind() {
gl.BindVertexArray(v.handle)
}
func (v *VAO) Unbind() {
gl.BindVertexArray(0)
}
type VBO struct {
handle uint32
}
// typ: gl. gl.STATIC_DRAW etc
func (v *VBO) Init(vertices []float32, typ uint32) *VBO {
var vbo uint32
gl.GenBuffers(1, &vbo)
gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), typ)
v.handle = vbo
return v
}
type EBO struct {
handle uint32
}
func (e *EBO) Init(indices []uint32, typ uint32) *EBO {
var ebo uint32
gl.GenBuffers(1, &ebo)
gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, ebo)
gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(indices)*4, gl.Ptr(indices), typ)
e.handle = ebo
return e
}
|
package configuration
import (
"fmt"
"strings"
"github.com/mohamed-gougam/kube-agent/internal/configuration/version1"
"github.com/mohamed-gougam/kube-agent/internal/nginx"
k8snginx_v1 "github.com/mohamed-gougam/kube-agent/pkg/apis/k8snginx/v1"
)
// Configurer configures NGINX
type Configurer struct {
nginxManager nginx.Manager
tcpServersEx map[string]*TCPServerEx
templateExecutor *version1.TemplateExecutor
}
// NewConfigurer return a new Configurer.
func NewConfigurer(nginxManager nginx.Manager, templateExecutor *version1.TemplateExecutor) *Configurer {
return &Configurer{
nginxManager: nginxManager,
tcpServersEx: make(map[string]*TCPServerEx),
templateExecutor: templateExecutor,
}
}
// AddOrUpdateTCPServer adds TCPServer to nginx's config
func (cgr *Configurer) AddOrUpdateTCPServer(tcpServerEx *TCPServerEx) error {
if err := cgr.addOrUpdateTCPServer(tcpServerEx); err != nil {
return fmt.Errorf("Error adding or updating TCPServer %v/%v: %v", tcpServerEx.TCPServer.Namespace, tcpServerEx.TCPServer.Name, err)
}
if err := cgr.nginxManager.Reload(); err != nil {
return fmt.Errorf("Error reloading NGINX for %v/%v: %v", tcpServerEx.TCPServer.Namespace, tcpServerEx.TCPServer.Name, err)
}
return nil
}
func (cgr *Configurer) addOrUpdateTCPServer(tcpServerEx *TCPServerEx) error {
cfg := generateNginxTCPServerCfg(tcpServerEx)
name := getFileNameForTCPServer(tcpServerEx.TCPServer)
nginxConfig, err := cgr.templateExecutor.ExecuteTCPServerConfigTemplate(cfg)
if err != nil {
return fmt.Errorf("Error generating TCPServer Config %v: %v", name, err)
}
cgr.nginxManager.CreateConfig(name, nginxConfig)
cgr.tcpServersEx[name] = tcpServerEx
return nil
}
// DeleteTCPServer deletes NGINX configuration for the TCPServer
func (cgr *Configurer) DeleteTCPServer(key string) error {
name := getFileNameForTCPServerFromKey(key)
cgr.nginxManager.DeleteConfig(name)
delete(cgr.tcpServersEx, key)
if err := cgr.nginxManager.Reload(); err != nil {
return fmt.Errorf("Error when removing TCPServer %v: %v", key, err)
}
return nil
}
func getFileNameForTCPServer(tcpServer *k8snginx_v1.TCPServer) string {
return fmt.Sprintf("tcp/tcps_%s_%s", tcpServer.Namespace, tcpServer.Name)
}
func getFileNameForTCPServerFromKey(key string) string {
return fmt.Sprintf("tcp/tcps_%s", strings.Replace(key, "/", "_", -1))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.