text stringlengths 11 4.05M |
|---|
package airplay
// A Device is an AirPlay Device.
type Device struct {
Name string
Addr string
Port int
Extra DeviceExtra
}
// A DeviceExtra is extra information of AirPlay device.
type DeviceExtra struct {
Model string
Features string
MacAddress string
ServerVersion string
IsPasswordRequired bool
}
// Devices returns all AirPlay devices in LAN.
func Devices() []Device {
devices := []Device{}
for _, entry := range searchEntry(&queryParam{}) {
devices = append(
devices,
entryToDevice(entry),
)
}
return devices
}
// FirstDevice return the first found AirPlay device in LAN.
func FirstDevice() Device {
params := &queryParam{maxCount: 1}
for _, entry := range searchEntry(params) {
return entryToDevice(entry)
}
return Device{}
}
func entryToDevice(entry *entry) Device {
extra := DeviceExtra{
Model: entry.textRecords["model"],
Features: entry.textRecords["features"],
MacAddress: entry.textRecords["deviceid"],
ServerVersion: entry.textRecords["srcvers"],
IsPasswordRequired: false,
}
if pw, ok := entry.textRecords["pw"]; ok && pw == "1" {
extra.IsPasswordRequired = true
}
return Device{
Name: entry.hostName,
Addr: entry.ipv4.String(),
Port: int(entry.port),
Extra: extra,
}
}
|
package majorityElement
import "testing"
func TestMajorNumMemo(t *testing.T) {
var arr []int
var rs int
arr = []int{3, 2, 3}
arr = []int{2, 2, 1, 1, 1, 2, 2}
rs = MajorNumMemo(arr, len(arr))
t.Logf("rs: %d", rs)
}
func TestMajorNumMiddle(t *testing.T) {
var arr []int
var rs int
arr = []int{3, 2, 3}
arr = []int{2, 2, 1, 1, 1, 1, 2}
rs = MajorNumMiddle(arr, len(arr))
t.Logf("rs: %d", rs)
}
|
package main
import "fmt"
func main() {
a := 40 // declare variable a
fmt.Println(a)
fmt.Println(&a) // print the memory address of a
var b *int = &a // create variable b that is of pointer to an int and assign the value of memory address of a to it
fmt.Println(b)
fmt.Println(*b) // dereference
*b = 45 // the value of this address change to 45
fmt.Println(a)
}
|
package backend
import (
"github.com/anabiozz/yotunheim/backend/common/datastore"
)
// Gatherer ...
type Gatherer interface {
Gather(c datastore.Datastore, acc Accumulator)
}
|
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package geomfn
import (
"github.com/cockroachdb/cockroach/pkg/geo"
"github.com/twpayne/go-geom"
)
// ShiftLongitude returns a modified version of a geometry in which the longitude (X coordinate)
// of each point is incremented by 360 if it is <0 and decremented by 360 if it is >180.
// The result is only meaningful if the coordinates are in longitude/latitude.
func ShiftLongitude(geometry geo.Geometry) (geo.Geometry, error) {
t, err := geometry.AsGeomT()
if err != nil {
return geometry, err
}
newT, err := applyOnCoordsForGeomT(t, func(l geom.Layout, dst []float64, src []float64) error {
copy(dst, src)
if src[0] < 0 {
dst[0] += 360
} else if src[0] > 180 {
dst[0] -= 360
}
return nil
})
if err != nil {
return geometry, err
}
return geo.MakeGeometryFromGeomT(newT)
}
|
//
// SimpleCommandTestCommand.go
// PureMVC Go Multicore
//
// Copyright(c) 2019 Saad Shams <saad.shams@puremvc.org>
// Your reuse is governed by the Creative Commons Attribution 3.0 License
//
package command
import "github.com/puremvc/puremvc-go-multicore-framework/src/interfaces"
/*
A SimpleCommand subclass used by SimpleCommandTest.
*/
type SimpleCommandTestCommand struct {
}
/*
Fabricate a result by multiplying the input by 2
- parameter event: the INotification carrying the SimpleCommandTestVO
*/
func (command SimpleCommandTestCommand) execute(notification interfaces.INotification) {
var vo = notification.Body().(*SimpleCommandTestVO)
//Fabricate a result
vo.Result = 2 * vo.Input
}
|
package cmd
import (
"reflect"
"strings"
"testing"
"time"
)
func TestUsage(t *testing.T) {
f := newFlags()
f.Flag("-x", new(bool), "")
f.Flag("-y", new(bool), "")
got := f.usage()
want := "[OPTION]..."
if got != want {
t.Errorf("usage returned %v, want %v", got, want)
}
}
func TestParse(t *testing.T) {
var (
size int
timeout time.Duration
v bool
percent float64
count int
distance int
name string
)
f := newFlags()
f.Bytes("-m --max-size", &size, "SIZE", "")
f.Duration("-timeout", &timeout, "D", "")
f.Flag("-v", &v, "")
f.Float("--percent", &percent, "P", "")
f.Int("--count", &count, "N", "")
f.Metric("-d", &distance, "DISTANCE", "")
f.String("-name", &name, "NAME", "")
args := "-m 2k -timeout 5m -v --percent 99.5 --count 7 -d 150G -name moon"
f.parse(strings.Split(args, " "))
wantSize := 2048
wantTimeout := 5 * time.Minute
wantV := true
wantPercent := 99.5
wantCount := 7
wantDistance := 150 * 1000000000
wantName := "moon"
if size != wantSize {
t.Errorf("parse set size = %v, want %v", size, wantSize)
}
if timeout != wantTimeout {
t.Errorf("parse set timeout = %v, want %v", timeout, wantTimeout)
}
if v != wantV {
t.Errorf("parse set v = %v, want %v", v, wantV)
}
if percent != wantPercent {
t.Errorf("parse set percent = %v, want %v", percent, wantPercent)
}
if count != wantCount {
t.Errorf("parse set count = %v, want %v", count, wantCount)
}
if distance != wantDistance {
t.Errorf("parse set distance = %v, want %v", distance, wantDistance)
}
if name != wantName {
t.Errorf("parse set name = %v, want %v", name, wantName)
}
}
func TestSplitSpec(t *testing.T) {
cases := []struct {
spec string
want []string
wantError bool
}{
{"-v", []string{"-v"}, false},
{"-v --verbose -d --debug", []string{"-v", "--verbose", "-d", "--debug"}, false},
{"", nil, true},
{"---verbose", nil, true},
{"hello", nil, true},
}
for _, c := range cases {
got, err := splitSpec(c.spec)
if err != nil && !c.wantError {
t.Errorf("splitSpec(%v) returned error", c.spec)
continue
}
if err == nil && c.wantError {
t.Errorf("splitSpec(%v) didn't return error", c.spec)
continue
}
if !reflect.DeepEqual(got, c.want) {
t.Errorf("splitSpec(%v) returned %v, want %v", c.spec, got, c.want)
}
}
}
|
package cmd
import (
"cmp"
"context"
"errors"
"fmt"
"net"
"net/http"
"slices"
"strconv"
"strings"
"sync"
"time"
paho "github.com/eclipse/paho.mqtt.golang"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/charger"
"github.com/evcc-io/evcc/charger/eebus"
"github.com/evcc-io/evcc/cmd/shutdown"
"github.com/evcc-io/evcc/core"
"github.com/evcc-io/evcc/core/site"
"github.com/evcc-io/evcc/hems"
"github.com/evcc-io/evcc/meter"
"github.com/evcc-io/evcc/provider/golang"
"github.com/evcc-io/evcc/provider/javascript"
"github.com/evcc-io/evcc/provider/mqtt"
"github.com/evcc-io/evcc/push"
"github.com/evcc-io/evcc/server"
"github.com/evcc-io/evcc/server/db"
"github.com/evcc-io/evcc/server/db/settings"
"github.com/evcc-io/evcc/server/oauth2redirect"
"github.com/evcc-io/evcc/tariff"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/config"
"github.com/evcc-io/evcc/util/locale"
"github.com/evcc-io/evcc/util/machine"
"github.com/evcc-io/evcc/util/modbus"
"github.com/evcc-io/evcc/util/pipe"
"github.com/evcc-io/evcc/util/request"
"github.com/evcc-io/evcc/util/sponsor"
"github.com/evcc-io/evcc/util/templates"
"github.com/evcc-io/evcc/vehicle"
"github.com/evcc-io/evcc/vehicle/wrapper"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/libp2p/zeroconf/v2"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/sync/errgroup"
"golang.org/x/text/currency"
)
var conf = globalConfig{
Interval: 10 * time.Second,
Log: "info",
Network: networkConfig{
Schema: "http",
Host: "evcc.local",
Port: 7070,
},
Mqtt: mqttConfig{
Topic: "evcc",
},
Database: dbConfig{
Type: "sqlite",
Dsn: "~/.evcc/evcc.db",
},
}
type globalConfig struct {
URI interface{} // TODO deprecated
Network networkConfig
Log string
SponsorToken string
Plant string // telemetry plant id
Telemetry bool
Metrics bool
Profile bool
Levels map[string]string
Interval time.Duration
Database dbConfig
Mqtt mqttConfig
ModbusProxy []proxyConfig
Javascript []javascriptConfig
Go []goConfig
Influx server.InfluxConfig
EEBus map[string]interface{}
HEMS config.Typed
Messaging messagingConfig
Meters []config.Named
Chargers []config.Named
Vehicles []config.Named
Tariffs tariffConfig
Site map[string]interface{}
Loadpoints []map[string]interface{}
}
type mqttConfig struct {
mqtt.Config `mapstructure:",squash"`
Topic string
}
type javascriptConfig struct {
VM string
Script string
}
type goConfig struct {
VM string
Script string
}
type proxyConfig struct {
Port int
ReadOnly bool
modbus.Settings `mapstructure:",squash"`
}
type dbConfig struct {
Type string
Dsn string
}
type messagingConfig struct {
Events map[string]push.EventTemplateConfig
Services []config.Typed
}
type tariffConfig struct {
Currency string
Grid config.Typed
FeedIn config.Typed
Co2 config.Typed
Planner config.Typed
}
type networkConfig struct {
Schema string
Host string
Port int
}
func (c networkConfig) HostPort() string {
if c.Schema == "http" && c.Port == 80 || c.Schema == "https" && c.Port == 443 {
return c.Host
}
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
}
func (c networkConfig) URI() string {
return fmt.Sprintf("%s://%s", c.Schema, c.HostPort())
}
func loadConfigFile(conf *globalConfig) error {
err := viper.ReadInConfig()
if cfgFile = viper.ConfigFileUsed(); cfgFile == "" {
return err
}
log.INFO.Println("using config file:", cfgFile)
if err == nil {
if err = viper.UnmarshalExact(&conf); err != nil {
err = fmt.Errorf("failed parsing config file: %w", err)
}
}
// parse log levels after reading config
if err == nil {
parseLogLevels()
}
return err
}
func configureMeters(static []config.Named) error {
for i, cc := range static {
if cc.Name == "" {
return fmt.Errorf("cannot create meter %d: missing name", i+1)
}
instance, err := meter.NewFromConfig(cc.Type, cc.Other)
if err != nil {
return fmt.Errorf("cannot create meter '%s': %w", cc.Name, err)
}
if err := config.Meters().Add(config.NewStaticDevice(cc, instance)); err != nil {
return err
}
}
// append devices from database
configurable, err := config.ConfigurationsByClass(templates.Meter)
if err != nil {
return err
}
for _, conf := range configurable {
cc := conf.Named()
instance, err := meter.NewFromConfig(cc.Type, cc.Other)
if err != nil {
return fmt.Errorf("cannot create meter '%s': %w", cc.Name, err)
}
if err := config.Meters().Add(config.NewConfigurableDevice(conf, instance)); err != nil {
return err
}
}
return nil
}
func configureChargers(static []config.Named) error {
g, _ := errgroup.WithContext(context.Background())
for i, cc := range static {
if cc.Name == "" {
return fmt.Errorf("cannot create charger %d: missing name", i+1)
}
cc := cc
g.Go(func() error {
instance, err := charger.NewFromConfig(cc.Type, cc.Other)
if err != nil {
return fmt.Errorf("cannot create charger '%s': %w", cc.Name, err)
}
return config.Chargers().Add(config.NewStaticDevice(cc, instance))
})
}
// append devices from database
configurable, err := config.ConfigurationsByClass(templates.Charger)
if err != nil {
return err
}
for _, conf := range configurable {
conf := conf
g.Go(func() error {
cc := conf.Named()
instance, err := charger.NewFromConfig(cc.Type, cc.Other)
if err != nil {
return fmt.Errorf("cannot create charger '%s': %w", cc.Name, err)
}
return config.Chargers().Add(config.NewConfigurableDevice(conf, instance))
})
}
return g.Wait()
}
func vehicleInstance(cc config.Named) (api.Vehicle, error) {
instance, err := vehicle.NewFromConfig(cc.Type, cc.Other)
if err != nil {
var ce *util.ConfigError
if errors.As(err, &ce) {
return nil, fmt.Errorf("cannot create vehicle '%s': %w", cc.Name, err)
}
// wrap non-config vehicle errors to prevent fatals
log.ERROR.Printf("creating vehicle %s failed: %v", cc.Name, err)
instance = wrapper.New(cc.Name, cc.Other, err)
}
// ensure vehicle config has title
if instance.Title() == "" {
//lint:ignore SA1019 as Title is safe on ascii
instance.SetTitle(strings.Title(cc.Name))
}
return instance, nil
}
func configureVehicles(static []config.Named) error {
g, _ := errgroup.WithContext(context.Background())
for i, cc := range static {
if cc.Name == "" {
return fmt.Errorf("cannot create vehicle %d: missing name", i+1)
}
cc := cc
g.Go(func() error {
instance, err := vehicleInstance(cc)
if err != nil {
return fmt.Errorf("cannot create vehicle '%s': %w", cc.Name, err)
}
return config.Vehicles().Add(config.NewStaticDevice(cc, instance))
})
}
// append devices from database
configurable, err := config.ConfigurationsByClass(templates.Vehicle)
if err != nil {
return err
}
// stable-sort vehicles by id
var mu sync.Mutex
devs := make([]config.ConfigurableDevice[api.Vehicle], 0, len(configurable))
for _, conf := range configurable {
conf := conf
g.Go(func() error {
cc := conf.Named()
instance, err := vehicleInstance(cc)
if err != nil {
return fmt.Errorf("cannot create vehicle '%s': %w", cc.Name, err)
}
mu.Lock()
defer mu.Unlock()
devs = append(devs, config.NewConfigurableDevice(conf, instance))
return nil
})
}
if err := g.Wait(); err != nil {
return err
}
slices.SortFunc(devs, func(i, j config.ConfigurableDevice[api.Vehicle]) int {
return cmp.Compare(i.ID(), j.ID())
})
for _, dev := range devs {
if err := config.Vehicles().Add(dev); err != nil {
return err
}
}
return nil
}
func configureEnvironment(cmd *cobra.Command, conf globalConfig) (err error) {
// full http request log
if cmd.Flags().Lookup(flagHeaders).Changed {
request.LogHeaders = true
}
// setup machine id
if conf.Plant != "" {
err = machine.CustomID(conf.Plant)
}
// setup sponsorship (allow env override)
if err == nil && conf.SponsorToken != "" {
err = sponsor.ConfigureSponsorship(conf.SponsorToken)
}
// setup translations
if err == nil {
err = locale.Init()
}
// setup persistence
if err == nil && conf.Database.Dsn != "" {
err = configureDatabase(conf.Database)
}
// setup mqtt client listener
if err == nil && conf.Mqtt.Broker != "" {
err = configureMQTT(conf.Mqtt)
}
// setup javascript VMs
if err == nil {
err = configureJavascript(conf.Javascript)
}
// setup go VMs
if err == nil {
err = configureGo(conf.Go)
}
// setup EEBus server
if err == nil && conf.EEBus != nil {
err = configureEEBus(conf.EEBus)
}
// setup config database
if err == nil {
err = config.Init(db.Instance)
}
return
}
// configureDatabase configures session database
func configureDatabase(conf dbConfig) error {
if err := db.NewInstance(conf.Type, conf.Dsn); err != nil {
return err
}
if err := settings.Init(); err != nil {
return err
}
persistSettings := func() {
if err := settings.Persist(); err != nil {
log.ERROR.Println("cannot save settings:", err)
}
}
// persist unsaved settings on shutdown
shutdown.Register(persistSettings)
// persist unsaved settings every 30 minutes
go func() {
for range time.Tick(30 * time.Minute) {
persistSettings()
}
}()
return nil
}
// configureInflux configures influx database
func configureInflux(conf server.InfluxConfig, site site.API, in <-chan util.Param) {
influx := server.NewInfluxClient(
conf.URL,
conf.Token,
conf.Org,
conf.User,
conf.Password,
conf.Database,
)
// eliminate duplicate values
dedupe := pipe.NewDeduplicator(30*time.Minute, "vehicleCapacity", "vehicleSoc", "vehicleRange", "vehicleOdometer", "chargedEnergy", "chargeRemainingEnergy")
in = dedupe.Pipe(in)
go influx.Run(site, in)
}
// setup mqtt
func configureMQTT(conf mqttConfig) error {
log := util.NewLogger("mqtt")
instance, err := mqtt.RegisteredClient(log, conf.Broker, conf.User, conf.Password, conf.ClientID, 1, conf.Insecure, func(options *paho.ClientOptions) {
topic := fmt.Sprintf("%s/status", strings.Trim(conf.Topic, "/"))
options.SetWill(topic, "offline", 1, true)
oc := options.OnConnect
options.SetOnConnectHandler(func(client paho.Client) {
oc(client) // original handler
_ = client.Publish(topic, 1, true, "online") // alive - not logged
})
})
if err != nil {
return fmt.Errorf("failed configuring mqtt: %w", err)
}
mqtt.Instance = instance
return nil
}
// setup javascript
func configureJavascript(conf []javascriptConfig) error {
for _, cc := range conf {
if _, err := javascript.RegisteredVM(cc.VM, cc.Script); err != nil {
return fmt.Errorf("failed configuring javascript: %w", err)
}
}
return nil
}
// setup go
func configureGo(conf []goConfig) error {
for _, cc := range conf {
if _, err := golang.RegisteredVM(cc.VM, cc.Script); err != nil {
return fmt.Errorf("failed configuring go: %w", err)
}
}
return nil
}
// setup HEMS
func configureHEMS(conf config.Typed, site *core.Site, httpd *server.HTTPd) error {
hems, err := hems.NewFromConfig(conf.Type, conf.Other, site, httpd)
if err != nil {
return fmt.Errorf("failed configuring hems: %w", err)
}
go hems.Run()
return nil
}
// setup MDNS
func configureMDNS(conf networkConfig) error {
host := strings.TrimSuffix(conf.Host, ".local")
zc, err := zeroconf.RegisterProxy("EV Charge Controller", "_http._tcp", "local.", conf.Port, host, nil, []string{}, nil)
if err != nil {
return fmt.Errorf("mDNS announcement: %w", err)
}
shutdown.Register(zc.Shutdown)
return nil
}
// setup EEBus
func configureEEBus(conf map[string]interface{}) error {
var err error
if eebus.Instance, err = eebus.NewServer(conf); err != nil {
return fmt.Errorf("failed configuring eebus: %w", err)
}
eebus.Instance.Run()
shutdown.Register(eebus.Instance.Shutdown)
return nil
}
// setup messaging
func configureMessengers(conf messagingConfig, valueChan chan util.Param, cache *util.Cache) (chan push.Event, error) {
messageChan := make(chan push.Event, 1)
messageHub, err := push.NewHub(conf.Events, cache)
if err != nil {
return messageChan, fmt.Errorf("failed configuring push services: %w", err)
}
for _, service := range conf.Services {
impl, err := push.NewFromConfig(service.Type, service.Other)
if err != nil {
return messageChan, fmt.Errorf("failed configuring push service %s: %w", service.Type, err)
}
messageHub.Add(impl)
}
go messageHub.Run(messageChan, valueChan)
return messageChan, nil
}
func configureTariffs(conf tariffConfig) (tariff.Tariffs, error) {
var grid, feedin, co2, planner api.Tariff
var currencyCode currency.Unit = currency.EUR
var err error
if conf.Currency != "" {
currencyCode = currency.MustParseISO(conf.Currency)
}
if conf.Grid.Type != "" {
grid, err = tariff.NewFromConfig(conf.Grid.Type, conf.Grid.Other)
if err != nil {
grid = nil
log.ERROR.Printf("failed configuring grid tariff: %v", err)
}
}
if conf.FeedIn.Type != "" {
feedin, err = tariff.NewFromConfig(conf.FeedIn.Type, conf.FeedIn.Other)
if err != nil {
feedin = nil
log.ERROR.Printf("failed configuring feed-in tariff: %v", err)
}
}
if conf.Co2.Type != "" {
co2, err = tariff.NewFromConfig(conf.Co2.Type, conf.Co2.Other)
if err != nil {
co2 = nil
log.ERROR.Printf("failed configuring co2 tariff: %v", err)
}
}
if conf.Planner.Type != "" {
planner, err = tariff.NewFromConfig(conf.Planner.Type, conf.Planner.Other)
if err != nil {
planner = nil
log.ERROR.Printf("failed configuring planner tariff: %v", err)
} else if planner.Type() == api.TariffTypeCo2 {
log.WARN.Printf("tariff configuration changed, use co2 instead of planner for co2 tariff")
}
}
tariffs := tariff.NewTariffs(currencyCode, grid, feedin, co2, planner)
return *tariffs, nil
}
func configureDevices(conf globalConfig) error {
if err := configureMeters(conf.Meters); err != nil {
return err
}
if err := configureChargers(conf.Chargers); err != nil {
return err
}
return configureVehicles(conf.Vehicles)
}
func configureSiteAndLoadpoints(conf globalConfig) (*core.Site, error) {
if err := configureDevices(conf); err != nil {
return nil, err
}
loadpoints, err := configureLoadpoints(conf)
if err != nil {
return nil, fmt.Errorf("failed configuring loadpoints: %w", err)
}
tariffs, err := configureTariffs(conf.Tariffs)
if err != nil {
return nil, err
}
return configureSite(conf.Site, loadpoints, config.Instances(config.Vehicles().Devices()), tariffs)
}
func configureSite(conf map[string]interface{}, loadpoints []*core.Loadpoint, vehicles []api.Vehicle, tariffs tariff.Tariffs) (*core.Site, error) {
site, err := core.NewSiteFromConfig(log, conf, loadpoints, vehicles, tariffs)
if err != nil {
return nil, fmt.Errorf("failed configuring site: %w", err)
}
return site, nil
}
func configureLoadpoints(conf globalConfig) (loadpoints []*core.Loadpoint, err error) {
lpInterfaces, ok := viper.AllSettings()["loadpoints"].([]interface{})
if !ok || len(lpInterfaces) == 0 {
return nil, errors.New("missing loadpoints")
}
for id, lpcI := range lpInterfaces {
var lpc map[string]interface{}
if err := util.DecodeOther(lpcI, &lpc); err != nil {
return nil, fmt.Errorf("failed decoding loadpoint configuration: %w", err)
}
log := util.NewLogger("lp-" + strconv.Itoa(id+1))
lp, err := core.NewLoadpointFromConfig(log, lpc)
if err != nil {
return nil, fmt.Errorf("failed configuring loadpoint: %w", err)
}
loadpoints = append(loadpoints, lp)
}
return loadpoints, nil
}
// configureAuth handles routing for devices. For now only api.AuthProvider related routes
func configureAuth(conf networkConfig, vehicles []api.Vehicle, router *mux.Router, paramC chan<- util.Param) {
auth := router.PathPrefix("/oauth").Subrouter()
auth.Use(handlers.CompressHandler)
auth.Use(handlers.CORS(
handlers.AllowedHeaders([]string{"Content-Type"}),
))
// wire the handler
oauth2redirect.SetupRouter(auth)
// initialize
authCollection := util.NewAuthCollection(paramC)
baseURI := conf.URI()
baseAuthURI := fmt.Sprintf("%s/oauth", baseURI)
var id int
for _, v := range vehicles {
if provider, ok := v.(api.AuthProvider); ok {
id += 1
basePath := fmt.Sprintf("vehicles/%d", id)
callbackURI := fmt.Sprintf("%s/%s/callback", baseAuthURI, basePath)
// register vehicle
ap := authCollection.Register(fmt.Sprintf("oauth/%s", basePath), v.Title())
provider.SetCallbackParams(baseURI, callbackURI, ap.Handler())
auth.
Methods(http.MethodPost).
Path(fmt.Sprintf("/%s/login", basePath)).
HandlerFunc(provider.LoginHandler())
auth.
Methods(http.MethodPost).
Path(fmt.Sprintf("/%s/logout", basePath)).
HandlerFunc(provider.LogoutHandler())
log.INFO.Printf("ensure the oauth client redirect/callback is configured for %s: %s", v.Title(), callbackURI)
}
}
authCollection.Publish()
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package feedback
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/fsutil"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/faillog"
fa "chromiumos/tast/local/chrome/uiauto/feedbackapp"
"chromiumos/tast/local/chrome/uiauto/nodewith"
"chromiumos/tast/local/chrome/uiauto/role"
"chromiumos/tast/local/cryptohome"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: AttachFile,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Verify user can attach a file",
Contacts: []string{
"zhangwenyu@google.com",
"xiangdongkong@google.com",
"cros-feedback-app@google.com",
},
Fixture: "chromeLoggedInWithOsFeedback",
Attr: []string{"group:mainline", "informational"},
Data: []string{fa.PngFile, fa.PdfFile},
SoftwareDeps: []string{"chrome"},
Timeout: 3 * time.Minute,
})
}
// AttachFile verifies user can attach a file.
func AttachFile(ctx context.Context, s *testing.State) {
cr := s.FixtValue().(*chrome.Chrome)
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 5*time.Second)
defer cancel()
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to connect to Test API: ", err)
}
defer faillog.DumpUITreeWithScreenshotOnError(cleanupCtx, s.OutDir(), s.HasError, cr,
"ui_dump")
downloadsPath, err := cryptohome.DownloadsPath(ctx, cr.NormalizedUser())
if err != nil {
s.Fatal("Failed to get user's Download path: ", err)
}
// Clean up in the end.
defer func() {
files, err := ioutil.ReadDir(downloadsPath)
if err != nil {
s.Log("Failed to read files in Downloads: ", err)
} else {
for _, f := range files {
path := filepath.Join(downloadsPath, f.Name())
if err := os.RemoveAll(path); err != nil {
s.Logf("Failed to RemoveAll(%q)", path)
}
}
}
}()
ui := uiauto.New(tconn).WithTimeout(20 * time.Second)
// Copy the file to Downloads for uploading purpose.
files := []string{fa.PngFile, fa.PdfFile}
for _, fileName := range files {
if err := fsutil.CopyFile(
s.DataPath(fileName), filepath.Join(downloadsPath, fileName)); err != nil {
s.Fatal("Failed to copy file to Downloads: ", err)
}
}
// Launch feedback app and go to share data page.
feedbackRootNode, err := fa.LaunchAndGoToShareDataPage(ctx, tconn)
if err != nil {
s.Fatal("Failed to launch feedback app and go to share data page: ", err)
}
// Find add file button and click.
addFileButton := nodewith.NameContaining("Add file").Role(
role.Button).Ancestor(feedbackRootNode)
if err := ui.DoDefault(addFileButton)(ctx); err != nil {
s.Fatal("Failed to click add file button: ", err)
}
// Open Downloads dir and select the png file to upload.
if err := uiauto.Combine("Open Downloads dir and select PNG file",
ui.LeftClick(nodewith.Name("Downloads").Role(role.TreeItem)),
ui.LeftClick(nodewith.NameContaining(fa.PngFile).Role(role.StaticText).First()),
ui.LeftClick(nodewith.Name("Open").Role(role.Button)),
)(ctx); err != nil {
s.Fatal("Failed to open Downloads dir and select PNG file: ", err)
}
// Verify the uploaded png file exists.
pngFileFinder := nodewith.NameContaining(fa.PngFile).Role(
role.StaticText).Ancestor(feedbackRootNode)
if err := ui.WaitUntilExists(pngFileFinder)(ctx); err != nil {
s.Fatal("Failed to find png file: ", err)
}
// Find replace button and click.
replaceButton := nodewith.NameContaining("Replace").Role(
role.Button).Ancestor(feedbackRootNode)
if err := ui.DoDefault(replaceButton)(ctx); err != nil {
s.Fatal("Failed to click replace button: ", err)
}
// Upload pdf file.
if err := uiauto.Combine("Open Downloads dir and select pdf file",
ui.LeftClick(nodewith.Name("Downloads").Role(role.TreeItem)),
ui.LeftClick(nodewith.NameContaining(fa.PdfFile).Role(role.StaticText).First()),
ui.LeftClick(nodewith.Name("Open").Role(role.Button)),
)(ctx); err != nil {
s.Fatal("Failed to open Downloads dir and select pdf file: ", err)
}
// Verify new uploaded pdf file exists.
newFile := nodewith.NameContaining(fa.PdfFile).Role(role.StaticText).Ancestor(feedbackRootNode)
if err := ui.WaitUntilExists(newFile)(ctx); err != nil {
s.Fatal("Failed to find new file: ", err)
}
}
|
package main
import (
"flag"
"fmt"
"os"
"log"
//"github.com/sapcc/hermes-etl/sink"
"github.com/sapcc/hermes-etl/source"
"github.com/spf13/viper"
)
func main() {
// Handle Config options, command line support for config location
configPath := parseCmdFlags()
setDefaultConfig()
readConfig(configPath)
//URI := "amqp://guest:guest@localhost:5672/"
//fmt.Println(URI)
//mqconn := source.Source{URI: viper.GetString("rabbitmq.uri"), Queue: viper.GetString("rabbitmq.queue")}
c, err := source.NewConsumer(viper.GetString("rabbitmq.uri"), "", viper.GetString("rabbitmq.queue"), "", "")
if err != nil {
log.Fatal(err)
}
source.ConsumeQueue(c.Channel, viper.GetString("rabbitmq.queue"), c.Done)
}
// parseCmdFlags grabs the location to hermes-etl.conf and parses it, or prints Usage
func parseCmdFlags() *string {
// Get config file location
configPath := flag.String("f", "hermes-etl.conf", "specifies the location of the TOML-format configuration file")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
return configPath
}
func setDefaultConfig() {
viper.SetDefault("elasticsearch.uri", "http://127.0.0.1:9200")
viper.SetDefault("rabbitmq.uri", "amqp://guest:guest@localhost:5672/")
viper.SetDefault("rabbitmq.queue", "hello")
}
// readConfig reads the configuration file from the configPath
func readConfig(configPath *string) {
// Don't read config file if the default config file isn't there,
// as we will just fall back to config defaults in that case
var shouldReadConfig = true
if _, err := os.Stat(*configPath); os.IsNotExist(err) {
shouldReadConfig = *configPath != flag.Lookup("f").DefValue
}
// Now we sorted that out, read the config
fmt.Printf("Should read config: %v, config file is %s", shouldReadConfig, *configPath)
if shouldReadConfig {
viper.SetConfigFile(*configPath)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s", err))
}
}
}
|
package main
import (
"bytes"
"fmt"
"net/url"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/mattermost/mattermost-plugin-api/experimental/command"
"github.com/mattermost/mattermost-plugin-api/experimental/flow"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/plugin"
"github.com/mattermost/mattermost-plugin-jira/server/utils"
"github.com/mattermost/mattermost-plugin-jira/server/utils/kvstore"
"github.com/mattermost/mattermost-plugin-jira/server/utils/types"
)
const commandTrigger = "jira"
var jiraCommandHandler = CommandHandler{
handlers: map[string]CommandHandlerFunc{
"assign": executeAssign,
"connect": executeConnect,
"disconnect": executeDisconnect,
"help": executeHelp,
"me": executeMe,
"about": executeAbout,
"install/cloud": executeInstanceInstallCloud,
"install/cloud-oauth": executeInstanceInstallCloudOAuth,
"install/server": executeInstanceInstallServer,
"instance/alias": executeInstanceAlias,
"instance/unalias": executeInstanceUnalias,
"instance/connect": executeConnect,
"instance/disconnect": executeDisconnect,
"instance/install/cloud": executeInstanceInstallCloud,
"instance/install/cloud-oauth": executeInstanceInstallCloudOAuth,
"instance/install/server": executeInstanceInstallServer,
"instance/list": executeInstanceList,
"instance/settings": executeSettings,
"instance/uninstall": executeInstanceUninstall,
"instance/v2": executeInstanceV2Legacy,
"issue/assign": executeAssign,
"issue/transition": executeTransition,
"issue/unassign": executeUnassign,
"issue/view": executeView,
"settings": executeSettings,
"subscribe/list": executeSubscribeList,
"transition": executeTransition,
"unassign": executeUnassign,
"uninstall": executeInstanceUninstall,
"view": executeView,
"v2revert": executeV2Revert,
"webhook": executeWebhookURL,
"setup": executeSetup,
},
defaultHandler: executeJiraDefault,
}
const helpTextHeader = "###### Mattermost Jira Plugin - Slash Command Help\n"
const commonHelpText = "\n" +
"* `/jira connect [jiraURL]` - Connect your Mattermost account to your Jira account\n" +
"* `/jira disconnect [jiraURL]` - Disconnect your Mattermost account from your Jira account\n" +
"* `/jira [issue] assign [issue-key] [assignee]` - Change the assignee of a Jira issue\n" +
"* `/jira [issue] create [text]` - Create a new Issue with 'text' inserted into the description field\n" +
"* `/jira [issue] transition [issue-key] [state]` - Change the state of a Jira issue\n" +
"* `/jira [issue] unassign [issue-key]` - Unassign the Jira issue\n" +
"* `/jira [issue] view [issue-key]` - View the details of a specific Jira issue\n" +
"* `/jira help` - Launch the Jira plugin command line help syntax\n" +
"* `/jira me` - Display information about the current user\n" +
"* `/jira about` - Display build info\n" +
"* `/jira instance list` - List installed Jira instances\n" +
"* `/jira instance settings [setting] [value]` - Update your user settings\n" +
" * [setting] can be `notifications`\n" +
" * [value] can be `on` or `off`\n" +
""
const sysAdminHelpText = "\n###### For System Administrators:\n" +
"Install Jira instances:\n" +
"* `/jira instance install server [jiraURL]` - Connect Mattermost to a Jira Server or Data Center instance located at <jiraURL>\n" +
"* `/jira instance install cloud-oauth [jiraURL]` - Connect Mattermost to a Jira Cloud instance using OAuth 2.0 located at <jiraURL>\n" +
"* `/jira instance install cloud [jiraURL]` - Connect Mattermost to a Jira Cloud instance located at <jiraURL>. (Deprecated. Please use `cloud-oauth` instead.)\n" +
"Uninstall Jira instances:\n" +
"* `/jira instance uninstall server [jiraURL]` - Disconnect Mattermost from a Jira Server or Data Center instance located at <jiraURL>\n" +
"* `/jira instance uninstall cloud-oauth [jiraURL]` - Disconnect Mattermost from a Jira Cloud instance using OAuth 2.0 located at <jiraURL>\n" +
"* `/jira instance uninstall cloud [jiraURL]` - Disconnect Mattermost from a Jira Cloud instance located at <jiraURL>\n" +
"Manage channel subscriptions:\n" +
"* `/jira subscribe ` - Configure the Jira notifications sent to this channel\n" +
"* `/jira subscribe list` - Display all the the subscription rules setup across all the channels and teams on your Mattermost instance\n" +
"Other:\n" +
"* `/jira instance alias [URL] [alias-name]` - assign an alias to an instance\n" +
"* `/jira instance unalias [alias-name]` - remve an alias from an instance\n" +
"* `/jira instance v2 <jiraURL>` - Set the Jira instance to process \"v2\" webhooks and subscriptions (not prefixed with the instance ID)\n" +
"* `/jira webhook [--instance=<jiraURL>]` - Show the Mattermost webhook to receive JQL queries\n" +
"* `/jira v2revert ` - Revert to V2 jira plugin data model\n" +
""
func (p *Plugin) registerJiraCommand(enableAutocomplete, enableOptInstance bool) error {
// Optimistically unregister what was registered before
_ = p.client.SlashCommand.Unregister("", commandTrigger)
command, err := p.createJiraCommand(enableAutocomplete, enableOptInstance)
if err != nil {
return errors.Wrap(err, "failed to get command")
}
err = p.client.SlashCommand.Register(command)
if err != nil {
return errors.Wrapf(err, "failed to register /%s command", commandTrigger)
}
return nil
}
func (p *Plugin) createJiraCommand(enableAutocomplete, enableOptInstance bool) (*model.Command, error) {
jira := model.NewAutocompleteData(
commandTrigger, "[issue|instance|help|me|about]", "Connect to and interact with Jira")
if enableAutocomplete {
addSubCommands(jira, enableOptInstance)
}
iconData, err := command.GetIconData(p.API, "assets/icon.svg")
if err != nil {
return nil, errors.Wrap(err, "failed to get icon data")
}
return &model.Command{
Trigger: jira.Trigger,
Description: "Integration with Jira.",
DisplayName: "Jira",
AutoComplete: true,
AutocompleteData: jira,
AutoCompleteDesc: jira.HelpText,
AutoCompleteHint: jira.Hint,
AutocompleteIconData: iconData,
}, nil
}
func addSubCommands(jira *model.AutocompleteData, optInstance bool) {
// Top-level common commands
jira.AddCommand(createViewCommand(optInstance))
jira.AddCommand(createTransitionCommand(optInstance))
jira.AddCommand(createAssignCommand(optInstance))
jira.AddCommand(createUnassignCommand(optInstance))
// Generic commands
jira.AddCommand(createIssueCommand(optInstance))
jira.AddCommand(createInstanceCommand(optInstance))
// Admin commands
jira.AddCommand(createSubscribeCommand(optInstance))
jira.AddCommand(createWebhookCommand(optInstance))
jira.AddCommand(createSetupCommand())
// Help and info
jira.AddCommand(model.NewAutocompleteData("help", "", "Display help for `/jira` command"))
jira.AddCommand(model.NewAutocompleteData("me", "", "Display information about the current user"))
jira.AddCommand(command.BuildInfoAutocomplete("about"))
}
func createInstanceCommand(optInstance bool) *model.AutocompleteData {
instance := model.NewAutocompleteData(
"instance", "[alias|connect|disconnect|settings|unalias]", "View and manage installed Jira instances; more commands available to system administrators")
instance.AddCommand(createAliasCommand())
instance.AddCommand(createUnAliasCommand())
instance.AddCommand(createConnectCommand())
instance.AddCommand(createSettingsCommand(optInstance))
instance.AddCommand(createDisconnectCommand())
jiraTypes := []model.AutocompleteListItem{
{HelpText: "Jira Server or Datacenter", Item: "server"},
{HelpText: "Jira Cloud OAuth 2.0 (atlassian.net)", Item: "cloud-oauth"},
{HelpText: "Jira Cloud (atlassian.net) (Deprecated. Please use cloud-oauth instead.)", Item: "cloud"},
}
install := model.NewAutocompleteData(
"install", "[cloud|server|cloud-oauth] [URL]", "Connect Mattermost to a Jira instance")
install.AddStaticListArgument("Jira type: server, cloud or cloud-oauth", true, jiraTypes)
install.AddTextArgument("Jira URL", "Enter the Jira URL, e.g. https://mattermost.atlassian.net", "")
install.RoleID = model.SystemAdminRoleId
uninstall := model.NewAutocompleteData(
"uninstall", "[cloud|server|cloud-oauth] [URL]", "Disconnect Mattermost from a Jira instance")
uninstall.AddStaticListArgument("Jira type: server, cloud or cloud-oauth", true, jiraTypes)
uninstall.AddDynamicListArgument("Jira instance", makeAutocompleteRoute(routeAutocompleteInstalledInstance), true)
uninstall.RoleID = model.SystemAdminRoleId
list := model.NewAutocompleteData(
"list", "", "List installed Jira instances")
list.RoleID = model.SystemAdminRoleId
instance.AddCommand(createConnectCommand())
instance.AddCommand(createDisconnectCommand())
instance.AddCommand(list)
instance.AddCommand(createSettingsCommand(optInstance))
instance.AddCommand(install)
instance.AddCommand(uninstall)
return instance
}
func createIssueCommand(optInstance bool) *model.AutocompleteData {
issue := model.NewAutocompleteData(
"issue", "[view|assign|transition]", "View and manage Jira issues")
issue.AddCommand(createViewCommand(optInstance))
issue.AddCommand(createTransitionCommand(optInstance))
issue.AddCommand(createAssignCommand(optInstance))
issue.AddCommand(createUnassignCommand(optInstance))
return issue
}
func withFlagInstance(cmd *model.AutocompleteData, optInstance bool, route string) {
if !optInstance {
return
}
cmd.AddNamedDynamicListArgument("instance", "Jira URL", route, false)
}
func withParamIssueKey(cmd *model.AutocompleteData) {
// TODO: Implement dynamic autocomplete for Jira issue (search)
cmd.AddTextArgument("Jira issue key", "", "")
}
func createConnectCommand() *model.AutocompleteData {
connect := model.NewAutocompleteData(
"connect", "", "Connect your Mattermost account to your Jira account")
connect.AddDynamicListArgument("Jira URL", makeAutocompleteRoute(routeAutocompleteConnect), false)
return connect
}
func createAliasCommand() *model.AutocompleteData {
alias := model.NewAutocompleteData(
"alias", "", "Create an alias to your Jira instance")
alias.AddDynamicListArgument("Jira URL", makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias), false)
return alias
}
func createUnAliasCommand() *model.AutocompleteData {
alias := model.NewAutocompleteData(
"unalias", "", "Remove an alias from a Jira instance")
alias.AddDynamicListArgument("Jira URL", makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias), false)
return alias
}
func createDisconnectCommand() *model.AutocompleteData {
disconnect := model.NewAutocompleteData(
"disconnect", "[Jira URL]", "Disconnect your Mattermost account from your Jira account")
disconnect.AddDynamicListArgument("Jira URL", makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias), false)
return disconnect
}
func createSettingsCommand(optInstance bool) *model.AutocompleteData {
settings := model.NewAutocompleteData(
"settings", "[list|notifications]", "View or update your user settings")
list := model.NewAutocompleteData(
"list", "", "View your current settings")
settings.AddCommand(list)
notifications := model.NewAutocompleteData(
"notifications", "[on|off]", "Update your user notifications settings")
notifications.AddStaticListArgument("value", true, []model.AutocompleteListItem{
{HelpText: "Turn notifications on", Item: "on"},
{HelpText: "Turn notifications off", Item: "off"},
})
withFlagInstance(notifications, optInstance, makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias))
settings.AddCommand(notifications)
return settings
}
func createViewCommand(optInstance bool) *model.AutocompleteData {
view := model.NewAutocompleteData(
"view", "[issue]", "Display a Jira issue")
withParamIssueKey(view)
withFlagInstance(view, optInstance, makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias))
return view
}
func createTransitionCommand(optInstance bool) *model.AutocompleteData {
transition := model.NewAutocompleteData(
"transition", "[Jira issue] [To state]", "Change the state of a Jira issue")
withParamIssueKey(transition)
// TODO: Implement dynamic transition autocomplete
transition.AddTextArgument("To state", "", "")
withFlagInstance(transition, optInstance, makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias))
return transition
}
func createAssignCommand(optInstance bool) *model.AutocompleteData {
assign := model.NewAutocompleteData(
"assign", "[Jira issue] [user]", "Change the assignee of a Jira issue")
withParamIssueKey(assign)
// TODO: Implement dynamic Jira user search autocomplete
assign.AddTextArgument("User", "", "")
withFlagInstance(assign, optInstance, makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias))
return assign
}
func createUnassignCommand(optInstance bool) *model.AutocompleteData {
unassign := model.NewAutocompleteData(
"unassign", "[Jira issue]", "Unassign a Jira issue")
withParamIssueKey(unassign)
withFlagInstance(unassign, optInstance, makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias))
return unassign
}
func createSubscribeCommand(optInstance bool) *model.AutocompleteData {
subscribe := model.NewAutocompleteData(
"subscribe", "[edit|list]", "List or configure the Jira notifications sent to this channel")
subscribe.AddCommand(model.NewAutocompleteData(
"edit", "", "Configure the Jira notifications sent to this channel"))
list := model.NewAutocompleteData(
"list", "", "List the Jira notifications sent to this channel")
withFlagInstance(list, optInstance, makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias))
subscribe.AddCommand(list)
return subscribe
}
func createWebhookCommand(optInstance bool) *model.AutocompleteData {
webhook := model.NewAutocompleteData(
"webhook", "[Jira URL]", "Display the webhook URLs to set up on Jira")
webhook.RoleID = model.SystemAdminRoleId
withFlagInstance(webhook, optInstance, makeAutocompleteRoute(routeAutocompleteInstalledInstanceWithAlias))
return webhook
}
func createSetupCommand() *model.AutocompleteData {
setup := model.NewAutocompleteData(
"setup", "", "Start Jira plugin setup flow")
setup.RoleID = model.SystemAdminRoleId
return setup
}
type CommandHandlerFunc func(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse
type CommandHandler struct {
handlers map[string]CommandHandlerFunc
defaultHandler CommandHandlerFunc
}
func (ch CommandHandler) Handle(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
for n := len(args); n > 0; n-- {
h := ch.handlers[strings.Join(args[:n], "/")]
if h != nil {
return h(p, c, header, args[n:]...)
}
}
return ch.defaultHandler(p, c, header, args...)
}
func executeHelp(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
return p.help(header)
}
func (p *Plugin) help(args *model.CommandArgs) *model.CommandResponse {
authorized, _ := authorizedSysAdmin(p, args.UserId)
helpText := helpTextHeader
jiraAdminAdditionalHelpText := p.getConfig().JiraAdminAdditionalHelpText
// Check if JIRA admin has provided additional help text to be shown up along with regular output
if jiraAdminAdditionalHelpText != "" {
helpText += " " + jiraAdminAdditionalHelpText
}
helpText += commonHelpText
if authorized {
helpText += sysAdminHelpText
}
p.postCommandResponse(args, helpText)
return &model.CommandResponse{}
}
func (p *Plugin) ExecuteCommand(c *plugin.Context, commandArgs *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
err := p.CheckSiteURL()
if err != nil {
return p.responsef(commandArgs, err.Error()), nil
}
args := strings.Fields(commandArgs.Command)
if len(args) == 0 || args[0] != "/jira" {
return p.help(commandArgs), nil
}
return jiraCommandHandler.Handle(p, c, commandArgs, args[1:]...), nil
}
func executeDisconnect(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
if len(args) > 1 {
return p.help(header)
}
jiraURL := ""
if len(args) > 0 {
jiraURL = args[0]
}
instances, err := p.instanceStore.LoadInstances()
if err != nil {
return p.responsef(header, "Failed to load instances. Error: %v.", err)
}
instance := instances.getByAlias(jiraURL)
if instance != nil {
jiraURL = instance.InstanceID.String()
}
disconnected, err := p.DisconnectUser(jiraURL, types.ID(header.UserId))
if errors.Cause(err) == kvstore.ErrNotFound {
errorStr := "Your account is not connected to Jira. Please use `/jira connect` to connect your account."
if jiraURL != "" {
errorStr = fmt.Sprintf("You do not currently have a Jira account at %s linked to your Mattermost account. Please use `/jira connect` to connect your account.", jiraURL)
}
return p.responsef(header, errorStr)
}
if err != nil {
return p.responsef(header, "Could not complete the **disconnection** request. Error: %v", err)
}
return p.responsef(header, "You have successfully disconnected your Jira account (**%s**).", disconnected.DisplayName)
}
func executeConnect(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
if len(args) > 1 {
return p.help(header)
}
jiraURL := ""
if len(args) > 0 {
jiraURL = args[0]
}
instances, err := p.instanceStore.LoadInstances()
if err != nil {
return p.responsef(header, "Failed to load instances. Error: %v.", err)
}
instance := instances.getByAlias(jiraURL)
if instance != nil {
jiraURL = instance.InstanceID.String()
}
info, err := p.GetUserInfo(types.ID(header.UserId), nil)
if err != nil {
return p.responsef(header, "Failed to connect: "+err.Error())
}
if info.Instances.IsEmpty() {
return p.responsef(header,
"No Jira instances have been installed. Please contact the system administrator.")
}
if jiraURL == "" {
if info.connectable.Len() == 1 {
jiraURL = info.connectable.IDs()[0].String()
}
}
instanceID := types.ID(jiraURL)
if info.connectable.IsEmpty() {
return p.responsef(header,
"You already have connected all available Jira accounts. Please use `/jira disconnect --instance=%s` to disconnect.",
instanceID)
}
if !info.connectable.Contains(instanceID) {
return p.responsef(header,
"Jira instance %s is not installed, please contact the system administrator.",
instanceID)
}
conn, err := p.userStore.LoadConnection(instanceID, types.ID(header.UserId))
if err == nil && len(conn.JiraAccountID()) != 0 {
return p.responsef(header,
"You already have a Jira account linked to your Mattermost account from %s. Please use `/jira disconnect --instance=%s` to disconnect.",
instanceID, instanceID)
}
link := routeUserConnect
link = instancePath(link, instanceID)
return p.responsef(header, "[Click here to link your Jira account](%s%s)",
p.GetPluginURL(), link)
}
func executeInstanceAlias(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, "%v", err)
}
if !authorized {
return p.responsef(header, "`/jira instance alias` can only be run by a system administrator.")
}
if len(args) < 2 {
return p.responsef(header, "Please specify both an instance and alias")
}
instanceID := types.ID(args[0])
alias := strings.Join(args[1:], " ")
if len(args) > 2 {
return p.responsef(header, "Alias `%v` is an invalid alias. Please choose an alias without spaces.", alias)
}
instances, err := p.instanceStore.LoadInstances()
if err != nil {
return p.responsef(header, "Failed to load instances. Error: %v.", err)
}
instanceFound := instances.getByAlias(string(instanceID))
if instanceFound != nil {
instanceID = instanceFound.InstanceID
}
isUnique, id := instances.isAliasUnique(instanceID, alias)
if !isUnique {
return p.responsef(header, "Alias `%v` already exists on InstanceID: %v.", alias, id)
}
instance, err := p.instanceStore.LoadInstance(instanceID)
if err != nil {
return p.responsef(header, "Failed to load instance. Error: %v.", err)
}
if instance == nil {
return p.responsef(header, "Failed to get instance. InstanceID: %v.", instanceID)
}
instance.Common().Alias = alias
instances.Set(instance.Common())
err = p.instanceStore.StoreInstances(instances)
if err != nil {
return p.responsef(header, "Failed to save instance. Error: %v.", err)
}
instance.Common().Alias = alias
err = p.instanceStore.StoreInstance(instance)
if err != nil {
return p.responsef(header, "Failed to save instance. Error: %v.", err)
}
return p.responsef(header, "You have successfully aliased instance %v to `%v`.", instanceID, alias)
}
func executeInstanceUnalias(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, "%v", err)
}
if !authorized {
return p.responsef(header, "`/jira instance unalias` can only be run by a system administrator.")
}
if len(args) < 1 {
return p.responsef(header, "Please specify an alias")
}
alias := strings.Join(args, " ")
instances, err := p.instanceStore.LoadInstances()
if err != nil {
return p.responsef(header, "Failed to load instances. Error: %v.", err)
}
instanceFound := instances.getByAlias(alias)
if instanceFound == nil {
return p.responsef(header, "Instance with alias `%v` does not exist.", alias)
}
idFound := instanceFound.InstanceID
instance, err := p.instanceStore.LoadInstance(idFound)
if err != nil {
return p.responsef(header, "Failed to load instance. Error: %v.", err)
}
if instance == nil {
return p.responsef(header, "Failed to get instance. InstanceID: %v.", idFound)
}
instance.Common().Alias = ""
instances.Set(instance.Common())
err = p.instanceStore.StoreInstances(instances)
if err != nil {
return p.responsef(header, "Failed to save instance. Error: %v.", err)
}
err = p.instanceStore.StoreInstance(instance)
if err != nil {
return p.responsef(header, "Failed to save instance. Error: %v.", err)
}
return p.responsef(header, "You have successfully unaliased instance %v from `%v`.", idFound, alias)
}
func executeSettings(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
user, instance, args, err := p.loadFlagUserInstance(header.UserId, args)
if err != nil {
return p.responsef(header, "Failed to load your connection to Jira. Error: %v.", err)
}
conn, err := p.userStore.LoadConnection(instance.GetID(), user.MattermostUserID)
if err != nil {
return p.responsef(header, "Your username is not connected to Jira. Please type `jira connect`. Error: %v.", err)
}
if len(args) == 0 {
return p.responsef(header, "Current settings:\n%s", conn.Settings.String())
}
switch args[0] {
case "list":
return p.responsef(header, "Current settings:\n%s", conn.Settings.String())
case "notifications":
return p.settingsNotifications(header, instance.GetID(), user.MattermostUserID, conn, args)
default:
return p.responsef(header, "Unknown setting.")
}
}
// executeJiraDefault is the default command if no other command fits. It defaults to help.
func executeJiraDefault(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
return p.help(header)
}
// executeView returns a Jira issue formatted as a slack attachment, or an error message.
func executeView(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
user, instance, args, err := p.loadFlagUserInstance(header.UserId, args)
if err != nil {
return p.responsef(header, "Failed to load your connection to Jira. Error: %v.", err)
}
if len(args) != 1 {
return p.responsef(header, "Please specify an issue key in the form `/jira view <issue-key>`.")
}
issueID := args[0]
conn, err := p.userStore.LoadConnection(instance.GetID(), user.MattermostUserID)
if err != nil {
// TODO: try to retrieve the issue anonymously
return p.responsef(header, "Your username is not connected to Jira. Please type `jira connect`.")
}
attachment, err := p.getIssueAsSlackAttachment(instance, conn, strings.ToUpper(issueID), true)
if err != nil {
return p.responsef(header, err.Error())
}
post := &model.Post{
UserId: p.getUserID(),
ChannelId: header.ChannelId,
RootId: header.RootId,
}
post.AddProp("attachments", attachment)
p.client.Post.SendEphemeralPost(header.UserId, post)
return &model.CommandResponse{}
}
// executeV2Revert reverts the store from v3 to v2 and instructs the user how
// to proceed with downgrading
func executeV2Revert(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, "%v", err)
}
if !authorized {
return p.responsef(header, "`/jira v2revert` can only be run by a system administrator.")
}
preMessage := `#### |/jira v2revert| will revert the V3 Jira plugin database to V2. Please use the |--force| flag to complete this command.` + "\n"
if len(args) == 1 && args[0] == "--force" {
msg := MigrateV3ToV2(p)
if msg != "" {
return p.responsef(header, msg)
}
preMessage = `#### Successfully reverted the V3 Jira plugin database to V2. The Jira plugin has been disabled.` + "\n"
go func() {
_ = p.client.Plugin.Disable(Manifest.Id)
}()
}
message := `**Please note that if you have multiple configured Jira instances this command will result in all non-legacy instances being removed.**
After successfully reverting, please **choose one** of the following:
##### 1. Install Jira plugin |v2.4.0|
Downgrade to install the V2 compatible Jira plugin and use the reverted V2 data models created by the |v2revert| command. The Jira plugin |v2.4.0| can be found via the marketplace or GitHub releases page.
##### 2. Continue using the |v3| data model of the plugin
If you ran |v2revert| unintentionally and would like to continue using the current version of the plugin (|v3+|) you can re-enable the plugin through |System Console| > |PLUGINS| > |Plugin Management|. This will perform the necessary migration steps to use a |v3+| version of the Jira plugin.`
message = preMessage + message
message = strings.ReplaceAll(message, "|", "`")
p.TrackUserEvent("v2RevertSubmitted", header.UserId, nil)
return p.responsef(header, message)
}
func executeInstanceList(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, "%v", err)
}
if !authorized {
return p.responsef(header, "`/jira instance list` can only be run by a system administrator.")
}
if len(args) != 0 {
return p.help(header)
}
instances, err := p.instanceStore.LoadInstances()
if err != nil {
return p.responsef(header, "Failed to load known Jira instances: %v", err)
}
if instances.IsEmpty() {
return p.responsef(header, "(none installed)\n")
}
keys := []string{}
for _, key := range instances.IDs() {
keys = append(keys, key.String())
}
sort.Strings(keys)
text := "| |Alias|URL|Type|\n|--|--|--|\n"
for i, key := range keys {
instanceID := types.ID(key)
instanceCommon := instances.Get(instanceID)
instance, err := p.instanceStore.LoadInstance(instanceID)
if err != nil {
text += fmt.Sprintf("|%v|%s|error: %v|\n", i+1, key, err)
continue
}
details := ""
for k, v := range instance.GetDisplayDetails() {
details += fmt.Sprintf("%s:%s, ", k, v)
}
if len(details) > len(", ") {
details = details[:len(details)-2]
} else {
details = string(instance.Common().Type)
}
format := "|%v|%s|%s|%s|\n"
if instances.Get(instanceID).IsV2Legacy {
format = "|%v|%s (v2 legacy)|%s|%s|\n"
}
alias := instanceCommon.Alias
if alias == "" {
alias = "n/a"
}
text += fmt.Sprintf(format, i+1, alias, key, details)
}
return p.responsef(header, text)
}
func executeSubscribeList(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, "%v", err)
}
if !authorized {
return p.responsef(header, "`/jira subscribe list` can only be run by a system administrator.")
}
_, instance, args, err := p.loadFlagUserInstance(header.UserId, args)
if err != nil {
return p.responsef(header, "Failed to identify the Jira instance. Error: %v.", err)
}
if len(args) != 0 {
return p.responsef(header, "No arguments were expected.")
}
msg, err := p.listChannelSubscriptions(instance.GetID(), header.TeamId)
if err != nil {
return p.responsef(header, "%v", err)
}
return p.responsef(header, msg)
}
func authorizedSysAdmin(p *Plugin, userID string) (bool, error) {
user, err := p.client.User.Get(userID)
if err != nil {
return false, err
}
if !strings.Contains(user.Roles, "system_admin") {
return false, nil
}
return true, nil
}
func executeInstanceInstallCloud(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, err.Error())
}
if !authorized {
return p.responsef(header, "`/jira install` can only be run by a system administrator.")
}
if len(args) != 1 {
return p.help(header)
}
jiraURL, err := p.installInactiveCloudInstance(args[0], header.UserId)
if err != nil {
return p.responsef(header, err.Error())
}
return p.respondCommandTemplate(header, "/command/install_cloud.md", map[string]string{
"JiraURL": jiraURL,
"PluginURL": p.GetPluginURL(),
"AtlassianConnectJSONURL": p.GetPluginURL() + instancePath(routeACJSON, types.ID(jiraURL)),
})
}
func executeInstanceInstallCloudOAuth(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, err.Error())
}
if !authorized {
return p.responsef(header, "`/jira install` can only be run by a Mattermost system administrator.")
}
if len(args) != 1 {
return p.help(header)
}
jiraURL, instance, err := p.installCloudOAuthInstance(args[0], "", "")
if err != nil {
return p.responsef(header, err.Error())
}
state := flow.State{
keyEdition: string(CloudOAuthInstanceType),
keyJiraURL: jiraURL,
keyInstance: instance,
keyOAuthCompleteURL: p.GetPluginURL() + instancePath(routeOAuth2Complete, types.ID(jiraURL)),
keyConnectURL: p.GetPluginURL() + instancePath(routeUserConnect, types.ID(jiraURL)),
}
if err = p.oauth2Flow.ForUser(header.UserId).Start(state); err != nil {
return p.responsef(header, err.Error())
}
channel, err := p.client.Channel.GetDirect(header.UserId, p.conf.botUserID)
if err != nil {
return p.responsef(header, err.Error())
}
if channel != nil && channel.Id != header.ChannelId {
return p.responsef(header, "continue in the direct conversation with @jira bot.")
}
return &model.CommandResponse{}
}
func executeInstanceInstallServer(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, err.Error())
}
if !authorized {
return p.responsef(header, "`/jira install` can only be run by a system administrator.")
}
if len(args) != 1 {
return p.help(header)
}
jiraURL, instance, err := p.installServerInstance(args[0])
if err != nil {
return p.responsef(header, err.Error())
}
pkey, err := p.publicKeyString()
if err != nil {
return p.responsef(header, "Failed to load public key: %v", err)
}
return p.respondCommandTemplate(header, "/command/install_server.md", map[string]string{
"JiraURL": jiraURL,
"PluginURL": p.GetPluginURL(),
"MattermostKey": instance.GetMattermostKey(),
"PublicKey": pkey,
})
}
// executeUninstall will uninstall the jira instance if the url matches, and then update all connected clients
// so that their Jira-related menu options are removed.
func executeInstanceUninstall(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, err.Error())
}
if !authorized {
return p.responsef(header, "`/jira uninstall` can only be run by a System Administrator.")
}
if len(args) != 2 {
return p.help(header)
}
instanceType := InstanceType(args[0])
instanceURL := args[1]
id, err := utils.NormalizeJiraURL(instanceURL)
if err != nil {
return p.responsef(header, err.Error())
}
uninstalled, err := p.UninstallInstance(types.ID(id), instanceType)
if err != nil {
return p.responsef(header, err.Error())
}
uninstallInstructions := `` +
`Jira instance successfully uninstalled. Navigate to [**your app management URL**](%s) in order to remove the application from your Jira instance.
Don't forget to remove Jira-side webhook in [Jira System Settings/Webhooks](%s)'
`
return p.responsef(header, uninstallInstructions, uninstalled.GetManageAppsURL(), uninstalled.GetManageWebhooksURL())
}
func executeUnassign(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
_, instance, args, err := p.loadFlagUserInstance(header.UserId, args)
if err != nil {
return p.responsef(header, "Failed to load your connection to Jira. Error: %v.", err)
}
if len(args) != 1 {
return p.responsef(header, "Please specify an issue key in the form `/jira unassign <issue-key>`.")
}
issueKey := strings.ToUpper(args[0])
msg, err := p.UnassignIssue(instance, types.ID(header.UserId), issueKey)
if err != nil {
return p.responsef(header, "%v", err)
}
return p.responsef(header, msg)
}
func executeAssign(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
_, instance, args, err := p.loadFlagUserInstance(header.UserId, args)
if err != nil {
return p.responsef(header, "Failed to load your connection to Jira. Error: %v.", err)
}
if len(args) != 2 {
return p.responsef(header, "Please specify an issue key and an assignee search string, in the form `/jira assign <issue-key> <assignee>`.")
}
issueKey := strings.ToUpper(args[0])
userSearch := strings.Join(args[1:], " ")
msg, err := p.AssignIssue(instance, types.ID(header.UserId), issueKey, userSearch)
if err != nil {
return p.responsef(header, "%v", err)
}
return p.responsef(header, msg)
}
// TODO should transition command post to channel? Options?
func executeTransition(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
instanceURL, args, err := p.parseCommandFlagInstanceURL(args)
if err != nil {
return p.responsef(header, "Failed to load your connection to Jira. Error: %v.", err)
}
if len(args) < 2 {
return p.help(header)
}
issueKey := strings.ToUpper(args[0])
toState := strings.Join(args[1:], " ")
mattermostUserID := types.ID(header.UserId)
_, instanceID, err := p.ResolveUserInstanceURL(mattermostUserID, instanceURL)
if err != nil {
return p.responsef(header, "Failed to identify Jira instance %s. Error: %v.", instanceURL, err)
}
msg, err := p.TransitionIssue(&InTransitionIssue{
InstanceID: instanceID,
mattermostUserID: mattermostUserID,
IssueKey: issueKey,
ToState: toState,
})
if err != nil {
return p.responsef(header, err.Error())
}
return p.responsef(header, msg)
}
func executeMe(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
if len(args) != 0 {
return p.help(header)
}
mattermostUserID := types.ID(header.UserId)
bullet := func(cond bool, k string, v interface{}) string {
if !cond {
return ""
}
return fmt.Sprintf(" * %s: %v\n", k, v)
}
sbullet := func(k, v string) string {
return bullet(v != "", k, v)
}
connectionBullet := func(ic *InstanceCommon, connection *Connection, isDefault bool) string {
id := ic.InstanceID.String()
if isDefault {
id = "**" + id + "**"
}
switch ic.Type {
case CloudInstanceType:
return sbullet(id, fmt.Sprintf("Cloud, connected as **%s** (AccountID: `%s`)",
connection.User.DisplayName,
connection.User.AccountID))
case ServerInstanceType:
return sbullet(id, fmt.Sprintf("Server, connected as **%s** (Name:%s, Key:%s, EmailAddress:%s)",
connection.User.DisplayName,
connection.User.Name,
connection.User.Key,
connection.User.EmailAddress))
}
return ""
}
info, err := p.GetUserInfo(mattermostUserID, nil)
if err != nil {
return p.responsef(header, err.Error())
}
resp := sbullet("Mattermost site URL", p.GetSiteURL())
resp += sbullet("Mattermost user ID", fmt.Sprintf("`%s`", mattermostUserID))
switch {
case info.IsConnected:
resp += fmt.Sprintf("###### Connected to %v Jira instances:\n", info.User.ConnectedInstances.Len())
case info.Instances.Len() > 0:
resp += "Jira is installed, but you are not connected. Please type `/jira connect` to connect.\n"
default:
return p.responsef(header, resp+"\nNo Jira instances installed, please contact your system administrator.")
}
if info.IsConnected {
for _, instanceID := range info.User.ConnectedInstances.IDs() {
connection, err := p.userStore.LoadConnection(instanceID, mattermostUserID)
if err != nil {
return p.responsef(header, err.Error())
}
resp += connectionBullet(info.User.ConnectedInstances.Get(instanceID), connection, info.User.DefaultInstanceID == instanceID)
resp += fmt.Sprintf(" * %s\n", connection.Settings)
if connection.DefaultProjectKey != "" {
resp += fmt.Sprintf(" * Default project: `%s`\n", connection.DefaultProjectKey)
}
}
}
orphans := ""
if !info.Instances.IsEmpty() {
resp += "\n###### Available Jira instances:\n"
for _, instanceID := range info.Instances.IDs() {
encoded := url.PathEscape(encode([]byte(instanceID)))
ic := info.Instances.Get(instanceID)
if ic.IsV2Legacy {
resp += sbullet(instanceID.String(), fmt.Sprintf("%s, **v2 legacy** (`%s`)", ic.Type, encoded))
} else {
resp += sbullet(instanceID.String(), fmt.Sprintf("%s (`%s`)", ic.Type, encoded))
}
}
for _, instanceID := range info.Instances.IDs() {
if info.IsConnected && info.User.ConnectedInstances.Contains(instanceID) {
continue
}
connection, err := p.userStore.LoadConnection(instanceID, mattermostUserID)
if err != nil {
if errors.Cause(err) == kvstore.ErrNotFound {
continue
}
return p.responsef(header, err.Error())
}
orphans += connectionBullet(info.Instances.Get(instanceID), connection, false)
}
}
if orphans != "" {
resp += fmt.Sprintf("###### Orphant Jira connections:\n%s", orphans)
}
return p.responsef(header, resp)
}
func executeAbout(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
text, err := command.BuildInfo(Manifest)
if err != nil {
text = errors.Wrap(err, "failed to get build info").Error()
}
return p.responsef(header, text)
}
func executeWebhookURL(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, "%v", err)
}
if !authorized {
return p.responsef(header, "`/jira webhook` can only be run by a system administrator.")
}
jiraURL, args, err := p.parseCommandFlagInstanceURL(args)
if err != nil {
return p.responsef(header, "%v", err)
}
if len(args) > 0 {
return p.help(header)
}
instanceID, err := p.ResolveWebhookInstanceURL(jiraURL)
if err != nil {
return p.responsef(header, err.Error())
}
instance, err := p.instanceStore.LoadInstance(instanceID)
if err != nil {
return p.responsef(header, err.Error())
}
subWebhookURL, legacyWebhookURL, err := p.GetWebhookURL(jiraURL, header.TeamId, header.ChannelId)
if err != nil {
return p.responsef(header, err.Error())
}
return p.responsef(header,
"To set up webhook for instance %s please navigate to [Jira System Settings/Webhooks](%s) where you can add webhooks.\n"+
"Use `/jira webhook jiraURL` to specify another Jira instance. Use `/jira instance list` to view the available instances.\n"+
"##### Subscriptions webhook.\n"+
"Subscriptions webhook needs to be set up once, is shared by all channels and subscription filters.\n"+
" - `%s`\n"+
" - right-click on [link](%s) and \"Copy Link Address\" to Copy\n"+
"##### Legacy webhooks\n"+
"If your organization's infrastructure is set up such that your Mattermost instance cannot connect to your Jira instance, you will not be able to use the Channel Subscriptions feature. You will instead need to use the \"Legacy Webhooks\" feature supported by the Jira plugin.\n"+
"Legacy webhook needs to be set up for each channel. For this channel:\n"+
" - `%s`\n"+
" - right-click on [link](%s) and \"Copy Link Address\" to copy\n"+
" Visit the [Legacy Webhooks](https://mattermost.gitbook.io/plugin-jira/administrator-guide/notification-management#legacy-webhooks) page to learn more about this feature.\n"+
"",
instanceID, instance.GetManageWebhooksURL(), subWebhookURL, subWebhookURL, legacyWebhookURL, legacyWebhookURL)
}
func executeSetup(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, "%v", err)
}
if !authorized {
return p.responsef(header, "`/jira setup` can only be run by a system administrator.")
}
if err = p.setupFlow.ForUser(header.UserId).Start(nil); err != nil {
return p.responsef(header, errors.Wrap(err, "Failed to start setup wizard").Error())
}
channel, err := p.client.Channel.GetDirect(header.UserId, p.conf.botUserID)
if err != nil {
return p.responsef(header, err.Error())
}
if channel != nil && channel.Id != header.ChannelId {
return p.responsef(header, "continue in the direct conversation with @jira bot.")
}
return &model.CommandResponse{}
}
func (p *Plugin) postCommandResponse(args *model.CommandArgs, text string) {
post := &model.Post{
UserId: p.getUserID(),
ChannelId: args.ChannelId,
RootId: args.RootId,
Message: text,
}
p.client.Post.SendEphemeralPost(args.UserId, post)
}
func (p *Plugin) responsef(commandArgs *model.CommandArgs, format string, args ...interface{}) *model.CommandResponse {
p.postCommandResponse(commandArgs, fmt.Sprintf(format, args...))
return &model.CommandResponse{}
}
func executeInstanceV2Legacy(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {
authorized, err := authorizedSysAdmin(p, header.UserId)
if err != nil {
return p.responsef(header, "%v", err)
}
if !authorized {
return p.responsef(header, "`/jira instance default` can only be run by a system administrator.")
}
if len(args) != 1 {
return p.help(header)
}
instanceID := types.ID(args[0])
err = p.StoreV2LegacyInstance(instanceID)
if err != nil {
return p.responsef(header, "Failed to set default Jira instance %s: %v", instanceID, err)
}
return p.responsef(header, "%s is set as the default Jira instance", instanceID)
}
func (p *Plugin) parseCommandFlagInstanceURL(args []string) (string, []string, error) {
instanceURL := ""
remaining := []string{}
afterFlagInstance := false
for _, arg := range args {
if afterFlagInstance {
instanceURL = arg
afterFlagInstance = false
continue
}
if !strings.HasPrefix(arg, "--instance") {
remaining = append(remaining, arg)
continue
}
if instanceURL != "" {
return "", nil, errors.New("--instance may not be specified multiple times")
}
str := arg[len("--instance"):]
// --instance=X
if strings.HasPrefix(str, "=") {
instanceURL = str[1:]
continue
}
// --instanceXXX error
if str != "" {
return "", nil, errors.Errorf("`%s` is not valid", arg)
}
// --instance X
afterFlagInstance = true
}
if afterFlagInstance && instanceURL == "" {
return "", nil, errors.New("--instance requires a value")
}
instances, err := p.instanceStore.LoadInstances()
if err != nil {
return "", nil, err
}
instance := instances.getByAlias(instanceURL)
if instance != nil {
instanceID := instance.Common().InstanceID
return string(instanceID), remaining, nil
}
return instanceURL, remaining, nil
}
func (p *Plugin) loadFlagUserInstance(mattermostUserID string, args []string) (*User, Instance, []string, error) {
instanceURL, args, err := p.parseCommandFlagInstanceURL(args)
if err != nil {
return nil, nil, nil, err
}
user, instance, err := p.LoadUserInstance(types.ID(mattermostUserID), instanceURL)
if err != nil {
return nil, nil, nil, err
}
return user, instance, args, nil
}
func (p *Plugin) respondCommandTemplate(commandArgs *model.CommandArgs, path string, values interface{}) *model.CommandResponse {
t := p.templates[path]
if t == nil {
return p.responsef(commandArgs, "no template found for "+path)
}
bb := &bytes.Buffer{}
err := t.Execute(bb, values)
if err != nil {
p.responsef(commandArgs, "failed to format results: %v", err)
}
return p.responsef(commandArgs, bb.String())
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package passpoint
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"path/filepath"
"strings"
"text/template"
"time"
"chromiumos/tast/common/crypto/certificate"
"chromiumos/tast/errors"
"chromiumos/tast/local/hostapd"
)
// AccessPoint describes a Passpoint compatible access point with its match criteria.
type AccessPoint struct {
// SSID is the name of the network.
SSID string
// Domain is the FQDN of the provider of this network.
Domain string
// Realms is the set of FQDN supported by this network.
Realms []string
// RoamingConsortiums is the list of OIs supported by this network.
RoamingConsortiums []uint64
// Auth is the EAP network authentication.
Auth
}
// ToServer transforms the Passpoint access point descriptions into a valid hostapd service instance.
func (ap *AccessPoint) ToServer(iface, outDir string) *hostapd.Server {
certs := certificate.TestCert1()
var roamingConsortiums []string
for _, rc := range ap.RoamingConsortiums {
roamingConsortiums = append(roamingConsortiums, fmt.Sprintf("%x", rc))
}
return hostapd.NewServer(
iface,
filepath.Join(outDir, iface),
NewAPConf(
ap.SSID,
ap.Auth,
testUser,
testPassword,
&certs,
ap.Domain,
ap.Realms,
roamingConsortiums,
),
)
}
// APConf contains the parameters required to setup a Passpoint-
// compatible access point.
type APConf struct {
// ssid is the name of the access point.
ssid string
// auth is the authentication method exposed by the access point.
auth Auth
// identity is the username of the EAP user (EAP-TTLS).
identity string
// password is the secret of the EAP user (EAP-TTLS).
password string
// cert is the set of certificates used by the radius server to prove its
// identity and authenticate the user (EAP-TLS).
cert *certificate.CertStore
// domain is the FQDN of the Passpoint service provider.
domain string
// realms is the set of domains supported by the access point.
realms []string
// roamingConsortiums is the Organisation Identifier (OI) list of compatible networks.
roamingConsortiums []string
}
// NewAPConf creates a new Passpoint compatible access point configuration from the parameters.
func NewAPConf(ssid string, auth Auth, identity, password string, cert *certificate.CertStore, domain string, realms, roamingConsortiums []string) *APConf {
return &APConf{
ssid: ssid,
auth: auth,
identity: identity,
password: password,
cert: cert,
domain: domain,
realms: realms,
roamingConsortiums: roamingConsortiums,
}
}
// Generate transforms the configuration parameters in a set of configuration
// files suitable for hostapd.
func (c APConf) Generate(ctx context.Context, dir, ctrlPath string) (string, error) {
serverCertPath := filepath.Join(dir, "cert")
privateKeyPath := filepath.Join(dir, "private_key")
eapUserFilePath := filepath.Join(dir, "eap_user")
caCertPath := filepath.Join(dir, "ca_cert")
confPath := filepath.Join(dir, "hostapd.conf")
// Create the radius users configuration.
eapUsers, err := c.prepareEAPUsers()
if err != nil {
return "", errors.Wrap(err, "failed to prepare EAP users file")
}
confContents, err := c.prepareConf(ctrlPath, caCertPath, serverCertPath, privateKeyPath, eapUserFilePath)
if err != nil {
return "", errors.Wrap(err, "failed to prepare configuration file")
}
for _, p := range []struct {
path string
contents string
}{
{confPath, confContents},
{serverCertPath, c.cert.ServerCred.Cert},
{privateKeyPath, c.cert.ServerCred.PrivateKey},
{eapUserFilePath, eapUsers},
{caCertPath, c.cert.CACred.Cert},
} {
if err := ioutil.WriteFile(p.path, []byte(p.contents), 0644); err != nil {
return "", errors.Wrapf(err, "failed to write file %q", p.path)
}
}
return confPath, nil
}
// prepareEAPUsers creates the content of the radius users file that describes
// how to authenticate users.
func (c APConf) prepareEAPUsers() (string, error) {
switch c.auth {
case AuthTLS:
// TLS auth only requires an outer authentication
return `# Outer authentication
* TLS`, nil
case AuthTTLS:
// TTLS requires outer and inner authentication
return fmt.Sprintf(`# Outer authentication
* TTLS
# Inner authentication
"%s" TTLS-MSCHAPV2 "%s" [2]`, c.identity, c.password), nil
default:
return "", errors.Errorf("unsupported authentication method: %v", c.auth)
}
}
// prepareRealms creates the list of realm domain names with the correct
// authentication parameters.
func (c APConf) prepareRealms() string {
realms := c.domain
if len(c.realms) > 0 {
realms = strings.Join(c.realms, ";")
}
switch c.auth {
case AuthTLS:
// EAP method TLS (13) with credentials type (5) set to certificate (6).
return fmt.Sprintf("%s,13[5:6]", realms)
case AuthTTLS:
// EAP method TTLS (21) with inner authentication (2) set to
// MSCHAPV2 (4) and credentials type (5) set to username/password (7).
return fmt.Sprintf("%s,21[2:4][5:7]", realms)
default:
return realms
}
}
// prepareConf generates the content of hostapd configuration file.
func (c APConf) prepareConf(socketPath, caPath, certPath, keyPath, eapUsers string) (string, error) {
tmpl, err := template.New("").Parse(`
ctrl_interface={{.CtrlSocket}}
# Wireless configuration
ssid={{.SSID}}
hw_mode=g
channel=1
# Enable EAP authentication and server
ieee8021x=1
eapol_version=2
eap_server=1
ca_cert={{.CaCert}}
server_cert={{.ServerCert}}
private_key={{.PrivateKey}}
eap_user_file={{.EapUsers}}
# Security
wpa=2
wpa_key_mgmt=WPA-EAP WPA-EAP-SHA256
wpa_pairwise=CCMP
ieee80211w=1
# Interworking (802.11u-2011)
interworking=1
domain_name={{.Domains}}
nai_realm=0,{{.Realms}}
{{range .RoamingConsortiums}}
roaming_consortium={{.}}
{{end}}
# Hotspot 2.0
hs20=1
`)
if err != nil {
return "", errors.Wrap(err, "failed to parse configuration template")
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, struct {
CtrlSocket string
SSID string
CaCert string
ServerCert string
PrivateKey string
EapUsers string
Domains string
Realms string
RoamingConsortiums []string
}{
CtrlSocket: socketPath,
SSID: c.ssid,
CaCert: caPath,
ServerCert: certPath,
PrivateKey: keyPath,
EapUsers: eapUsers,
Domains: c.domain,
Realms: c.prepareRealms(),
RoamingConsortiums: c.roamingConsortiums,
}); err != nil {
return "", errors.Wrap(err, "failed to execute hostapd configuration template")
}
return buf.String(), nil
}
// STAAssociationTimeout is the reasonable delay to wait for station
// association before making a decision.
const STAAssociationTimeout = time.Minute
// WaitForSTAAssociated polls an access point until a specific station is
// associated or timeout is fired.
func WaitForSTAAssociated(ctx context.Context, m *hostapd.Monitor, client string, timeout time.Duration) error {
return waitForSTAAssociationEvent(ctx, m, client, timeout, true)
}
// WaitForSTADissociated polls an access point until a specific station is
// dissociated or timeout is fired.
func WaitForSTADissociated(ctx context.Context, m *hostapd.Monitor, client string, timeout time.Duration) error {
return waitForSTAAssociationEvent(ctx, m, client, timeout, false)
}
// waitForSTAAssociationEvent polls an access point for until a specific station got an
// association event (association or dissociation based on the parameter association) or until timeout is fired.
func waitForSTAAssociationEvent(ctx context.Context, m *hostapd.Monitor, client string, timeout time.Duration, association bool) error {
timeoutContext, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
iface, err := net.InterfaceByName(client)
if err != nil {
return errors.Wrapf(err, "failed to obtain %s interface information: ", client)
}
for {
event, err := m.WaitForEvent(timeoutContext)
if err != nil {
return errors.Wrap(err, "failed to wait for AP event")
}
if event == nil { // timeout
return errors.New("association event timeout")
}
if e, ok := event.(*hostapd.ApStaConnectedEvent); ok && association {
if bytes.Compare(iface.HardwareAddr, e.Addr) != 0 {
return errors.Errorf("unexpected station association: got %v want %v", e.Addr, iface.HardwareAddr)
}
return nil
}
if e, ok := event.(*hostapd.ApStaDisconnectedEvent); ok && !association {
if bytes.Compare(iface.HardwareAddr, e.Addr) != 0 {
return errors.Errorf("unexpected station association: got %v want %v", e.Addr, iface.HardwareAddr)
}
return nil
}
}
}
|
package main
import (
"fmt"
)
/**
关于这个并行模型, 整个流程可以说是非常操蛋的。。。
1. 首先建立两个 chan 类型的变量, 然后把这两个变量赋予 函数 Processor, 从 Processor(origin, wait),下面就是 赋值到 origin channel 的流程,
Processor(origin, wait) 这一行是不会立马执行的, 因为参数是 channel 类型的, 所以要等 channel全部 读完才执行, 直到 close(origin),
<-wait 这个很重要, 这个是表示程序一直要等 wait 这个 channel 消费完才能结束
2、 再去到 Processor 函数, 这个就是一个 递归函数, 这个递归函数其实每一轮结束的标志就是 这一句 out <- num
整个程序总结就是很抽象。。。。。。。。。。。。
一开始 prime的值其实是2来的, 传进去函数之后, 清晰点的理解, 关键可 out 的值, out每当2, 3, 5, 7, 9 的时候才有值,
所以为了 各个 数都是并行去匹配, 所以才把 out 也设置成 channel
所以整个 并行模型 的总结就是, 为了我们需要的逻辑都实现并行, 就把相关处理函数的 参数 设置为 channel, 然后利用递归函数, 不断
把参数一直 赋值 给函数, 取得函数的返回作为 我们需要的结果就可以了
*/
func main() {
origin, wait := make(chan int), make(chan int)
Processor(origin, wait)
for num := 2; num < 10; num++ {
origin <- num //把num写进 chan 去, 其实这里没有任何并行的概念, 真正的并行逻辑是从 go func(){} 开始的
}
close(origin)
<-wait
}
func Processor(seq chan int, wait chan int) {
go func() {
prime, ok := <-seq
//fmt.Println("get prime -------------------")
//fmt.Println(prime)
//fmt.Println("++++++++++++++\n\n\n")
if !ok {
close(wait)
return
}
//fmt.Println(prime)
out := make(chan int)
Processor(out, wait) //因为参数是 channel类型的, 所以这里是不会马上执行的, 而是去到了下一个 for 循环
//其实这个程序还是不够好的, 因为当5 碰到 不整除的时候
for num := range seq {
//fmt.Println("get num -------------------")
//fmt.Println(num)
fmt.Println("get prime -------------------")
fmt.Println(prime)
fmt.Println("\n\n\n")
//fmt.Println("\n\n")
if num % prime != 0 { //操, 是我想得太复杂了, 其实这个 prime 的值一直都是 2
//fmt.Println(num)
out <- num
}
}
close(out)
}()
}
|
package tests
import (
"testing"
)
/**
* [122] Best Time to Buy and Sell Stock II
*
* Say you have an array for which the i^th element is the price of a given stock on day i.
*
* Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
*
* Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
*
* Example 1:
*
*
* Input: [7,1,5,3,6,4]
* Output: 7
* Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
* Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
*
*
* Example 2:
*
*
* Input: [1,2,3,4,5]
* Output: 4
* Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
* Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
* engaging multiple transactions at the same time. You must sell before buying again.
*
*
* Example 3:
*
*
* Input: [7,6,4,3,1]
* Output: 0
* Explanation: In this case, no transaction is done, i.e. max profit = 0.
*
*/
func TestBestTimetoBuyandSellStockII(t *testing.T) {
var cases = []struct {
input []int
output int
}{
{
input: []int{7, 1, 5, 3, 6, 4},
output: 7,
},
{
input: []int{1, 2, 3, 4, 5},
output: 4,
},
{
input: []int{7, 6, 4, 3, 1},
output: 0,
},
}
for _, c := range cases {
x := maxProfitII(c.input)
if x != c.output {
t.Fail()
}
}
}
// submission codes start here
func maxProfitII(prices []int) int {
if len(prices) == 0 {
return 0
}
sum := 0
for i := 0; i < len(prices)-1; i++ {
if prices[i+1] > prices[i] {
sum += prices[i+1] - prices[i]
}
}
return sum
}
// submission codes end
|
package requests
import (
"fmt"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
)
// ListMultipleAssignmentsGradeableStudents A paginated list of students eligible to submit a list of assignments. The caller must have
// permission to view grades for the requested course.
//
// Section-limited instructors will only see students in their own sections.
// https://canvas.instructure.com/doc/api/submissions.html
//
// Path Parameters:
// # Path.CourseID (Required) ID
//
// Query Parameters:
// # Query.AssignmentIDs (Optional) Assignments being requested
//
type ListMultipleAssignmentsGradeableStudents struct {
Path struct {
CourseID string `json:"course_id" url:"course_id,omitempty"` // (Required)
} `json:"path"`
Query struct {
AssignmentIDs []string `json:"assignment_ids" url:"assignment_ids,omitempty"` // (Optional)
} `json:"query"`
}
func (t *ListMultipleAssignmentsGradeableStudents) GetMethod() string {
return "GET"
}
func (t *ListMultipleAssignmentsGradeableStudents) GetURLPath() string {
path := "courses/{course_id}/assignments/gradeable_students"
path = strings.ReplaceAll(path, "{course_id}", fmt.Sprintf("%v", t.Path.CourseID))
return path
}
func (t *ListMultipleAssignmentsGradeableStudents) GetQuery() (string, error) {
v, err := query.Values(t.Query)
if err != nil {
return "", err
}
return v.Encode(), nil
}
func (t *ListMultipleAssignmentsGradeableStudents) GetBody() (url.Values, error) {
return nil, nil
}
func (t *ListMultipleAssignmentsGradeableStudents) GetJSON() ([]byte, error) {
return nil, nil
}
func (t *ListMultipleAssignmentsGradeableStudents) HasErrors() error {
errs := []string{}
if t.Path.CourseID == "" {
errs = append(errs, "'Path.CourseID' is required")
}
if len(errs) > 0 {
return fmt.Errorf(strings.Join(errs, ", "))
}
return nil
}
func (t *ListMultipleAssignmentsGradeableStudents) Do(c *canvasapi.Canvas) error {
_, err := c.SendRequest(t)
if err != nil {
return err
}
return nil
}
|
package command
import (
"fmt"
"testing"
)
func TestCommands(t *testing.T) {
Add("test", test, "test function")
Add("test1", test1, "test1 function")
for _, c := range Commands {
c.Run()
}
}
func test() error {
fmt.Println("test run here")
return nil
}
func test1() error {
fmt.Println("test1 run here")
return nil
}
|
// use of big
// var distance int64 = 41.3e12 - use of exponential format in go
package main
import (
"fmt"
"math/big"
)
func main() {
ls := big.NewInt(299792)
scndsperday := big.NewInt(86400)
dist := new(big.Int)
// 24 quintillion. It won’t fit in an int64, so instead you can create a big.Int from a string:
// The number 24 quintillion is in base 10 (decimal), so the second argument is 10.
dist.SetString("24000000000000000000", 10)
fmt.Println("Galaxy is ", dist, "km away.")
scnds := new(big.Int)
scnds.Div(dist, ls)
days := new(big.Int)
days.Div(scnds, scndsperday)
fmt.Println("That is ", days, "of travel at light speed.")
}
// Galaxy is 24000000000000000000 km away.
// That is 926568346 of travel at light speed.
|
package database_test
import (
"os"
"testing"
"github.com/matthew-burr/db/database"
"github.com/matthew-burr/db/file"
"github.com/stretchr/testify/assert"
)
func SetupDBForTests() (db *database.DB, cleanup func()) {
db = database.Init("db_test")
cleanup = func() {
db.Shutdown()
os.Remove("db_test.dat")
}
return
}
func AssertEqualEntry(t *testing.T, want, got file.DBFileEntry) {
assert.Equal(t, want.Deleted(), got.Deleted())
assert.Equal(t, want.Key(), got.Key())
assert.Equal(t, want.Value(), got.Value())
}
func TestDelete_RemovesEntry(t *testing.T) {
db, cleanup := SetupDBForTests()
defer cleanup()
db.Write("hello", "world")
value := db.Read("hello").Value()
assert.Equal(t, "world", value)
db.Delete("hello")
value = db.Read("hello").Value()
assert.Equal(t, "<not found>", value)
}
func TestWrite_AddsEntryToFile(t *testing.T) {
db, c := SetupDBForTests()
defer c()
db.Write("hello", "there")
entry := db.DBFile.ReadEntry("hello")
assert.Equal(t, "hello", entry.Key())
assert.Equal(t, "there", entry.Value())
}
func TestWrite_ReturnsDBEntry(t *testing.T) {
db, c := SetupDBForTests()
defer c()
entry := db.Write("hello", "again")
assert.Equal(t, "hello", entry.Key())
assert.Equal(t, "again", entry.Value())
}
func TestRead_ReturnsEntry(t *testing.T) {
db, c := SetupDBForTests()
defer c()
db.Write("test", "me")
entry := db.Read("test")
AssertEqualEntry(t, file.NewEntry("test", file.Value("me")), entry)
}
func TestDelete_ReturnsDeletedEntry(t *testing.T) {
db, c := SetupDBForTests()
defer c()
db.Write("delete", "test")
got := db.Delete("delete")
want := file.NewEntry("delete", file.Deleted)
AssertEqualEntry(t, want, got)
}
|
package configutil_test
import (
"strings"
"testing"
"github.com/cerana/cerana/pkg/configutil"
"github.com/spf13/pflag"
"github.com/stretchr/testify/suite"
)
type ConfigUtil struct {
suite.Suite
}
func TestConfigUtil(t *testing.T) {
suite.Run(t, new(ConfigUtil))
}
func (s *ConfigUtil) TestNormalizeFunc() {
type testStruct struct {
input string
output string
}
tests := []testStruct{
{"foo", "foo"},
{"Foo", "foo"},
{"FOO", "FOO"},
{"fooBar", "fooBar"},
{"FooBar", "fooBar"},
{"fooBBar", "fooBBar"},
{" fooBar ", "fooBar"},
}
sets := []struct {
parts []string
output string
}{
{[]string{"foo", "bar"}, "fooBar"},
{[]string{"Foo", "bar"}, "fooBar"},
{[]string{"Foo", "Bar"}, "fooBar"},
{[]string{"fOo", "bAr"}, "fooBar"},
{[]string{"foo", "url"}, "fooURL"},
{[]string{"foo", "Url"}, "fooURL"},
{[]string{"foo", "uRl"}, "fooURL"},
{[]string{"foo", "URL"}, "fooURL"},
{[]string{"url", "foo"}, "urlFoo"},
{[]string{"foo", "cpu"}, "fooCPU"},
{[]string{"foo", "Cpu"}, "fooCPU"},
{[]string{"foo", "cPu"}, "fooCPU"},
{[]string{"foo", "CPU"}, "fooCPU"},
{[]string{"cpu", "foo"}, "cpuFoo"},
{[]string{"foo", "ip"}, "fooIP"},
{[]string{"foo", "Ip"}, "fooIP"},
{[]string{"foo", "iP"}, "fooIP"},
{[]string{"foo", "IP"}, "fooIP"},
{[]string{"ip", "foo"}, "ipFoo"},
{[]string{"foo", "id"}, "fooID"},
{[]string{"foo", "Id"}, "fooID"},
{[]string{"foo", "iD"}, "fooID"},
{[]string{"foo", "ID"}, "fooID"},
{[]string{"id", "foo"}, "idFoo"},
}
for _, sep := range []string{" ", ".", "_", "-", "--", "_-"} {
for _, set := range sets {
tests = append(tests, testStruct{strings.Join(set.parts, sep), set.output})
}
}
for _, test := range tests {
s.Equal(pflag.NormalizedName(test.output), configutil.NormalizeFunc(pflag.CommandLine, test.input), "'"+test.input+"'")
}
}
|
package array
// StringElementsMatch compares two arrays of strings irrespective of order.
func StringElementsMatch(one, two []string) bool {
if len(one) != len(two) {
return false
}
diff := make(map[string]bool)
for _, dim := range one {
diff[dim] = true
}
for _, dim := range two {
if !diff[dim] {
return false
}
}
return true
}
|
package azuretoken
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault"
"github.com/go-jose/go-jose/v3"
"github.com/sassoftware/relic/v7/config"
"github.com/sassoftware/relic/v7/lib/passprompt"
"github.com/sassoftware/relic/v7/lib/x509tools"
"github.com/sassoftware/relic/v7/token"
)
const tokenType = "azure"
type kvToken struct {
config *config.Config
tconf *config.TokenConfig
cli *keyvault.BaseClient
}
type kvKey struct {
kconf *config.KeyConfig
cli *keyvault.BaseClient
pub crypto.PublicKey
kbase string
kname string
kversion string
id []byte
cert []byte
}
func init() {
token.Openers[tokenType] = open
}
func open(conf *config.Config, tokenName string, pinProvider passprompt.PasswordGetter) (token.Token, error) {
tconf, err := conf.GetToken(tokenName)
if err != nil {
return nil, err
}
auth, err := newAuthorizer(tconf)
if err != nil {
return nil, fmt.Errorf("configuring azure auth: %w", err)
}
cli := keyvault.New()
cli.Authorizer = auth
return &kvToken{
config: conf,
tconf: tconf,
cli: &cli,
}, nil
}
func (t *kvToken) Close() error {
return nil
}
func (t *kvToken) Ping(ctx context.Context) error {
// query info for one of the keys in this token
for _, keyConf := range t.config.Keys {
if keyConf.Token != t.tconf.Name() || keyConf.Hide {
continue
}
ctx, cancel := context.WithTimeout(ctx, keyConf.GetTimeout())
defer cancel()
_, err := t.getKey(ctx, keyConf, true)
if err != nil {
return fmt.Errorf("checking key %q: %w", keyConf.Name(), err)
}
break
}
return nil
}
func (t *kvToken) Config() *config.TokenConfig {
return t.tconf
}
func (t *kvToken) GetKey(ctx context.Context, keyName string) (token.Key, error) {
keyConf, err := t.config.GetKey(keyName)
if err != nil {
return nil, err
}
return t.getKey(ctx, keyConf, false)
}
func (t *kvToken) getKey(ctx context.Context, keyConf *config.KeyConfig, pingOnly bool) (token.Key, error) {
words, baseURL, err := parseKeyURL(keyConf.ID)
if err != nil {
return nil, fmt.Errorf("key %q: %w", keyConf.Name(), err)
}
wantKeyID := token.KeyID(ctx)
var cert *certRef
switch {
case len(wantKeyID) != 0:
// reusing a key the client saw before
cert = refFromKeyID(wantKeyID)
if cert == nil {
return nil, errors.New("invalid keyID")
}
cert = &certRef{KeyName: words[0], KeyVersion: words[1]}
case len(words) == 4 && words[1] == "keys":
// directly to a key version, no cert provided
cert = &certRef{KeyName: words[2], KeyVersion: words[3]}
case len(words) == 4 && words[1] == "certificates":
// link to a cert version, get the key version and cert contents from it
cert, err = t.loadCertificateVersion(ctx, baseURL, words[2], words[3])
if err != nil {
return nil, fmt.Errorf("key %q: fetching certificate: %w", keyConf.Name(), err)
} else if pingOnly {
return nil, nil
}
case len(words) == 3 && words[1] == "certificates":
// link to a cert, pick the latest version
cert, err = t.loadCertificateLatest(ctx, baseURL, words[2])
if err != nil {
return nil, fmt.Errorf("key %q: fetching certificate: %w", keyConf.Name(), err)
} else if pingOnly {
return nil, nil
}
default:
return nil, fmt.Errorf("key %q: %w", keyConf.Name(), errKeyID)
}
key, err := t.cli.GetKey(ctx, baseURL, cert.KeyName, cert.KeyVersion)
if err != nil {
return nil, fmt.Errorf("key %q: %w", keyConf.Name(), err)
} else if pingOnly {
return nil, nil
}
// strip off -HSM suffix to get a key type jose will accept
kty := strings.TrimSuffix(string(key.Key.Kty), "-HSM")
key.Key.Kty = keyvault.JSONWebKeyType(kty)
// marshal back to JSON and then parse using jose to get a PublicKey
keyBlob, err := json.Marshal(key.Key)
if err != nil {
return nil, fmt.Errorf("marshaling public key: %w", err)
}
var jwk jose.JSONWebKey
if err := json.Unmarshal(keyBlob, &jwk); err != nil {
return nil, fmt.Errorf("unmarshaling public key: %w", err)
}
return &kvKey{
kconf: keyConf,
cli: t.cli,
pub: jwk.Key,
kbase: baseURL,
kname: cert.KeyName,
kversion: cert.KeyVersion,
cert: cert.CertBlob,
id: cert.KeyID(),
}, nil
}
func (t *kvToken) Import(keyName string, privKey crypto.PrivateKey) (token.Key, error) {
return nil, token.NotImplementedError{Op: "import-key", Type: tokenType}
}
func (t *kvToken) ImportCertificate(cert *x509.Certificate, labelBase string) error {
return token.NotImplementedError{Op: "import-certificate", Type: tokenType}
}
func (t *kvToken) Generate(keyName string, keyType token.KeyType, bits uint) (token.Key, error) {
return nil, token.NotImplementedError{Op: "generate-key", Type: tokenType}
}
func (t *kvToken) ListKeys(opts token.ListOptions) error {
return token.NotImplementedError{Op: "list-keys", Type: tokenType}
}
func (k *kvKey) Public() crypto.PublicKey {
return k.pub
}
func (k *kvKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
return k.SignContext(context.Background(), digest, opts)
}
func (k *kvKey) SignContext(ctx context.Context, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
alg, err := k.sigAlgorithm(opts)
if err != nil {
return nil, err
}
encoded := base64.RawURLEncoding.EncodeToString(digest)
kname, kversion := k.kname, k.kversion
if wantKeyID := token.KeyID(ctx); len(wantKeyID) != 0 {
// reusing a key the client saw before
cert := refFromKeyID(wantKeyID)
if cert == nil {
return nil, errors.New("invalid keyID")
}
kname, kversion = cert.KeyName, cert.KeyVersion
}
resp, err := k.cli.Sign(ctx, k.kbase, kname, kversion, keyvault.KeySignParameters{
Algorithm: keyvault.JSONWebKeySignatureAlgorithm(alg),
Value: &encoded,
})
if err != nil {
return nil, err
}
sig, err := base64.RawURLEncoding.DecodeString(*resp.Result)
if err != nil {
return nil, err
}
if _, ok := k.pub.(*ecdsa.PublicKey); ok {
// repack as ASN.1
unpacked, err := x509tools.UnpackEcdsaSignature(sig)
if err != nil {
return nil, err
}
sig = unpacked.Marshal()
}
return sig, nil
}
func (k *kvKey) Config() *config.KeyConfig { return k.kconf }
func (k *kvKey) Certificate() []byte { return k.cert }
func (k *kvKey) GetID() []byte { return k.id }
func (k *kvKey) ImportCertificate(cert *x509.Certificate) error {
return token.NotImplementedError{Op: "import-certificate", Type: tokenType}
}
// select a JOSE signature algorithm based on the public key algorithm and requested hash func
func (k *kvKey) sigAlgorithm(opts crypto.SignerOpts) (string, error) {
var alg string
switch opts.HashFunc() {
case crypto.SHA256:
alg = "256"
case crypto.SHA384:
alg = "384"
case crypto.SHA512:
alg = "512"
default:
return "", token.KeyUsageError{
Key: k.kconf.Name(),
Err: fmt.Errorf("unsupported digest algorithm %s", opts.HashFunc()),
}
}
switch k.pub.(type) {
case *rsa.PublicKey:
if _, ok := opts.(*rsa.PSSOptions); ok {
return "PS" + alg, nil
} else {
return "RS" + alg, nil
}
case *ecdsa.PublicKey:
return "ES" + alg, nil
default:
return "", token.KeyUsageError{
Key: k.kconf.Name(),
Err: fmt.Errorf("unsupported public key type %T", k.pub),
}
}
}
|
package cryptocore
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"github.com/transmutate-io/cryptocore/types"
)
type jsonRPCClient struct {
Address string
Username string
Password string
tlsConfig *TLSConfig
cachedTLSConfig *tls.Config
}
func newJsonRpcClient(addr, user, pass string, tlsConf *TLSConfig) (*jsonRPCClient, error) {
r := &jsonRPCClient{
Address: addr,
Username: user,
Password: pass,
}
if err := r.SetTLSConfig(tlsConf); err != nil {
return nil, err
}
return r, nil
}
func (c *jsonRPCClient) SetTLSConfig(cfg *TLSConfig) error {
c.tlsConfig = cfg
nc, err := c.newTLSConfig()
if err != nil {
return err
}
c.cachedTLSConfig = nc
return nil
}
func (c *jsonRPCClient) newTLSConfig() (*tls.Config, error) {
if c.tlsConfig == nil {
return nil, nil
}
tlsConf := &tls.Config{InsecureSkipVerify: c.tlsConfig.SkipVerify}
if c.tlsConfig.CA != "" {
b, err := ioutil.ReadFile(c.tlsConfig.CA)
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(b)
if err != nil {
return nil, err
}
rootCAs := x509.NewCertPool()
rootCAs.AddCert(cert)
tlsConf.RootCAs = rootCAs
}
if c.tlsConfig.ClientCertificate != "" && c.tlsConfig.ClientKey != "" {
cert, err := tls.LoadX509KeyPair(c.tlsConfig.ClientCertificate, c.tlsConfig.ClientKey)
if err != nil {
return nil, err
}
tlsConf.Certificates = append(tlsConf.Certificates, cert)
}
return tlsConf, nil
}
func clientURL(addr string, username string, password string, tlsConf *TLSConfig) string {
callURL := append(make([]string, 0, 16), "http")
if tlsConf != nil {
callURL = append(callURL, "s")
}
// use cached config
callURL = append(callURL, "://")
if username != "" {
callURL = append(callURL, username, ":", password, "@")
}
return strings.Join(append(callURL, addr, "/"), "")
}
func (c *jsonRPCClient) clientURL() string {
return clientURL(c.Address, c.Username, c.Password, c.tlsConfig)
}
func (c *jsonRPCClient) do(method string, params interface{}, r interface{}) error {
b := make([]byte, 0, 1024)
bb := bytes.NewBuffer(b)
err := json.NewEncoder(bb).Encode(&rpcRequest{
JsonRPC: "1.0",
ID: "go-cryptocore",
Method: method,
Params: params,
})
if err != nil {
return err
}
cl := &http.Client{Transport: &http.Transport{TLSClientConfig: c.cachedTLSConfig}}
resp, err := cl.Post(c.clientURL(), "application/json", bb)
if err != nil {
return err
}
defer resp.Body.Close()
rr := &rpcResponse{Result: r}
if err = json.NewDecoder(resp.Body).Decode(rr); err != nil {
return err
}
if rr.Error != nil {
return rr.Error
}
return nil
}
func (c *jsonRPCClient) doString(method string, args interface{}) (string, error) {
var r string
if err := c.do(method, args, &r); err != nil {
return "", err
}
return r, nil
}
func (c *jsonRPCClient) doUint64(method string, args interface{}) (uint64, error) {
var r uint64
if err := c.do(method, args, &r); err != nil {
return 0, err
}
return r, nil
}
func (c *jsonRPCClient) doBytes(method string, args interface{}) (types.Bytes, error) {
var r types.Bytes
if err := c.do(method, args, &r); err != nil {
return nil, err
}
return r, nil
}
func (c *jsonRPCClient) doSliceBytes(method string, args interface{}) ([]types.Bytes, error) {
var r []types.Bytes
if err := c.do(method, args, &r); err != nil {
return nil, err
}
return r, nil
}
type rpcRequest struct {
JsonRPC string `json:"jsonrpc"`
ID string `json:"id"`
Method string `json:"method"`
Params interface{} `json:"params"`
}
type rpcResponse struct {
ID string `json:"id"`
Error *ClientError `json:"error"`
Result interface{} `json:"result"`
}
type ClientError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (ce *ClientError) Error() string { return ce.Message }
|
package main
import (
"fmt"
"os"
"strconv"
)
// It's a example without recursive function
func not_recursive_3n1(f int) int {
var counter int = 1
for {
if f%2 == 0 {
f = f / 2
} else {
f = (f * 3) + 1
}
counter = counter + 1
// when f is equal to 1, program exit
if f == 1 {
break
}
}
return counter
}
func main() {
from, e := strconv.Atoi(os.Args[1])
to, e := strconv.Atoi(os.Args[2])
aux := from
if e != nil {
fmt.Println(e)
}
max_circle_lenght := 0
for aux <= to {
var circle_lenght int = not_recursive_3n1(aux)
if circle_lenght > max_circle_lenght {
max_circle_lenght = circle_lenght
}
aux = aux + 1
}
fmt.Println(from, to, max_circle_lenght)
}
|
package api
import (
"encoding/json"
"net/http"
"github.com/patrickoliveros/bookings/models"
)
var Articles []models.Article
func GetArticles(w http.ResponseWriter, r *http.Request) {
Articles = []models.Article{
{Title: "Hello", Desc: "Article Description 1", Content: "Article Content 1"},
{Title: "Hello 2", Desc: "Article Description 2", Content: "Article Content 2"},
}
json.NewEncoder(w).Encode(Articles)
}
|
package maps
type Rating struct {
// 1. Create a struct for storing CSV lines and annotate it with JSON struct field tags
Tconst string `json:"tconst"`
AverageRating string `json:"averageRating"`
NumVotes string `json:"numVotes"`
}
func CreateRatings(lines [][]string) []Rating {
// Loop through lines & turn into object
var ratings []Rating
for _, line := range lines {
data := Rating{
Tconst: line[0],
AverageRating: line[1],
NumVotes: line[2],
}
ratings = append(ratings, data)
}
return ratings
}
|
package main
import (
"fmt"
"os"
"github.com/gcla/gowid"
"github.com/gcla/gowid/widgets/list"
"github.com/gcla/gowid/widgets/pile"
"github.com/gcla/gowid/widgets/selectable"
"github.com/gcla/gowid/widgets/styled"
"github.com/gcla/gowid/widgets/text"
)
func main() {
palette := gowid.Palette{
"default": gowid.MakePaletteEntry(gowid.ColorWhite, gowid.ColorBlack),
"focus": gowid.MakePaletteEntry(gowid.ColorBlack, gowid.ColorGreen),
}
txt := text.New("")
stxt := styled.New(txt, gowid.MakePaletteRef("default"))
// text.Widget is not selectable.
// selectable.Widget makes non-selectable widget selectable.
// Selected item of the list can be changed by pressing Down, Up, Ctrl-N or Ctrl-P.
widgets := []gowid.IWidget{
styled.NewFocus(selectable.New(text.New("one")), gowid.MakePaletteRef("focus")),
styled.NewFocus(selectable.New(text.New("two")), gowid.MakePaletteRef("focus")),
styled.NewFocus(selectable.New(text.New("three")), gowid.MakePaletteRef("focus")),
}
lst := list.New(list.NewSimpleListWalker(widgets))
// This is called when selected item of the list is changed.
lst.OnFocusChanged(gowid.WidgetCallback{Name: "focus", WidgetChangedFunction: func(app gowid.IApp, widget gowid.IWidget) {
tw := widget.(*styled.Widget).SubWidget().(*selectable.Widget).SubWidget().(*text.Widget)
txt.SetContent(app, tw.Content())
}})
pl := pile.New([]gowid.IContainerWidget{
&gowid.ContainerWidget{IWidget: stxt, D: gowid.RenderFlow{}},
&gowid.ContainerWidget{IWidget: lst, D: gowid.RenderFlow{}},
})
app, err := gowid.NewApp(gowid.AppArgs{
View: pl,
Palette: palette,
})
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
app.SimpleMainLoop()
}
|
// +build !windows
package lib
// Defaults for linux/unix if none are specified
const (
conmonPath = "/usr/local/libexec/crio/conmon"
seccompProfilePath = "/etc/crio/seccomp.json"
cniConfigDir = "/etc/cni/net.d/"
cniBinDir = "/opt/cni/bin/"
lockPath = "/run/crio.lock"
containerExitsDir = "/var/run/crio/exits"
ContainerAttachSocketDir = "/var/run/crio"
)
|
package component
import "sync/atomic"
// Status indicates the health status of this component
type Status int
const (
// StatusHealthy indicates a healthy component
StatusHealthy Status = iota
// StatusUnhealthy indicates an unhealthy component
StatusUnhealthy
)
// GetStatus gets the health status of the component
func (c *Component) GetStatus() Status {
return Status(atomic.LoadInt64(&c.status))
}
// SetStatus sets the health status of the component
func (c *Component) SetStatus(status Status) {
atomic.StoreInt64(&c.status, int64(status))
}
|
// 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 ocr
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"chromiumos/tast/common/testexec"
"chromiumos/tast/local/printing/document"
"chromiumos/tast/shutil"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: GenerateSearchablePDFFromImage,
Desc: "Check that we can generate searchable PDF files from images",
Contacts: []string{"project-bolton@google.com"},
Attr: []string{"group:mainline", "informational"},
Data: []string{sourceImage, goldenPDF},
SoftwareDeps: []string{"ocr"},
})
}
const (
sourceImage = "phototest.tif"
goldenPDF = "phototest_golden.pdf"
)
// GenerateSearchablePDFFromImage runs the ocr_tool on a test image and compares
// the output PDF file with a golden file. It also dumps the output to a file
// for debugging.
func GenerateSearchablePDFFromImage(ctx context.Context, s *testing.State) {
tmpDir, err := ioutil.TempDir("", "tast.ocr.GenerateSearchablePDFFromImage.")
if err != nil {
s.Fatal("Failed to create temporary directory: ", err)
}
defer os.RemoveAll(tmpDir)
outputPDFPath := filepath.Join(tmpDir, "phototest.pdf")
cmd := testexec.CommandContext(ctx, "ocr_tool",
"--input_image_filename="+s.DataPath(sourceImage), "--output_pdf_filename="+outputPDFPath,
"--language=eng")
out, err := cmd.Output(testexec.DumpLogOnError)
if err != nil {
s.Fatalf("Failed to run %q: %v", shutil.EscapeSlice(cmd.Args), err)
}
// Log output to file for debugging.
path := filepath.Join(s.OutDir(), "command_output.txt")
if err := ioutil.WriteFile(path, out, 0644); err != nil {
s.Fatal("Failed to write output to ", path)
}
diffPath := filepath.Join(s.OutDir(), "diff.txt")
if err := document.CompareFiles(ctx, outputPDFPath, s.DataPath(goldenPDF), diffPath); err != nil {
s.Error("Generated PDF file differs from golden file: ", err)
}
}
|
package adapter
import (
"fmt"
"github.com/dustin/go-humanize"
"github.com/tidwall/gjson"
"github.com/zcong1993/badge-service/utils"
)
var defaultErrorResp = makeUnknownTopicInput("docker")
// VALID_TOPICS is valid topic docker api support
var VALID_TOPICS = []string{"stars", "pulls"}
// DockerApi is docker hub api provider
func DockerApi(args ...string) BadgeInput {
if len(args) != 3 {
return ErrorInput
}
topic := args[0]
namespace := args[1]
name := args[2]
if !utils.IsOneOf(VALID_TOPICS, topic) {
return defaultErrorResp
}
endpoint := fmt.Sprintf("https://hub.docker.com/v2/repositories/%s/%s", namespace, name)
resp, err := utils.Get(endpoint)
if err != nil {
return ErrorInput
}
pullCount := gjson.Get(string(resp), "pull_count").Float()
starCount := gjson.Get(string(resp), "star_count").Float()
switch topic {
case "stars":
return BadgeInput{
Subject: "docker stars",
Status: utils.StringOrDefault(humanize.SI(starCount, ""), "0"),
Color: "blue",
}
case "pulls":
return BadgeInput{
Subject: "docker pulls",
Status: utils.StringOrDefault(humanize.SI(pullCount, ""), "0"),
Color: "blue",
}
default:
return defaultErrorResp
}
}
|
package client
import (
"errors"
"fmt"
"math/rand"
"testing"
"time"
"github.com/mkocikowski/libkafka/api/Metadata"
)
func (c *PartitionClient) Kill() error { // implement io.Closer
c.Lock()
defer c.Unlock()
c.disconnect()
return nil
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func TestIntergationPartitionClientBadBootstrap(t *testing.T) {
bootstrap := "foo"
topic := fmt.Sprintf("test-%x", rand.Uint32()) // do not create
c := &PartitionClient{
Bootstrap: bootstrap,
Topic: topic,
Partition: 0,
}
_, err := c.ListOffsets(0)
if err == nil {
t.Fatal("expected 'dial tcp' error")
}
t.Log(err)
}
func TestIntergationPartitionClientTopicDoesNotExist(t *testing.T) {
bootstrap := "localhost:9092"
topic := fmt.Sprintf("test-%x", rand.Uint32()) // do not create
c := &PartitionClient{
Bootstrap: bootstrap,
Topic: topic,
Partition: 0,
}
_, err := c.ListOffsets(0)
if !errors.Is(err, ErrPartitionDoesNotExist) {
t.Fatal(err)
}
t.Log(err)
}
func TestUnitLeaderString(t *testing.T) {
b := &Metadata.Broker{Rack: "foo", NodeId: 1, Host: "bar", Port: 9092}
s := fmt.Sprintf("%v", b)
if s != "foo:1:bar:9092" {
t.Fatal(s)
}
}
|
package main
import (
"fmt"
"log"
"net/http"
"database/sql"
"github.com/adammohammed/groupmebot"
_ "github.com/mattn/go-sqlite3"
"regexp"
"strings"
)
/*
Test hook functions
Each hook should match a certain string, and if it matches
it should return a string of text
Hooks will be traversed until match occurs
*/
func hello(msg groupmebot.InboundMessage) string {
resp := fmt.Sprintf("Hi, %v.", msg.Name)
return resp
}
func hello2(msg groupmebot.InboundMessage) string {
resp := fmt.Sprintf("Hello, %v.", msg.Name)
return resp
}
func nameism(msg groupmebot.InboundMessage) string {
db, err := sql.Open("sqlite3", "messages.db")
if err != nil {
fmt.Println("FAILED TO GET DB")
return ""
}
defer db.Close()
re := regexp.MustCompile("(?P<name>[a-zA-Z]+)(i|I)(s|S)(m|M)")
match := re.FindStringSubmatch(msg.Text)
if len(match) > 0 {
name := strings.ToLower(match[1])
fmt.Printf("Looking for message from %s\n", name)
query := "SELECT Messages.text FROM Messages JOIN Users ON Messages.userid = Users.userid WHERE Users.name IS ? ORDER BY RANDOM() LIMIT 1;"
var randomMessage string
err = db.QueryRow(query, name).Scan(&randomMessage)
switch {
case err == sql.ErrNoRows:
return ""
case err != nil:
return ""
default:
return randomMessage
}
}
fmt.Println("FAILED TO GET MSG")
return ""
}
func main() {
csvLog := groupmebot.CSVLogger{"messages.csv"}
std := groupmebot.StdOutLogger{}
combinedLogger := groupmebot.CompositeLogger{Loggers: []groupmebot.Logger{csvLog, std}}
bot := groupmebot.GroupMeBot{Logger: combinedLogger}
err := bot.ConfigureFromJson("mybot_cfg.json")
if err != nil {
log.Fatal("Could not create bot structure")
}
// Make a list of functions
bot.AddHook("Hi!$", hello)
bot.AddHook("Hello!$", hello2)
bot.AddHook("([a-zA-Z]+)(i|I)(s|S)(m|M)", nameism)
// Create Server to listen for incoming POST from GroupMe
log.Printf("Listening on %v...\n", bot.Server)
http.HandleFunc("/", bot.Handler())
log.Fatal(http.ListenAndServe(bot.Server, nil))
}
|
package repowatch
import (
"context"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/Cloud-Foundations/golib/pkg/log"
"github.com/Cloud-Foundations/Dominator/lib/fsutil"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
xssh "golang.org/x/crypto/ssh"
)
func isHttpRepo(repoURL string) bool {
parsedURL, err := url.Parse(repoURL)
if err != nil {
return false
}
if strings.HasPrefix(parsedURL.Scheme, "http") {
return true
}
return false
}
// getAuth will return with a null authentication on http repositories, and
// for ssh repostories it tries to find an SSH authentication method.
// The ssh authenticaiton methods are AWS secrets manager, an SSH agent or
// local ssh keys.
func getAuth(ctx context.Context, repoURL string, secretsClient *secretsmanager.Client,
secretId string, logger log.DebugLogger) (transport.AuthMethod, error) {
if isHttpRepo(repoURL) {
// TODO: we actually want to fetch creds from AWS or other method
// for plain https creds.
return nil, nil
}
return getAuthSSH(ctx, secretsClient, secretId, logger)
}
// getAuthSSH tries to find an SSH authentication method.
// If secretId is specified, the SSH private key will be extracted from the
// specified AWS Secrets Manager secret object, otherwise an SSH agent or local
// keys will be tried.
func getAuthSSH(ctx context.Context, secretsClient *secretsmanager.Client,
secretId string, logger log.DebugLogger) (transport.AuthMethod, error) {
if secretId != "" {
return getAuthFromAWS(ctx, secretsClient, secretId, logger)
}
if os.Getenv("SSH_AUTH_SOCK") != "" {
if pkc, err := ssh.NewSSHAgentAuth(ssh.DefaultUsername); err != nil {
return nil, err
} else {
pkc.HostKeyCallbackHelper.HostKeyCallback =
xssh.InsecureIgnoreHostKey()
return pkc, nil
}
}
dirname := filepath.Join(os.Getenv("HOME"), ".ssh")
dirfile, err := os.Open(dirname)
if err != nil {
return nil, err
}
defer dirfile.Close()
names, err := dirfile.Readdirnames(-1)
if err != nil {
return nil, err
}
var lastError error
for _, name := range names {
if !strings.HasPrefix(name, "id_") {
continue
}
if strings.HasSuffix(name, ".pub") {
continue
}
pubkeys, err := getAuthFromFile(filepath.Join(dirname, name))
if err == nil {
return pubkeys, nil
}
lastError = err
}
if lastError != nil {
return nil, lastError
}
return nil, fmt.Errorf("no usable SSH keys found in: %s", dirname)
}
func getAuthFromAWS(ctx context.Context, secretsClient *secretsmanager.Client,
secretId string, logger log.DebugLogger) (
transport.AuthMethod, error) {
secrets, err := getAwsSecret(ctx, secretsClient, secretId)
if err != nil {
return nil, err
}
filename, err := writeSshKey(secrets)
if err != nil {
return nil, err
}
logger.Debugf(0,
"fetched SSH key from AWS Secrets Manager, SecretId: %s and wrote to: %s\n",
secretId, filename)
return getAuthFromFile(filename)
}
func getAuthFromFile(filename string) (transport.AuthMethod, error) {
pubkeys, err := ssh.NewPublicKeysFromFile(ssh.DefaultUsername, filename, "")
if err != nil {
return nil, err
}
pubkeys.HostKeyCallbackHelper.HostKeyCallback = xssh.InsecureIgnoreHostKey()
return pubkeys, nil
}
// keyMap is mutated.
func writeKeyAsPEM(writer io.Writer, keyMap map[string]string) error {
keyType := keyMap["KeyType"]
if keyType == "" {
return errors.New("no KeyType in map")
}
delete(keyMap, "KeyType")
privateKeyBase64 := keyMap["PrivateKey"]
if privateKeyBase64 == "" {
return errors.New("no PrivateKey in map")
}
delete(keyMap, "PrivateKey")
privateKey, err := base64.StdEncoding.DecodeString(
strings.Replace(privateKeyBase64, " ", "", -1))
if err != nil {
return err
}
block := &pem.Block{
Type: keyType + " PRIVATE KEY",
Headers: keyMap,
Bytes: privateKey,
}
return pem.Encode(writer, block)
}
// keyMap is mutated.
func writeSshKey(keyMap map[string]string) (string, error) {
dirname := filepath.Join(os.Getenv("HOME"), ".ssh")
if err := os.MkdirAll(dirname, 0700); err != nil {
return "", err
}
var filename string
switch keyType := keyMap["KeyType"]; keyType {
case "DSA":
filename = "id_dsa"
case "RSA":
filename = "id_rsa"
default:
return "", fmt.Errorf("unsupported key type: %s", keyType)
}
pathname := filepath.Join(dirname, filename)
writer, err := fsutil.CreateRenamingWriter(pathname,
fsutil.PrivateFilePerms)
if err != nil {
return "", err
}
if err := writeKeyAsPEM(writer, keyMap); err != nil {
writer.Abort()
return "", err
}
return pathname, writer.Close()
}
|
package battleship
import (
"strconv"
"strings"
)
type Location string
func (l Location) Row() int {
row := strings.Index("ABCDEFGHIJKLMNOPQRSTUVWXYZ", string(l[0:1]))
return row
}
func (l Location) Column() int {
column, _ := strconv.Atoi(string(l[1:]))
return (column - 1)
}
|
package db
import (
"time"
"github.com/gorilla/feeds"
)
func NewsletterToFeed(title string, archive []Newsletter) feeds.JSONFeed {
feed := feeds.JSONFeed{
Title: title,
Items: make([]*feeds.JSONItem, len(archive)),
}
for i, nl := range archive {
var date time.Time = nl.PublishedAt
feed.Items[i] = &feeds.JSONItem{
Id: nl.ArchiveURL,
Url: nl.ArchiveURL,
Title: nl.Subject,
PublishedDate: &date,
}
}
return feed
}
|
// +build ignore
// package level documents
package main
// test
import (
"encoding/json"
"fmt"
"github.com/fzerorubigd/onion"
"github.com/goraz/humanize"
)
const (
alpha = iota
beta
)
const (
x1 int = iota
y1
)
var maked = make([]int, 10)
var (
// Booogh
test, bogh /*doogh*/ string
)
// the hes var
var hes string
// Commet
type example struct {
p int `tag:"str"`
q string
}
// On both
type (
// On any
any int
// On Many
many int64
)
// On Pointer
type pointer *struct{}
// On x chan
type x chan string
// on zz
type zz *example
// on mappex
type mapex map[string]interface{}
// on slice
type slice []pointer
// on arr
type arr [10]int
// on testing
type testing interface {
Test(string) string
}
// The test is the test
func (m *example) Test(x string) (y string) {
y = x
return
}
type layer struct {
}
func (layer) Load() (map[string]interface{}, error) {
return nil, nil
}
func (layer) Error() string {
return ""
}
var o = onion.New()
var j, _ = AnnotatedOne("", 1, 1, 1, example{}, nil, nil)
var s func()
var alal onion.Layer
var js = 10
var im complex64
type testType int
var xxx = testType(10)
var yyy = onion.Layer(layer{})
var eee = error(layer{})
var pop = [...]int{1, 2, 6}
// Test
func main() {
p, err := humanize.ParsePackage("github.com/goraz/humanize/test")
if err != nil {
panic(err)
}
c, _ := json.MarshalIndent(p, "", "\t")
fmt.Print(string(c))
}
//AnnotatedOne is anotated one
// @Test is test dude "one liner"
func AnnotatedOne(p1 string, p2, p3 int, _ int, u example, i *example, j map[string]interface{}, ill ...int) (string, error) {
return "", nil
}
|
package main
import (
"fmt"
"time"
"gocv.io/x/gocv"
)
// MatBuffer is a matrix ring buffer, which stores the last frames added to it.
type MatBuffer struct {
imgs []*gocv.Mat
times []time.Time
writes int
}
// NewMatBuffer creates a new MatBuffer with enough frames to store the given
// duration at the given FPS.
func NewMatBuffer(duration time.Duration, fps float64) *MatBuffer {
frames := int(fps * duration.Seconds())
b := MatBuffer{
imgs: make([]*gocv.Mat, frames),
times: make([]time.Time, frames),
}
for i := range b.imgs {
m := gocv.NewMat()
b.imgs[i] = &m
}
return &b
}
// Close closes the buffer. A closed buffer can no longer be used.
func (b *MatBuffer) Close() error {
var err error
for _, img := range b.imgs {
if err == nil {
err = img.Close()
}
img.Close()
}
return err
}
// Add adds a new frame with the given timestamp to the buffer. If the buffer is
// full, the oldest frame is discarded.
func (b *MatBuffer) Add(img *gocv.Mat, t time.Time) {
i := b.writes % len(b.imgs)
img.CopyTo(b.imgs[i])
b.times[i] = t
b.writes++
}
// Duration returns the duration between the first and last frame added.
func (b *MatBuffer) Duration() time.Duration {
oldest, newest := b.TimeWindow()
return newest.Sub(oldest)
}
// Count returns the number of frames in the buffer.
func (b *MatBuffer) Count() int {
return len(b.imgs)
}
// TimeWindow returns the timestamps of the first and last frames added.
// If no frames were added, the zero-value times are returned for both.
func (b *MatBuffer) TimeWindow() (time.Time, time.Time) {
if b.writes == 0 {
return time.Time{}, time.Time{}
} else if b.writes <= len(b.imgs) {
return b.times[0], b.times[b.writes-1]
}
var (
first = b.writes % len(b.imgs)
last = (b.writes - 1 + len(b.imgs)) % len(b.imgs)
)
return b.times[first], b.times[last]
}
// FPS returns the average FPS of current contents of the buffer. Note that this
// may be different from the FPS with which the buffer was created.
func (b *MatBuffer) FPS() float64 {
if b.writes < 2 {
return 0
}
seconds := b.Duration().Seconds()
if b.writes < len(b.imgs) {
return float64(b.writes) / seconds
}
return float64(len(b.imgs)) / seconds
}
// Slice returns the buffer as a slice of matrices.
func (b *MatBuffer) Slice() []*gocv.Mat {
if b.writes <= len(b.imgs) {
return b.imgs[0:b.writes]
}
i := b.writes % len(b.imgs)
return append(b.imgs[i:], b.imgs[:i]...)
}
// WriteFile writes the buffer as a video to the specified filename, using the
// specified "FourCC" codec (e.g. "mp4v"), with the given video dimensions.
func (b *MatBuffer) WriteFile(filename, codec string) error {
imgs := b.Slice()
if len(imgs) < 2 {
return fmt.Errorf("need at least 2 frames")
}
var (
width = imgs[0].Cols()
height = imgs[0].Rows()
)
vw, err := gocv.VideoWriterFile(filename, codec, b.FPS(), width, height, true)
if err != nil {
return fmt.Errorf("opening writer failed: %w", err)
}
defer vw.Close()
for _, img := range imgs {
if img.Cols() != width || img.Rows() != height {
return fmt.Errorf("not all frames have the same dimensions")
}
if err := vw.Write(*img); err != nil {
return fmt.Errorf("writing image failed: %w", err)
}
}
return nil
}
|
package testing
import (
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
qsv1a1 "code.cloudfoundry.org/quarks-operator/pkg/kube/apis/quarkssecret/v1alpha1"
)
// DefaultQuarksSecret for use in tests
func (c *Catalog) DefaultQuarksSecret(name string) qsv1a1.QuarksSecret {
return qsv1a1.QuarksSecret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: qsv1a1.QuarksSecretSpec{
Type: "password",
SecretName: "generated-secret",
},
}
}
// CertificateQuarksSecret for use in tests, creates a certificate
func (c *Catalog) CertificateQuarksSecret(name string, secretref string, cacertref string, keyref string) qsv1a1.QuarksSecret {
return qsv1a1.QuarksSecret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: qsv1a1.QuarksSecretSpec{
SecretName: "generated-cert-secret",
Type: "certificate",
Request: qsv1a1.Request{
CertificateRequest: qsv1a1.CertificateRequest{
CommonName: "example.com",
CARef: qsv1a1.SecretReference{Name: secretref, Key: cacertref},
CAKeyRef: qsv1a1.SecretReference{Name: secretref, Key: keyref},
AlternativeNames: []string{"qux.com"},
},
},
},
}
}
// RotationConfig is a config map, which triggers secret rotation
func (c *Catalog) RotationConfig(name string) corev1.ConfigMap {
return corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "rotation-config1",
Labels: map[string]string{
qsv1a1.LabelSecretRotationTrigger: "yes",
},
},
Data: map[string]string{
qsv1a1.RotateQSecretListName: fmt.Sprintf(`["%s"]`, name),
},
}
}
|
package main
import (
"fmt"
m "math"
"github.com/MaxHalford/gago"
)
// DropWave minimum is -1 reached in (0, 0)
// Recommended search domain is [-5.12, 5.12]
func DropWave(X []float64) float64 {
numerator := 1 + m.Cos(12*m.Sqrt(m.Pow(X[0], 2)+m.Pow(X[1], 2)))
denominator := 0.5*(m.Pow(X[0], 2)+m.Pow(X[1], 2)) + 2
return -numerator / denominator
}
func main() {
// Instantiate a population
ga := gago.Default
// Fitness function
function := DropWave
// Number of variables the function takes as input
variables := 2
// Initialize the genetic algorithm
ga.Initialize(function, variables)
// Enhancement
for i := 0; i < 30; i++ {
fmt.Println(ga.Best)
ga.Enhance()
}
}
|
package graphql
//https://medium.com/@benbjohnson/standard-package-layout-7cdbc8391fc1
import (
"fmt"
"log"
ge "github.com/OIT-ads-web/graphql_endpoint"
"github.com/OIT-ads-web/graphql_endpoint/elastic"
"github.com/graphql-go/graphql"
ms "github.com/mitchellh/mapstructure"
)
func personResolver(params graphql.ResolveParams) (interface{}, error) {
id := params.Args["id"].(string)
log.Printf("looking for person %s\n", id)
person, err := elastic.FindPerson(id)
return person, err
}
func publicationResolver(params graphql.ResolveParams) (interface{}, error) {
id := params.Args["id"].(string)
log.Printf("looking for publication %s\n", id)
person, err := elastic.FindPublication(id)
return person, err
}
func grantResolver(params graphql.ResolveParams) (interface{}, error) {
id := params.Args["id"].(string)
log.Printf("looking for grant %s\n", id)
person, err := elastic.FindGrant(id)
return person, err
}
// NOTE: this duplicates structure here:
// var PersonFilter *graphql.InputObject
// not sure best way to go about this
type CommonFilter struct {
Limit int
Offset int
Query string
}
// NOTE: these aren't different now, but dealing with
// facets would probably make them different
type PersonFilterParam struct {
Filter CommonFilter
}
type PublicationFilterParam struct {
Filter CommonFilter
}
type GrantFilterParam struct {
Filter CommonFilter
}
func convertPeopleFilter(params graphql.ResolveParams) (PersonFilterParam, error) {
result := PersonFilterParam{
Filter: CommonFilter{Limit: 100, Offset: 0, Query: ""},
}
err := ms.Decode(params.Args, &result)
return result, err
}
func convertPublicationFilter(params graphql.ResolveParams) (PublicationFilterParam, error) {
// default values?
result := PublicationFilterParam{
Filter: CommonFilter{Limit: 100, Offset: 0, Query: ""},
}
err := ms.Decode(params.Args, &result)
return result, err
}
func convertGrantFilter(params graphql.ResolveParams) (GrantFilterParam, error) {
// default values?
result := GrantFilterParam{
Filter: CommonFilter{Limit: 100, Offset: 0, Query: ""},
}
err := ms.Decode(params.Args, &result)
return result, err
}
func peopleResolver(params graphql.ResolveParams) (interface{}, error) {
// TODO: not finding a good way to default these
// e.g. if filter is not sent at all
limit := 100
offset := 0
query := ""
filter, err := convertPeopleFilter(params)
if err == nil {
limit = filter.Filter.Limit
offset = filter.Filter.Offset
// NOTE: this is not that great
query = fmt.Sprintf("*:%v*", filter.Filter.Query)
}
fmt.Printf("limit=%v,offset=%v,query=%v\n", limit, offset, query)
personList, err := elastic.FindPeople(limit, offset, query)
return personList, err
}
func publicationsResolver(params graphql.ResolveParams) (interface{}, error) {
// TODO: not finding a good way to default these
limit := 100
offset := 0
query := ""
filter, err := convertPublicationFilter(params)
if err == nil {
limit = filter.Filter.Limit
offset = filter.Filter.Offset
query = fmt.Sprintf("*:%v*", filter.Filter.Query)
}
publications, err := elastic.FindPublications(limit, offset, query)
return publications, err
}
func personPublicationResolver(params graphql.ResolveParams) (interface{}, error) {
person, _ := params.Source.(ge.Person)
limit := params.Args["limit"].(int)
offset := params.Args["offset"].(int)
publicationList, err := elastic.FindPersonPublications(person.Id, limit, offset)
return func() (interface{}, error) {
return &publicationList, err
}, nil
}
func grantsResolver(params graphql.ResolveParams) (interface{}, error) {
limit := 100
offset := 0
query := ""
filter, err := convertGrantFilter(params)
if err == nil {
limit = filter.Filter.Limit
offset = filter.Filter.Offset
query = fmt.Sprintf("*:%v*", filter.Filter.Query)
}
grants, err := elastic.FindGrants(limit, offset, query)
return grants, err
}
func personGrantResolver(params graphql.ResolveParams) (interface{}, error) {
person, _ := params.Source.(ge.Person)
limit := params.Args["limit"].(int)
offset := params.Args["offset"].(int)
grants, err := elastic.FindPersonGrants(person.Id, limit, offset)
return func() (interface{}, error) {
return &grants, err
}, nil
}
|
package dht
import (
"errors"
"os"
"time"
"github.com/google/logger"
)
const (
bootstrapTimeOut = 3 * time.Second
minNodeNum = 10
)
var (
dhtLogger *logger.Logger
defaultBootNode []*node
)
func init() {
dhtLogger = logger.Init("DHT", false, false, os.Stdout)
bootNodes := []string{
"router.bittorrent.com:6881",
"router.utorrent.com:6881",
"router.bitcomet.com:6881",
}
defaultBootNode = make([]*node, 0, len(bootNodes))
for _, n := range bootNodes {
n, err := newNode(newNodeID(), n)
if err == nil {
defaultBootNode = append(defaultBootNode, n)
}
}
}
//DHT is Distributed Hash Table, see https://en.wikipedia.org/wiki/Distributed_hash_table
type DHT struct {
own *node
table *table
bootNode []*node
rawNodeC chan *node
nodeCh chan *node
msgCh chan []byte
stopC chan chan error
reqC chan peerRequest
}
//NewDHT DHT create a DHT instance
func NewDHT(m string, nodes []*node, bootNode []string) (*DHT, error) {
var err error
d := &DHT{
rawNodeC: make(chan *node),
nodeCh: make(chan *node),
msgCh: make(chan []byte),
stopC: make(chan chan error),
reqC: make(chan peerRequest),
}
d.bootNode = defaultBootNode
d.own, err = newNode(newNodeID(), m)
if err != nil {
return nil, err
}
d.table = newTable(d.own)
for _, boot := range bootNode {
for _, n := range defaultBootNode {
if boot == n.addr {
continue
}
}
n, err := newNode(newNodeID(), boot)
if err != nil {
return nil, err
}
d.bootNode = append(d.bootNode, n)
}
if d.bootNode == nil {
d.bootNode = defaultBootNode
}
for _, n := range nodes {
d.addNode(n)
}
d.bootstrap()
return d, nil
}
func (d *DHT) bootstrap() {
if d.table.count >= minNodeNum {
return
}
for _, n := range d.bootNode {
ns, err := n.findNode(&d.own.id, &d.own.id)
if err != nil {
dhtLogger.Warningf("find node from %v, err: %v", n.addr, err)
continue
}
dhtLogger.Infof("get %v node from %v", len(ns), n.addr)
for _, n := range ns {
d.addNode(n)
}
}
}
type peerRequest struct {
infoHash [20]byte
peers chan []string
}
//Run start a DHT instance
func (d *DHT) Run() {
var err error
for {
select {
case n := <-d.rawNodeC:
go func() {
err := n.ping(&d.own.id)
if err != nil {
dhtLogger.Warning("check node fail, err:", err)
return
}
d.nodeCh <- n
}()
case n := <-d.nodeCh:
if n != nil {
d.table.addNode(n)
}
case req := <-d.reqC:
go d.getPeers(req)
case errC := <-d.stopC:
errC <- err
}
}
}
func (d *DHT) getPeers(req peerRequest) {
var f func(n *node) error
//stop the recrusion?
f = func(n *node) error {
if n == nil {
return errors.New("emptyt node")
}
peers, nodes, token, err := n.getPeers(&d.own.id, req.infoHash)
if err != nil {
return err
}
if len(peers) != 0 {
req.peers <- peers
n.announcePeer(d.own, req.infoHash, token)
}
if len(nodes) != 0 {
// d.nodeCh <- nodes
for _, n := range nodes {
d.nodeCh <- n
f(n)
}
}
return nil
}
d.table.foreach(f)
}
func (d *DHT) addNode(n *node) error {
go func() {
err := n.ping(&d.own.id)
dhtLogger.Infof("ping %v, result:%v", n.addr, err)
if err == nil {
d.rawNodeC <- n
}
}()
return nil
}
//GetPeers query peers from DHT by infohash
func (d *DHT) GetPeers(infoHash [20]byte, peerC chan []string) {
d.reqC <- peerRequest{infoHash, peerC}
}
//AddNode add node addr to DHT
func (d *DHT) AddNode(addrs []string) {
nodes := []*node{}
for _, addr := range addrs {
n, err := newNode(newNodeID(), addr)
if err != nil {
return
}
nodes = append(nodes, n)
}
for _, n := range nodes {
d.nodeCh <- n
}
}
|
package main
import "sort"
func p12917(s string) string {
a := []byte(s)
sort.Slice(a, func(i, j int) bool {
return a[i] > a[j]
})
return string(a)
}
|
package space
// Planet ...
type Planet string
// PlanetMap ...
var PlanetMap = make(map[Planet]float64)
const earthSecond = 31557600
func setData() {
PlanetMap["Mercury"] = 0.2408467
PlanetMap["Venus"] = 0.61519726
PlanetMap["Mars"] = 1.8808158
PlanetMap["Jupiter"] = 11.862615
PlanetMap["Saturn"] = 29.447498
PlanetMap["Uranus"] = 84.016846
PlanetMap["Neptune"] = 164.79132
}
// Age ...
func Age(s float64, p Planet) float64 {
setData()
o := s / earthSecond
if u, ok := PlanetMap[p]; ok {
return o / u
}
return o
}
|
package main
import (
"os"
"github.com/rzyns/gogen/cli"
)
func main() {
code := cli.Main(os.Args)
os.Exit(code)
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package cryptohome
import (
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
uda "chromiumos/system_api/user_data_auth_proto"
"chromiumos/tast/common/hwsec"
"chromiumos/tast/errors"
)
/*
This file implements miscellaneous and unsorted helpers.
*/
// ExpectAuthIntents checks whether two given sets of intents are equal, and
// in case they're not returns an error containing the formatted difference.
func ExpectAuthIntents(intents, expectedIntents []uda.AuthIntent) error {
less := func(a, b uda.AuthIntent) bool { return a < b }
diff := cmp.Diff(intents, expectedIntents, cmpopts.SortSlices(less))
if diff == "" {
return nil
}
return errors.New(diff)
}
// ExpectContainsAuthIntent checks whether the intents set contains the given value.
func ExpectContainsAuthIntent(intents []uda.AuthIntent, expectedIntent uda.AuthIntent) error {
for _, intent := range intents {
if intent == expectedIntent {
return nil
}
}
return errors.Errorf("expected to contain %v, got %v", expectedIntent, intents)
}
// ExpectAuthFactorTypes checks whether two given sets of types are equal, and
// in case they're not returns an error containing the formatted difference.
func ExpectAuthFactorTypes(types, expectedTypes []uda.AuthFactorType) error {
less := func(a, b uda.AuthFactorType) bool { return a < b }
diff := cmp.Diff(types, expectedTypes, cmpopts.SortSlices(less))
if diff == "" {
return nil
}
return errors.New(diff)
}
// ExpectAuthFactorsWithTypeAndLabel checks whether AuthFactorWithStatus proto
// contains expected AuthFactors, looking only at the types and labels of the
// factors. If they are not equal then this returns an error containing the
// formatted difference.
func ExpectAuthFactorsWithTypeAndLabel(factors, expectedFactors []*uda.AuthFactorWithStatus) error {
eq := func(a, b *uda.AuthFactorWithStatus) bool {
return a.AuthFactor.Type == b.AuthFactor.Type && a.AuthFactor.Label == b.AuthFactor.Label
}
less := func(a, b *uda.AuthFactorWithStatus) bool {
return a.AuthFactor.Type < b.AuthFactor.Type || (a.AuthFactor.Type == b.AuthFactor.Type && a.AuthFactor.Label < b.AuthFactor.Label)
}
diff := cmp.Diff(factors, expectedFactors, cmp.Comparer(eq), cmpopts.SortSlices(less))
if diff == "" {
return nil
}
return errors.New(diff)
}
// ExpectCryptohomeErrorCode checks whether the specified error `err` has the
// exit error code equal to the specified `code`.
func ExpectCryptohomeErrorCode(err error, code uda.CryptohomeErrorCode) error {
var exitErr *hwsec.CmdExitError
if !errors.As(err, &exitErr) {
return errors.Errorf("unexpected error: got %q; want *hwsec.CmdExitError", err)
}
if exitErr.ExitCode != int(code) {
return errors.Errorf("unexpected exit code: got %d; want %d", exitErr.ExitCode, code)
}
return nil
}
|
package tiltfile
import (
"context"
"strings"
"testing"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/tilt-dev/tilt/pkg/apis"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/google/go-cmp/cmp"
"github.com/moby/buildkit/frontend/dockerfile/dockerignore"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/api/equality"
"github.com/tilt-dev/tilt/internal/container"
"github.com/tilt-dev/tilt/internal/controllers/fake"
"github.com/tilt-dev/tilt/internal/k8s/testyaml"
"github.com/tilt-dev/tilt/internal/store"
"github.com/tilt-dev/tilt/internal/testutils"
"github.com/tilt-dev/tilt/internal/testutils/manifestbuilder"
"github.com/tilt-dev/tilt/internal/testutils/tempdir"
"github.com/tilt-dev/tilt/pkg/model"
)
func TestFileWatch_basic(t *testing.T) {
f := newFWFixture(t)
target := model.LocalTarget{
Name: "foo",
Deps: []string{"."},
}
f.SetManifestLocalTarget(target)
f.RequireFileWatchSpecEqual(target.ID(), v1alpha1.FileWatchSpec{WatchedPaths: []string{"."}})
}
func TestFileWatch_disabledOnCIMode(t *testing.T) {
f := newFWFixture(t)
f.inputs.EngineMode = store.EngineModeCI
target := model.LocalTarget{
Name: "foo",
Deps: []string{"."},
}
f.SetManifestLocalTarget(target)
m := model.Manifest{Name: "foo"}.WithDeployTarget(target)
f.SetManifest(m)
actualSet := ToFileWatchObjects(f.inputs, make(disableSourceMap))
assert.Empty(t, actualSet)
}
func TestFileWatch_IgnoreOutputsImageRefs(t *testing.T) {
f := newFWFixture(t)
target := model.MustNewImageTarget(container.MustParseSelector("img")).
WithBuildDetails(model.CustomBuild{
CmdImageSpec: v1alpha1.CmdImageSpec{OutputsImageRefTo: f.JoinPath("ref.txt")},
Deps: []string{f.Path()},
})
m := manifestbuilder.New(f, "sancho").
WithK8sYAML(testyaml.SanchoYAML).
WithImageTarget(target).
Build()
f.SetManifest(m)
f.RequireFileWatchSpecEqual(target.ID(), v1alpha1.FileWatchSpec{
WatchedPaths: []string{f.Path()},
Ignores: []v1alpha1.IgnoreDef{
{BasePath: f.Path(), Patterns: []string{"ref.txt"}},
},
})
}
func TestFileWatch_ConfigFiles(t *testing.T) {
f := newFWFixture(t)
f.SetTiltIgnoreContents("**/foo")
f.inputs.ConfigFiles = append(f.inputs.ConfigFiles, "path_to_watch", "stop")
id := model.TargetID{Type: model.TargetTypeConfigs, Name: model.TargetName(model.MainTiltfileManifestName)}
f.RequireFileWatchSpecEqual(id, v1alpha1.FileWatchSpec{
WatchedPaths: []string{"path_to_watch", "stop"},
Ignores: []v1alpha1.IgnoreDef{
{BasePath: f.Path(), Patterns: []string{"**/foo"}},
},
})
}
func TestFileWatch_IgnoreTiltIgnore(t *testing.T) {
f := newFWFixture(t)
target := model.LocalTarget{
Name: "foo",
Deps: []string{"."},
}
f.SetManifestLocalTarget(target)
f.SetTiltIgnoreContents("**/foo")
f.RequireFileWatchSpecEqual(target.ID(), v1alpha1.FileWatchSpec{
WatchedPaths: []string{"."},
Ignores: []v1alpha1.IgnoreDef{
{BasePath: f.Path(), Patterns: []string{"**/foo"}},
},
})
}
func TestFileWatch_IgnoreWatchSettings(t *testing.T) {
f := newFWFixture(t)
target := model.LocalTarget{
Name: "foo",
Deps: []string{"."},
}
f.SetManifestLocalTarget(target)
f.inputs.WatchSettings.Ignores = append(f.inputs.WatchSettings.Ignores, model.Dockerignore{
LocalPath: f.Path(),
Patterns: []string{"**/foo"},
})
f.RequireFileWatchSpecEqual(target.ID(), v1alpha1.FileWatchSpec{
WatchedPaths: []string{"."},
Ignores: []v1alpha1.IgnoreDef{
{BasePath: f.Path(), Patterns: []string{"**/foo"}},
},
})
}
func TestFileWatch_PickUpTiltIgnoreChanges(t *testing.T) {
f := newFWFixture(t)
target := model.LocalTarget{
Name: "foo",
Deps: []string{"."},
}
f.SetManifestLocalTarget(target)
f.SetTiltIgnoreContents("**/foo")
f.RequireFileWatchSpecEqual(target.ID(), v1alpha1.FileWatchSpec{
WatchedPaths: []string{"."},
Ignores: []v1alpha1.IgnoreDef{
{BasePath: f.Path(), Patterns: []string{"**/foo"}},
},
})
f.SetTiltIgnoreContents("**foo\n!bar/baz/foo")
f.RequireFileWatchSpecEqual(target.ID(), v1alpha1.FileWatchSpec{
WatchedPaths: []string{"."},
Ignores: []v1alpha1.IgnoreDef{
{BasePath: f.Path(), Patterns: []string{"**foo", "!bar/baz/foo"}},
},
})
}
type fwFixture struct {
t testing.TB
ctx context.Context
cli ctrlclient.Client
*tempdir.TempDirFixture
inputs WatchInputs
}
func newFWFixture(t *testing.T) *fwFixture {
cli := fake.NewFakeTiltClient()
ctx, _, _ := testutils.CtxAndAnalyticsForTest()
ctx, cancel := context.WithCancel(ctx)
tmpdir := tempdir.NewTempDirFixture(t)
tmpdir.Chdir()
f := &fwFixture{
t: t,
ctx: ctx,
cli: cli,
TempDirFixture: tmpdir,
inputs: WatchInputs{TiltfileManifestName: model.MainTiltfileManifestName},
}
t.Cleanup(func() {
cancel()
})
return f
}
type fileWatchDiffer struct {
expected v1alpha1.FileWatchSpec
actual v1alpha1.FileWatchSpec
}
func (f fileWatchDiffer) String() string {
return cmp.Diff(f.expected, f.actual)
}
func (f *fwFixture) RequireFileWatchSpecEqual(targetID model.TargetID, spec v1alpha1.FileWatchSpec) {
f.t.Helper()
actualSet := ToFileWatchObjects(f.inputs, make(disableSourceMap))
actual, ok := actualSet[apis.SanitizeName(targetID.String())]
require.True(f.T(), ok, "No filewatch found for %s", targetID)
fwd := &fileWatchDiffer{expected: spec, actual: actual.GetSpec().(v1alpha1.FileWatchSpec)}
require.True(f.T(), equality.Semantic.DeepEqual(actual.GetSpec(), spec), "FileWatch spec was not equal: %v", fwd)
}
func (f *fwFixture) SetManifestLocalTarget(target model.LocalTarget) {
m := model.Manifest{Name: "foo"}.WithDeployTarget(target)
f.SetManifest(m)
}
func (f *fwFixture) SetManifest(m model.Manifest) {
for i, original := range f.inputs.Manifests {
if original.Name == m.Name {
f.inputs.Manifests[i] = m
return
}
}
f.inputs.Manifests = append(f.inputs.Manifests, m)
}
func (f *fwFixture) SetTiltIgnoreContents(s string) {
patterns, err := dockerignore.ReadAll(strings.NewReader(s))
assert.NoError(f.T(), err)
f.inputs.Tiltignore = model.Dockerignore{
LocalPath: f.Path(),
Patterns: patterns,
}
}
|
package tests
import (
"testing"
)
/**
* [797] Rabbits in Forest
*
* In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.
*
* Return the minimum number of rabbits that could be in the forest.
*
*
* Examples:
* Input: answers = [1, 1, 2]
* Output: 5
* Explanation:
* The two rabbits that answered "1" could both be the same color, say red.
* The rabbit than answered "2" can't be red or the answers would be inconsistent.
* Say the rabbit that answered "2" was blue.
* Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
* The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
*
* Input: answers = [10, 10, 10]
* Output: 11
*
* Input: answers = []
* Output: 0
*
*
* Note:
*
*
* answers will have length at most 1000.
* Each answers[i] will be an integer in the range [0, 999].
*
*
*/
func TestRabbitsinForest(t *testing.T) {
var cases = []struct {
input []int
output int
}{
{
input: []int{1, 1, 2},
output: 5,
},
{
input: []int{10, 10, 10},
output: 11,
},
{
input: []int{},
output: 0,
},
{
input: []int{1, 0, 1, 0, 0},
output: 5,
},
{
input: []int{0, 0, 1, 1, 1},
output: 6,
},
{
input: []int{2, 1, 2, 2, 2, 2, 2, 2, 1, 1},
output: 13,
},
}
for _, c := range cases {
x := numRabbits(c.input)
if x != c.output {
t.Fail()
}
}
}
// submission codes start here
func numRabbits(answers []int) int {
if len(answers) == 0 {
return 0
}
res := 0
m := make(map[int]int)
for _, v := range answers {
if v == 0 {
res += 1
} else {
if _, ok := m[v]; !ok {
m[v] = 1
res += v + 1
} else {
m[v] += 1
if m[v] > v+1 {
m[v] = 1
res += v + 1
}
}
}
}
return res
}
// submission codes end
|
// Copyright 2012 Joe Wass. All rights reserved.
// Use of this source code is governed by the MIT license
// which can be found in the LICENSE file.
// MIDI package
// A package for reading Standard Midi Files, written in Go.
// Joe Wass 2012
// joe@afandian.com
// Constants and values.
package midi
// SMF format
const (
SingleMultiTrackChannel = 0
SimultaneousTracks = 1
SequentialTracks = 2
)
// Time code formats used in HeaderData.TimeFormat
const (
MetricalTimeFormat = iota
TimeCodeTimeFormat = iota
)
// Supplied to KeySignature
const (
MajorMode = 0
MinorMode = 1
)
type KeySignatureMode uint8
const (
DegreeC = 0
DegreeCs = 1
DegreeDf = DegreeCs
DegreeD = 2
DegreeDs = 3
DegreeEf = DegreeDs
DegreeE = 4
DegreeF = 5
DegreeFs = 6
DegreeGf = DegreeFs
DegreeG = 7
DegreeGs = 8
DegreeAf = DegreeGs
DegreeA = 9
DegreeAs = 10
DegreeBf = DegreeAs
DegreeB = 11
DegreeCf = DegreeB
)
type ScaleDegree uint8
|
package main
import (
"github.com/micro/go-micro"
rpc "github.com/micro/go-plugins/micro/disable_rpc"
"github.com/micro/go-plugins/micro/metrics"
"github.com/micro/micro/cmd"
"github.com/micro/micro/plugin"
"github.com/paitime/gateway/plugins/gzip"
)
func init() {
plugin.Register(gzip.NewPlugin())
plugin.Register(metrics.NewPlugin())
plugin.Register(rpc.NewPlugin())
}
func main() {
cmd.Init(
micro.Name("cn.paitime.api"),
)
}
|
package repository
import (
"context"
"github.com/sapawarga/userpost-service/model"
)
type PostI interface {
// query for get userpost
GetListPost(ctx context.Context, request *model.UserPostRequest) ([]*model.PostResponse, error)
GetMetadataPost(ctx context.Context, request *model.UserPostRequest) (*int64, error)
GetListPostByMe(ctx context.Context, request *model.UserPostByMeRequest) ([]*model.PostResponse, error)
GetMetadataPostByMe(ctx context.Context, request *model.UserPostByMeRequest) (*int64, error)
GetActor(ctx context.Context, id int64) (*model.UserResponse, error)
GetDetailPost(ctx context.Context, id int64) (*model.PostResponse, error)
CheckIsExistLikeOnPostBy(ctx context.Context, request *model.AddOrRemoveLikeOnPostRequest) (bool, error)
CheckHealthReadiness(ctx context.Context) error
// query for create
InsertPost(ctx context.Context, request *model.CreateNewPostRequestRepository) error
AddLikeOnPost(ctx context.Context, request *model.AddOrRemoveLikeOnPostRequest) error
// query for update
UpdateDetailOfUserPost(ctx context.Context, request *model.UpdatePostRequest) error
// query for delete
RemoveLikeOnPost(ctx context.Context, request *model.AddOrRemoveLikeOnPostRequest) error
}
type CommentI interface {
GetLastComment(ctx context.Context, id int64) (*model.CommentResponse, error)
GetTotalComments(ctx context.Context, userPostID int64) (*int64, error)
GetCommentsByPostID(ctx context.Context, req *model.GetComment) ([]*model.CommentResponse, error)
Create(ctx context.Context, req *model.CreateCommentRequestRepository) (int64, error)
}
|
package main
import (
"HeeloBeego/db_mysql"
_ "HeeloBeego/routers"
"github.com/astaxie/beego"
_ "github.com/go-sql-driver/msyql"
)
func main() {
db_mysql.OpenDB()
defer db_mysql.Db.Close()
beego.Run()
}
|
package httputils
import (
"encoding/json"
"fmt"
"net"
"net/http"
)
// **** Request handler ****
type RequestHandler struct {
getRemoteHostAddress func(r *http.Request) string
Method string
Handler func(remoteHostAddress string, params *json.RawMessage) (bool, error)
}
// Should be used if there is no reverse proxy i.e. address is not changed
func DefaultHostAddressExtractor(r *http.Request) string {
host, _, _ := net.SplitHostPort(r.RemoteAddr)
return host
}
func sendResponse(w http.ResponseWriter, success bool, message string) {
w.Header().Set("Content-Type", "application/json")
response := ServerResponseMessage{Success: success, Message: message}
json.NewEncoder(w).Encode(response)
}
func (rh *RequestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Every path has a mathod
if r.Method != rh.Method {
sendResponse(w, false, "Not a valid HTTP method for given path")
return
}
// Lets get all params required for the handler
var command json.RawMessage
jsonParser := json.NewDecoder(r.Body)
jsonParser.Decode(&command)
remoteHostAddress := rh.getRemoteHostAddress(r)
// Invoke handler and reply to host based on the response
success, err := rh.Handler(remoteHostAddress, &command)
if err != nil {
sendResponse(w, false, err.Error())
return
}
if success {
sendResponse(w, true, "Success")
} else {
sendResponse(w, false, "Failed executing command")
}
}
// **** Request multiplexer *****
type RequestMultiplexer struct {
mux *http.ServeMux
hostAddrExtractor func(r *http.Request) string
}
func (rm *RequestMultiplexer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rm.mux.ServeHTTP(w, r)
}
func (rm *RequestMultiplexer) RegisterHandler(path string, method string,
rh func(string, *json.RawMessage) (bool, error),
) {
rm.mux.Handle(path, &RequestHandler{
getRemoteHostAddress: rm.hostAddrExtractor,
Method: method,
Handler: rh,
})
}
func (rh *RequestMultiplexer) StartHttpServer(port string) *http.Server {
addr := fmt.Sprint(":", port)
h := &http.Server{Addr: addr, Handler: rh}
go func() {
if err := h.ListenAndServe(); err != nil {
fmt.Println(err)
}
}()
return h
}
func CreateHttpRequestMultiplexer(hostAddressExtractor func(r *http.Request) string) *RequestMultiplexer {
rh := &RequestMultiplexer{
mux: http.NewServeMux(),
hostAddrExtractor: hostAddressExtractor,
}
return rh
}
|
package main
func main() {
//panic("call panic")
//死锁
//死锁(Deadlock)就是一个进程拿着资源A请求资源B,
//另一个进程拿着资源B请求资源A,双方都不释放自己的资源,导致两个进程都进行不下去。
ch := make(chan int)
<-ch
}
|
package menu
import (
"github.com/kenshaw/envcfg"
"github.com/sirupsen/logrus"
)
// Methode is the methode type
type Method int
const (
// List of different Methods
Get Method = iota
POST
other
)
// Server is the server object for this api service.
type Server struct {
config *envcfg.Envcfg
logger *logrus.Logger
}
//RetrieveRequest
type RetrieveRequest struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `'json:"desc"'`
}
//RetrieveRequest
type RetrieveResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `'json:"desc"'`
}
// New creates a new server.
func New(config *envcfg.Envcfg, logger *logrus.Logger) *Server {
return &Server{
config: config,
logger: logger,
}
}
|
// Copyright 2018 xgfone
//
// 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 ship
import (
"bytes"
"context"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"sync"
"syscall"
"github.com/xgfone/ship/router/echo"
"github.com/xgfone/ship/utils"
)
// Router stands for a router management.
type Router interface {
// Generate a URL by the url name and parameters.
URL(name string, params ...interface{}) string
// Add a route with name, path, method and handler,
// and return the number of the parameters if there are the parameters
// in the route. Or return 0.
//
// If the name has been added for the same path, it should be allowed.
// Or it should panic.
//
// If the router does not support the parameter, it should panic.
//
// Notice: for keeping consistent, the parameter should start with ":"
// or "*". ":" stands for a single parameter, and "*" stands for
// a wildcard parameter.
Add(name string, path string, method string, handler interface{}) (paramNum int)
// Find a route handler by the method and path of the request.
//
// Return nil if the route does not exist.
//
// If the route has more than one parameter, the name and value
// of the parameters should be stored `pnames` and `pvalues` respectively.
Find(method string, path string, pnames []string, pvalues []string) (handler interface{})
// Traverse each route.
Each(func(name string, method string, path string))
}
// Resetter is an Reset interface.
type Resetter interface {
Reset()
}
type stopT struct {
once sync.Once
f func()
}
func (s *stopT) run() {
s.once.Do(s.f)
}
var defaultSignals = []os.Signal{
os.Interrupt,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGABRT,
syscall.SIGINT,
}
var defaultMethodMapping = map[string]string{
"Create": "POST",
"Delete": "DELETE",
"Update": "PUT",
"Get": "GET",
}
// Ship is an app to be used to manage the router.
type Ship struct {
/// Configuration Options
name string
debug bool
prefix string
logger Logger
binder Binder
session Session
renderer Renderer
signals []os.Signal
bufferSize int
ctxDataSize int
middlewareMaxNum int
enableCtxHTTPContext bool
keepTrailingSlashPath bool
defaultMethodMapping map[string]string
notFoundHandler Handler
optionsHandler Handler
methodNotAllowedHandler Handler
isDefaultRouter bool
disableErrorLog bool
newRouter func() Router
newCtxData func(*Context) Resetter
handleError func(*Context, error)
ctxHandler func(*Context, ...interface{}) error
bindQuery func(interface{}, url.Values) error
/// Inner settings
ctxpool sync.Pool
bufpool utils.BufferPool
maxNum int
router Router
handler Handler
premiddlewares []Middleware
middlewares []Middleware
links []*Ship
vhosts map[string]*Ship
server *http.Server
stopfs []*stopT
once1 sync.Once // For shutdown
once2 sync.Once // For stop
done chan struct{}
lock sync.RWMutex
connState func(net.Conn, http.ConnState)
}
// New returns a new Ship.
func New(options ...Option) *Ship {
s := new(Ship)
/// Initialize the default configuration.
s.logger = NewNoLevelLogger(os.Stderr)
s.session = NewMemorySession()
s.signals = defaultSignals
mb := NewMuxBinder()
mb.Add(MIMEApplicationJSON, JSONBinder())
mb.Add(MIMETextXML, XMLBinder())
mb.Add(MIMEApplicationXML, XMLBinder())
mb.Add(MIMEMultipartForm, FormBinder())
mb.Add(MIMEApplicationForm, FormBinder())
s.binder = mb
mr := NewMuxRenderer()
mr.Add("json", JSONRenderer())
mr.Add("jsonpretty", JSONPrettyRenderer(" "))
mr.Add("xml", XMLRenderer())
mr.Add("xmlpretty", XMLPrettyRenderer(" "))
s.renderer = mr
s.bufferSize = 2048
s.middlewareMaxNum = 256
s.defaultMethodMapping = defaultMethodMapping
s.notFoundHandler = NotFoundHandler()
s.handleError = s.handleErrorDefault
s.bindQuery = func(v interface{}, d url.Values) error {
return BindURLValues(v, d, "query")
}
s.newRouter = s.defaultNewRouter
s.isDefaultRouter = true
/// Initialize the inner variables.
s.ctxpool.New = func() interface{} { return s.NewContext(nil, nil) }
s.bufpool = utils.NewBufferPool(s.bufferSize)
s.router = s.newRouter()
s.handler = s.handleRequestRoute
s.vhosts = make(map[string]*Ship)
s.done = make(chan struct{}, 1)
return s.Configure(options...)
}
func (s *Ship) defaultNewRouter() Router {
var handleMethodNotAllowed, handleOptions func([]string) interface{}
if s.methodNotAllowedHandler != nil {
handleMethodNotAllowed = toRouterHandler(s.methodNotAllowedHandler)
}
if s.optionsHandler != nil {
handleOptions = toRouterHandler(s.optionsHandler)
}
return echo.NewRouter(handleMethodNotAllowed, handleOptions)
}
func (s *Ship) clone() *Ship {
newShip := Ship{
// Configurations
name: s.name,
debug: s.debug,
prefix: s.prefix,
logger: s.logger,
binder: s.binder,
session: s.session,
renderer: s.renderer,
signals: s.signals,
bufferSize: s.bufferSize,
ctxDataSize: s.ctxDataSize,
middlewareMaxNum: s.middlewareMaxNum,
keepTrailingSlashPath: s.keepTrailingSlashPath,
defaultMethodMapping: s.defaultMethodMapping,
notFoundHandler: s.notFoundHandler,
optionsHandler: s.optionsHandler,
methodNotAllowedHandler: s.methodNotAllowedHandler,
isDefaultRouter: s.isDefaultRouter,
newRouter: s.newRouter,
newCtxData: s.newCtxData,
handleError: s.handleError,
ctxHandler: s.ctxHandler,
bindQuery: s.bindQuery,
// Inner variables
bufpool: utils.NewBufferPool(s.bufferSize),
router: s.newRouter(),
handler: s.handleRequestRoute,
vhosts: make(map[string]*Ship),
done: make(chan struct{}, 1),
}
newShip.ctxpool.New = func() interface{} { return newShip.NewContext(nil, nil) }
return &newShip
}
func (s *Ship) setURLParamNum(num int) {
if num > s.maxNum {
s.maxNum = num
}
}
// Configure configures the Ship.
//
// Notice: the method must be called before starting the http server.
func (s *Ship) Configure(options ...Option) *Ship {
s.lock.RLock()
defer s.lock.RUnlock()
if s.server != nil {
panic(fmt.Errorf("the http server has been started"))
}
for _, opt := range options {
opt(s)
}
return s
}
// Clone returns a new Ship router with a new name by the current configuration.
//
// Notice: the new router will disable the signals and register the shutdown
// function into the parent Ship router.
func (s *Ship) Clone(name ...string) *Ship {
newShip := s.clone()
newShip.signals = []os.Signal{}
if len(name) > 0 && name[0] != "" {
newShip.name = name[0]
}
s.RegisterOnShutdown(newShip.shutdown)
return newShip
}
// VHost returns a new ship used to manage the virtual host.
//
// For the different virtual host, you can register the same route.
//
// Notice: the new virtual host won't inherit anything except the configuration.
func (s *Ship) VHost(host string) *Ship {
if s.vhosts == nil {
panic(fmt.Errorf("the virtual host cannot create the virtual host"))
}
if s.vhosts[host] != nil {
panic(fmt.Errorf("the virtual host '%s' has been added", host))
}
vhost := s.clone()
vhost.vhosts = nil
s.vhosts[host] = vhost
return vhost
}
// Link links other to the current router, that's, only if either of the two
// routers is shutdown, another is also shutdown.
//
// Return the current router.
func (s *Ship) Link(other *Ship) *Ship {
// Avoid to add each other repeatedly.
for i := range s.links {
if other == s.links[i] {
return s
}
}
s.links = append(s.links, other)
other.links = append(other.links, s)
return s
}
// NewContext news and returns a Context.
func (s *Ship) NewContext(r *http.Request, w http.ResponseWriter) *Context {
return newContext(s, r, w, s.maxNum)
}
// AcquireContext gets a Context from the pool.
func (s *Ship) AcquireContext(r *http.Request, w http.ResponseWriter) *Context {
c := s.ctxpool.Get().(*Context)
c.setReqResp(r, w)
return c
}
// ReleaseContext puts a Context into the pool.
func (s *Ship) ReleaseContext(c *Context) {
if c != nil {
c.reset()
s.ctxpool.Put(c)
}
}
// AcquireBuffer gets a Buffer from the pool.
func (s *Ship) AcquireBuffer() *bytes.Buffer {
return s.bufpool.Get()
}
// ReleaseBuffer puts a Buffer into the pool.
func (s *Ship) ReleaseBuffer(buf *bytes.Buffer) {
s.bufpool.Put(buf)
}
// Logger returns the inner Logger
func (s *Ship) Logger() Logger {
return s.logger
}
// Renderer returns the inner Renderer.
func (s *Ship) Renderer() Renderer {
return s.renderer
}
// MuxRenderer check whether the inner Renderer is MuxRenderer.
//
// If yes, return it as "*MuxRenderer"; or return nil.
func (s *Ship) MuxRenderer() *MuxRenderer {
if mr, ok := s.renderer.(*MuxRenderer); ok {
return mr
}
return nil
}
// Binder returns the inner Binder.
func (s *Ship) Binder() Binder {
return s.binder
}
// MuxBinder check whether the inner Binder is MuxBinder.
//
// If yes, return it as "*MuxBinder"; or return nil.
func (s *Ship) MuxBinder() *MuxBinder {
if mb, ok := s.binder.(*MuxBinder); ok {
return mb
}
return nil
}
// Pre registers the Pre-middlewares, which are executed before finding the route.
// then returns the origin ship router to write the chained router.
func (s *Ship) Pre(middlewares ...Middleware) *Ship {
s.premiddlewares = append(s.premiddlewares, middlewares...)
handler := s.handleRequestRoute
for i := len(s.premiddlewares) - 1; i >= 0; i-- {
handler = s.premiddlewares[i](handler)
}
s.handler = handler
return s
}
// Use registers the global middlewares and returns the origin ship router
// to write the chained router.
func (s *Ship) Use(middlewares ...Middleware) *Ship {
s.middlewares = append(s.middlewares, middlewares...)
return s
}
// Group returns a new sub-group.
func (s *Ship) Group(prefix string, middlewares ...Middleware) *Group {
ms := make([]Middleware, 0, len(s.middlewares)+len(middlewares))
ms = append(ms, s.middlewares...)
ms = append(ms, middlewares...)
return newGroup(s, s.router, s.prefix, prefix, ms...)
}
// GroupWithoutMiddleware is the same as Group, but not inherit the middlewares of Ship.
func (s *Ship) GroupWithoutMiddleware(prefix string, middlewares ...Middleware) *Group {
ms := make([]Middleware, 0, len(middlewares))
ms = append(ms, middlewares...)
return newGroup(s, s.router, s.prefix, prefix, ms...)
}
// RouteWithoutMiddleware is the same as Route, but not inherit the middlewares of Ship.
func (s *Ship) RouteWithoutMiddleware(path string) *Route {
return newRoute(s, s.router, s.prefix, path)
}
// Route returns a new route, then you can customize and register it.
//
// You must call Route.Method() or its short method.
func (s *Ship) Route(path string) *Route {
return newRoute(s, s.router, s.prefix, path, s.middlewares...)
}
// R is short for Ship#Route(path).
func (s *Ship) R(path string) *Route {
return s.Route(path)
}
// Router returns the inner Router.
func (s *Ship) Router() Router {
return s.router
}
// URL generates an URL from route name and provided parameters.
func (s *Ship) URL(name string, params ...interface{}) string {
return s.router.URL(name, params...)
}
// Traverse traverses the registered route.
func (s *Ship) Traverse(f func(name string, method string, path string)) {
s.router.Each(f)
}
// ServeHTTP implements the interface http.Handler.
func (s *Ship) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if s.vhosts != nil {
if vhost := s.vhosts[r.Host]; vhost != nil {
vhost.serveHTTP(w, r)
return
}
}
s.serveHTTP(w, r)
}
func (s *Ship) handleRequestRoute(c *Context) error {
if h := c.findHandler(c.req.Method, c.req.URL.Path); h != nil {
return h(c)
}
return c.NotFoundHandler()(c)
}
func (s *Ship) serveHTTP(w http.ResponseWriter, r *http.Request) {
ctx := s.AcquireContext(r, w)
ctx.router = s.router
err := s.handler(ctx)
if err == nil {
err = ctx.Err
}
if err != nil {
s.handleError(ctx, err)
}
s.ReleaseContext(ctx)
}
func (s *Ship) handleErrorDefault(ctx *Context, err error) {
switch err {
case nil, ErrSkip:
return
}
if !ctx.IsResponded() {
switch e := err.(type) {
case HTTPError:
if e.Code < 500 {
if e.Msg == "" {
if e.Err == nil {
ctx.Blob(e.Code, e.CT, nil)
} else {
ctx.Blob(e.Code, e.CT, []byte(e.Err.Error()))
}
} else if e.Err == nil {
ctx.Blob(e.Code, e.CT, []byte(e.Msg))
} else {
ctx.Blob(e.Code, e.CT, []byte(fmt.Sprintf("msg='%s', err='%s'", e.Msg, e.Err)))
}
return
}
ctx.Blob(e.Code, e.CT, []byte(e.Msg))
default:
ctx.NoContent(http.StatusInternalServerError)
goto END
}
}
END:
if !s.disableErrorLog {
s.logger.Error("%s", err)
}
}
// Shutdown stops the HTTP server.
func (s *Ship) Shutdown(ctx context.Context) error {
s.lock.RLock()
server := s.server
s.lock.RUnlock()
if server == nil {
return fmt.Errorf("the server has not been started")
}
return server.Shutdown(ctx)
}
// RegisterOnShutdown registers some functions to run when the http server is
// shut down.
func (s *Ship) RegisterOnShutdown(functions ...func()) *Ship {
s.lock.Lock()
for _, f := range functions {
s.stopfs = append(s.stopfs, &stopT{once: sync.Once{}, f: f})
}
s.lock.Unlock()
return s
}
// SetConnStateHandler sets a handler to monitor the change of the connection
// state, which is used by the HTTP server.
func (s *Ship) SetConnStateHandler(h func(net.Conn, http.ConnState)) *Ship {
s.lock.Lock()
s.connState = h
s.lock.Unlock()
return s
}
// Start starts a HTTP server with addr.
//
// If tlsFile is not nil, it must be certFile and keyFile. That's,
//
// router := ship.New()
// rouetr.Start(addr, certFile, keyFile)
//
func (s *Ship) Start(addr string, tlsFiles ...string) *Ship {
var cert, key string
if len(tlsFiles) == 2 && tlsFiles[0] != "" && tlsFiles[1] != "" {
cert = tlsFiles[0]
key = tlsFiles[1]
}
s.startServer(&http.Server{Addr: addr}, cert, key)
return s
}
// StartServer starts a HTTP server.
func (s *Ship) StartServer(server *http.Server) {
s.startServer(server, "", "")
}
func (s *Ship) handleSignals(sigs ...os.Signal) {
ss := make(chan os.Signal, 1)
signal.Notify(ss, sigs...)
for {
<-ss
s.shutdown()
return
}
}
func (s *Ship) runStop() {
s.lock.RLock()
defer s.lock.RUnlock()
defer close(s.done)
for _len := len(s.stopfs) - 1; _len >= 0; _len-- {
if r := s.stopfs[_len]; r != nil {
r.run()
}
}
}
func (s *Ship) stop() {
s.once2.Do(s.runStop)
}
func (s *Ship) shutdown() {
s.once1.Do(func() { s.Shutdown(context.Background()) })
}
func (s *Ship) startServer(server *http.Server, certFile, keyFile string) {
defer s.shutdown()
if s.vhosts == nil {
s.logger.Error("forbid the virtual host to be started as a server")
return
}
server.ErrorLog = log.New(s.logger.Writer(), "",
log.LstdFlags|log.Lmicroseconds|log.Lshortfile)
if server.Handler == nil {
server.Handler = s
}
// Handle the signal
if len(s.signals) > 0 {
go s.handleSignals(s.signals...)
}
for _, r := range s.links {
s.RegisterOnShutdown(r.shutdown)
r.RegisterOnShutdown(s.shutdown)
}
server.RegisterOnShutdown(s.stop)
if server.ConnState == nil && s.connState != nil {
server.ConnState = s.connState
}
var format string
if s.name == "" {
format = "The HTTP Server is shutdown"
s.logger.Info("The HTTP Server is running on %s", server.Addr)
} else {
format = fmt.Sprintf("The HTTP Server [%s] is shutdown", s.name)
s.logger.Info("The HTTP Server [%s] is running on %s",
s.name, server.Addr)
}
s.lock.Lock()
if s.server != nil {
s.logger.Error(format + ": the server has been started")
return
}
s.server = server
s.lock.Unlock()
var err error
s.RegisterOnShutdown(func() {
if err == nil || err == http.ErrServerClosed {
s.logger.Info(format)
} else {
s.logger.Error(format+": %s", err)
}
})
if certFile != "" && keyFile != "" {
err = server.ListenAndServeTLS(certFile, keyFile)
} else {
err = server.ListenAndServe()
}
}
// Wait waits until all the registered shutdown functions have finished.
func (s *Ship) Wait() {
<-s.done
}
|
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
)
// GetSpecificAttributeOfUserReader is a Reader for the GetSpecificAttributeOfUser structure.
type GetSpecificAttributeOfUserReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the recieved o.
func (o *GetSpecificAttributeOfUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetSpecificAttributeOfUserOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("unknown error", response, response.Code())
}
}
// NewGetSpecificAttributeOfUserOK creates a GetSpecificAttributeOfUserOK with default headers values
func NewGetSpecificAttributeOfUserOK() *GetSpecificAttributeOfUserOK {
return &GetSpecificAttributeOfUserOK{}
}
/*GetSpecificAttributeOfUserOK handles this case with default header values.
GetSpecificAttributeOfUserOK get specific attribute of user o k
*/
type GetSpecificAttributeOfUserOK struct {
}
func (o *GetSpecificAttributeOfUserOK) Error() string {
return fmt.Sprintf("[GET /{name}/attributes/{attrName}][%d] getSpecificAttributeOfUserOK ", 200)
}
func (o *GetSpecificAttributeOfUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
|
package multipartfile
import (
"mime/multipart"
)
type MultipartFile struct {
multipart.File
Header *multipart.FileHeader
}
func (m MultipartFile) Name() string {
if m.Header == nil {
return ""
}
return m.Header.Filename
}
|
package cmd
import (
"context"
"github.com/geospace/sac"
"github.com/machinebox/graphql"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
// DeleteTokenM : query for mutation `deleteToken`
var DeleteTokenM = `
mutation($token: String) {
deleteToken(token: $token)
}
`
// DeleteTokenR : response struct for mutation `deleteToken`
type DeleteTokenR struct {
DeleteToken bool `json:"deleteToken"`
}
func createLogoutCmd(sacYML *sac.Sac) *cobra.Command {
return &cobra.Command{
Use: "logout",
Short: "Logs you out from dessert.",
PreRun: func(cmd *cobra.Command, args []string) {
Logger.Info(logLoggingYouOut)
},
PostRun: func(cmd *cobra.Command, args []string) {
Logger.Info(logOutSuccess)
},
RunE: func(cmd *cobra.Command, args []string) error {
if err := sacYML.ReadConfig(dessertYML); err != nil {
return err
}
if err := logout(sacYML); err != nil {
return errors.Wrap(err, errLoggingOut)
}
return nil
},
}
}
func logout(sacYML *sac.Sac) error {
token := sacYML.GetString("token")
if token == "" {
Logger.Info("already logged out")
return nil
}
client := initClient()
var respData DeleteTokenR
req := graphql.NewRequest(DeleteTokenM)
ctx := context.Background()
req.Var("token", token)
if err := client.Run(ctx, req, &respData); err != nil {
return err
}
if !respData.DeleteToken {
return errors.New(errBadServerResp)
}
// removing token from dessert_config.yml
sacYML.Set("token", "")
return sacYML.WriteConfig()
}
|
package xml2map
import (
"testing"
"strings"
)
func BenchmarkEncode(b *testing.B) {
for n := 0; n < b.N; n++ {
NewEncoder(strings.NewReader(`<container uid="FA6666D9-EC9F-4DA3-9C3D-4B2460A4E1F6" lifetime="2019-10-10T18:00:11">
<cats>
<cat>
<id>CDA035B6-D453-4A17-B090-84295AE2DEC5</id>
<name>moritz</name>
<age>7</age>
<items>
<n>1293</n>
<n>1255</n>
<n>1257</n>
</items>
</cat>
<cat>
<id>1634C644-975F-4302-8336-1EF1366EC6A4</id>
<name>oliver</name>
<age>12</age>
</cat>
</cats>
<color>white</color>
<city>NY</city>
</container>`)).Encode()
}
} |
package goutil
import "testing"
import "fmt"
func TestPrintStrEle(t *testing.T) {
cases := []string{
"string",
"hello",
}
for _, str := range cases {
count := PrintStrEle(str)
if count == len(str) {
fmt.Println("test %s ok", str)
} else {
t.Errorf("test %s error for %d, excepted %d ", str, count, len(str))
}
}
}
|
package main
import (
"fmt"
"github.com/mutao-net/go-weather/weather"
)
func main() {
result := weather.GetWeather("XXXXXX", "35.4660694", "139.6226196")
// fmt.Printf("result: %+v\n", result)
fmt.Println(result.Current.Feelslike)
for _, value := range result.Current.Weather {
fmt.Println(value.Description)
}
}
|
package main
import (
"github.com/jessevdk/go-flags"
"log"
"os"
)
func main() {
os.Exit(run())
}
func run() int {
var options struct{}
var parser = flags.NewParser(&options, flags.Default)
if _, err := parser.AddCommand("new", "Create a new memo", "", &NewCommand{}); err != nil {
log.Fatal(err)
}
if _, err := parser.AddCommand("version", "Show version", "", &VersionCommand{}); err != nil {
log.Fatal(err)
}
if _, err := parser.Parse(); err != nil {
switch err.(type) {
case *flags.Error:
fe, _ := err.(*flags.Error)
if fe.Type == flags.ErrHelp {
return 0
}
return 1
default:
return 1
}
}
return 0
}
|
package verify
import (
"reflect"
"testing"
)
// --- Helpers ---
func expect(t *testing.T, a interface{}, b interface{}) {
if a != b {
t.Errorf(
"Expected %v (type %v) - Got %v (type %v)",
b,
reflect.TypeOf(b),
a,
reflect.TypeOf(a),
)
}
}
func refute(t *testing.T, a interface{}, b interface{}) {
if a == b {
t.Errorf(
"Did not expect %v (type %v) - Got %v (type %v)",
b,
reflect.TypeOf(b),
a,
reflect.TypeOf(a),
)
}
}
// --- End helpers ---
func Test_Verify(t *testing.T) {
v := Verify(validEmail)
refute(t, v, nil)
expect(t, v.Query, validEmail)
}
|
package main
import (
"errors"
"log"
"regexp"
"strconv"
"strings"
)
var TypeMap map[string]string = map[string]string{
"other": "string",
"token": "string",
"dateTime": "string",
"duration": "string",
"time": "string",
"anyURI": "string",
"base64Binary": "[]byte",
"string": "string",
"boolean": "bool",
"float": "float64", //32
"double": "float64",
"decimal": "float64",
"int": "int64", //32
"long": "int64",
}
var SubstituteMap map[string]string = map[string]string{
"int32": "NullInt64",
"int64": "NullInt64",
"string": "NullString",
"float32": "NullFloat64",
"float64": "NullFloat64",
"bool": "NullBool",
}
var NullableType map[string]bool = map[string]bool{
"[]byte": true,
"string": true,
"time.Time": true,
"NullInt64": true,
"NullString": true,
"NullFloat64": true,
"NullBool": true,
}
var SliceableType map[string]string = map[string]string{
"NullString": "NullStringList",
"NullInt64": "NullInt64List",
"NullFloat64": "NullFloat64List",
}
type Type string
func (e Type) Nullable() bool {
if v, k := NullableType[e.GoType()]; k {
return v
}
s, ok := FindSimple(e.String())
if ok {
if v, k := NullableType[s.Restriction.Base.GoType()]; k {
return v
}
}
return false
}
func (e Type) IsRequest() bool {
return strings.HasSuffix(string(e), "RequestType")
}
func (e Type) IsBasic() bool {
if _, k := TypeMap[e.String()]; k {
return true
}
return false
}
func (e Type) IsNS() bool {
if strings.Contains(string(e), ":") {
return strings.SplitAfterN(string(e), ":", 2)[0] != "xs:"
}
return e[:3] == "ns:"
}
func (e Type) IsXS() bool {
if len(string(e)) < 4 {
panic(string(e))
}
return e[:3] == "xs:"
}
func (e Type) IsSimpleType() bool {
if e.IsXS() {
return false
}
_, ok := FindSimple(e.String())
return ok
}
func (e Type) IsComplexType() bool {
if e.IsXS() {
return false
}
_, ok := FindComplex(e.String())
return ok
}
func (e Type) String() string {
if strings.Contains(string(e), ":") {
return strings.SplitAfterN(string(e), ":", 2)[1]
}
return string(e)
}
func (s Type) GoType(noSub ...bool) string {
if !s.IsXS() {
return s.String()
}
t := ""
k := false
if t, k = TypeMap[s.String()]; !k {
log.Fatal("could not find go type for ", s.String())
}
if len(noSub) == 0 {
if tSub, k := SubstituteMap[t]; k {
t = tSub
}
}
return t
}
type schema struct {
attributeFormDefault string `xml:"attributeFormDefault,attr"`
BlockDefault string `xml:"blockDefault,attr"`
ElementFormDefault string `xml:"elementFormDefault,attr"`
FinalDefault string `xml:"finalDefault,attr"`
Id string `xml:"id,attr"`
TargetNamespace string `xml:"targetNamespace,attr"`
Xmlns string `xml:"xmlns,attr"`
Version string `xml:"version,attr"`
XmlLang string `xml:"lang,attr"`
//Include []includeMany `xml:"include"`
//Import []importMany `xml:"import"`
Annotation annotation `xml:"annotation"`
//redefine
Attribute []attribute `xml:"attribute"`
//attributeGroup
Element []element `xml:"element"`
//group
//notation
SimpleType []simpleType `xml:"simpleType"`
ComplexType []complexType `xml:"complexType"`
}
type element struct {
// Abstract string `xml:"abstract,attr"`
// Block string `xml:"block,attr"`
// Default string `xml:"default,attr"`
// SubstitutionGroup string `xml:"substitutionGroup,attr"`
// Final string `xml:"final,attr"`
// Fixed string `xml:"fixed,attr"`
// Form string `xml:"form,attr"`
// ID string `xml:"id,attr"`
MaxOccurs string `xml:"maxOccurs,attr"`
MinOccurs string `xml:"minOccurs,attr"`
Name string `xml:"name,attr"`
Nillable bool `xml:"nillable,attr"`
// Ref string `xml:"ref,attr"`
Type Type `xml:"type,attr"`
Annotation *annotation `xml:"annotation"`
SimpleType *simpleType `xml:"simpleType"`
ComplexType *complexType `xml:"complexType"`
//key
//keyref
//unique
}
func (e element) SliceLen() (int, bool) {
if strings.Contains(string(e.Type), "base64Binary") {
return 0, true
}
if e.MaxOccurs == "" {
return 0, false
}
if e.MaxOccurs == "unbounded" {
return 0, true
}
mo, err := strconv.Atoi(e.MaxOccurs)
if err != nil {
log.Fatal(err)
}
return mo, mo > 1
}
// https://msdn.microsoft.com/en-us/library/ms256067(v=vs.110).aspx
// Number of occurrences: Unlimited within schema; one time within element.
type complexType struct {
Abstract bool `xml:"abstract,attr"`
// Block string `xml:"block,attr"`
// Final string `xml:"final,attr"`
// ID string `xml:"id,attr"`
// Mixed string `xml:"mixed,attr"`
Name string `xml:"name,attr"`
Annotation annotation `xml:"annotation"`
// The complex type has character data or a simpleType as content and contains no elements, but may contain attributes.
SimpleContent *simpleContent `xml:"simpleContent"`
// The complex type contains only elements or no element content (empty).
ComplexContent *complexContent `xml:"complexContent"`
//group
//all
//choice
// The complex type contains the elements defined in the specified sequence.
Sequence *sequence `xml:"sequence"`
Attribute []attribute `xml:"attribute"`
//attributeGroup
//anyAttribute
}
// https://msdn.microsoft.com/en-us/library/ms256053(v=vs.110).aspx
// Number of occurrences: One time
// Optional. annotation
// Required. One and only one of the following elements: restriction (complexContent), or extension (complexContent).
type complexContent struct {
ID string `xml:"id,attr"`
Mixed string `xml:"mixed,attr"`
Annotation annotation `xml:"annotation"`
Restriction *restrictioncomplexContent `xml:"restriction"` //OR
Extension *extensioncomplexContent `xml:"extension"` //
}
// https://msdn.microsoft.com/en-us/library/ms256061(v=vs.110).aspx
// Number of occurrences: One time
type restrictioncomplexContent struct {
Base Type `xml:"base,attr"`
Id string `xml:"id,attr"`
//group
//all
//choice
Sequence sequence `xml:"sequence"`
Attribute []attribute `xml:"attribute"`
//attributeGroup
//anyAttribute
}
// https://msdn.microsoft.com/en-us/library/ms256161(v=vs.110).aspx
// Number of occurrences: One time
type extensioncomplexContent struct {
Base Type `xml:"base,attr"`
ID string `xml:"id,attr"`
Annotation annotation `xml:"annotation"`
Attribute []attribute `xml:"attribute"`
//attributeGroup
//anyAttribute
//choice
//all
Sequence sequence `xml:"sequence"`
//group
}
// https://msdn.microsoft.com/en-us/library/ms256106(v=vs.110).aspx
// Number of occurrences: One time
// Optional — annotation
// Required — One and only one of the following elements: restriction (simpleContent), or extension (simpleContent).
type simpleContent struct {
ID string `xml:"id,attr"`
Annotation annotation `xml:"annotation"`
Restriction *restrictionSimpleContent `xml:"restriction"` //OR
Extension *extensionSimpleContent `xml:"extension"` //
}
// https://msdn.microsoft.com/en-us/library/ms256056(v=vs.110).aspx
// Number of occurrences: One time
type extensionSimpleContent struct {
Base Type `xml:"base,attr"`
ID string `xml:"id,attr"`
Annotation annotation `xml:"annotation"`
Attribute []attribute `xml:"attribute"`
//attributeGroup
//anyAttribute
}
// https://msdn.microsoft.com/en-us/library/ms256219(v=vs.110).aspx
// Number of occurrences: One time
type restrictionSimpleContent struct {
Base string `xml:"base,attr"`
Id string `xml:"id,attr"`
Annotation annotation `xml:"annotation"`
//fractionDigits
Enumeration []enumeration `xml:"enumeration"`
//length
//maxExclusive
//maxInclusive
//maxLength
//minExclusive
//minInclusive
//minLength
//pattern
SimpleType simpleType `xml:"simpleType"`
//totalDigits
//whiteSpace
Attribute attribute `xml:"attribute"`
//attributeGroup
//anyAttribute
}
// https://msdn.microsoft.com/en-us/library/ms256219(v=vs.110).aspx
type enumeration struct {
Value string `xml:"value,attr"`
Annotation annotation `xml:"annotation"`
}
// https://msdn.microsoft.com/en-us/library/ms256143(v=vs.110).aspx
// Number of occurrences: Defined one time in the schema element. Referred to multiple times in complex types or attribute groups.
type attribute struct {
Default string `xml:"default,attr"`
Fixed string `xml:"fixed,attr"`
Form string `xml:"form,attr"`
ID string `xml:"id,attr"`
Name string `xml:"name,attr"`
Ref string `xml:"ref,attr"`
Type Type `xml:"type,attr"`
Use string `xml:"use,attr"`
Annotation *annotation `xml:"annotation"`
SimpleType []simpleType `xml:"simpleType"`
}
type simpleType struct {
Final string `xml:"final,attr"`
ID string `xml:"id,attr"`
Name string `xml:"name,attr"`
Annotation annotation `xml:"annotation"`
//list,
Restriction *restrictionSimpleType `xml:"restriction"`
//union
}
type restrictionSimpleType struct {
Base Type `xml:"base,attr"`
ID string `xml:"id,attr"`
Annotation annotation `xml:"annotation"`
//fractionDigits
Enumeration []enumeration `xml:"enumeration"` //
//length
//maxExclusive
//maxInclusive
//maxLength
//minExclusive
//minInclusive
//minLength
//pattern
SimpleType simpleType `xml:"simpleType"`
//totalDigits
//whiteSpace
}
// type include struct {
// Id string `xml:"Id,attr"`
// SchemaLocation string `xml:"schemaLocation,attr"`
// Annotation annotation
// }
// type importT struct {
// Id string `xml:"id,attr"`
// Namespace string `xml:"namespace,attr"`
// SchemaLocation string `xml:"schemaLocation,attr"`
// Annotation annotation
// }
// https://msdn.microsoft.com/en-us/library/ms256102(v=vs.110).aspx
type annotation struct {
AppInfo appInfo `xml:"appinfo"`
Documentation []documentation `xml:"documentation"`
}
func (e annotation) IncludedIn(call string, request bool) bool {
if call == "" {
return true
}
for _, a := range e.AppInfo.CallInfo {
if a.AllCallsExcept != "" {
excepts := strings.Split(strings.Replace(a.AllCallsExcept, " ", "", -1), ",")
if contains(excepts, call) {
return false
}
return true
}
if a.AllCalls != nil {
if request {
return a.RequiredInput != ""
} else { //response
return a.Returned != ""
}
}
if request {
if contains(a.CallName, call) {
return a.RequiredInput != ""
}
} else { //response
if contains(a.CallName, call) {
return a.Returned != ""
}
}
}
return false
}
func (e attribute) NeedsValidation(callName string) (ValidationContainer, bool) {
list := ValidationContainer{}
if e.Annotation == nil {
return list, false
}
a := e.Annotation
if a.RequiredFor(callName) || e.Use == "required" {
list.New(ValTypRequired, nil)
}
if nlist, ok := a.AppInfo.ValidationRules(callName); ok {
list = append(list, nlist...)
}
return list, list.Len() > 0
}
type ValidationRule struct {
Type ValidationType
Value interface{}
}
func (v ValidationRule) ValueInt() (int, error) {
strValue := v.Value.(string)
if strValue == "length of longest name in ShippingRegionCodeType and CountryCodeType" {
codeTypes := []string{"ShippingRegionCodeType", "CountryCodeType"}
var biggestInt int
for _, k := range codeTypes {
if splx, ok := FindSimple(k); ok {
for _, s := range splx.Restriction.Enumeration {
if biggestInt < len(s.Value) {
biggestInt = len(s.Value)
}
}
} else {
return 0, errors.New("could not find simple type: " + k)
}
}
return biggestInt, nil
}
if mxRegx := regexp.MustCompile(`Currently, the maximum length is (\d+) `).FindStringSubmatch(strValue); len(mxRegx) == 2 {
strValue = mxRegx[1]
goto parse
}
if mxRegx := regexp.MustCompile(`allocates up to (\d+) characters`).FindStringSubmatch(strValue); len(mxRegx) == 2 {
strValue = mxRegx[1]
}
parse:
value := strings.Split(strValue, " ")[0]
flt, err := strconv.ParseFloat(value, 64)
if err != nil {
return 0, err
}
return int(flt), nil
}
type ValidationContainer []ValidationRule
func (x *ValidationContainer) New(validation ValidationType, value interface{}) {
*x = append(*x, ValidationRule{Type: validation, Value: value})
}
func (x ValidationContainer) Len() int {
return len(x)
}
func (x *ValidationContainer) Includes(value ValidationType) (rule *ValidationRule, ok bool) {
for _, v := range *x {
if value == v.Type {
return &v, true
}
}
return nil, false
}
func (x *ValidationContainer) Except(values ...ValidationType) (rules ValidationContainer) {
for _, v := range *x {
for _, exc := range values {
if exc == v.Type {
goto next
}
}
rules = append(rules, v)
next:
}
return
}
func (a appInfo) ValidationRules(callName string) (ValidationContainer, bool) {
list := ValidationContainer{}
if strings.HasSuffix(callName, "Response") {
return list, false
}
if x, ok := a.MaxOccurs(); ok {
list.New(ValTypMaxOccurs, x)
}
if x, ok := a.AllValuesExcept(); ok {
list.New(ValTypAllValuesExcept, x)
}
if x, ok := a.OnlyTheseValues(); ok {
list.New(ValTypOnlyTheseValues, x)
}
if x, ok := a.MaxLength(); ok {
list.New(ValTypMaxLength, x)
}
if x, ok := a.Min(); ok {
list.New(ValTypMin, x)
}
if x, ok := a.Max(); ok {
list.New(ValTypMax, x)
}
for _, a2 := range a.CallInfo {
if contains(a2.CallName, callName) {
if x, ok := a2.MaxOccurs(); ok {
list.New(ValTypMaxOccurs, x)
}
if x, ok := a2.AllValuesExcept(); ok {
list.New(ValTypAllValuesExcept, x)
}
if x, ok := a2.OnlyTheseValues(); ok {
list.New(ValTypOnlyTheseValues, x)
}
if x, ok := a2.MaxLength(); ok {
list.New(ValTypMaxLength, x)
}
if x, ok := a2.Min(); ok {
list.New(ValTypMin, x)
}
if x, ok := a2.Max(); ok {
list.New(ValTypMax, x)
}
}
}
return list, list.Len() > 0
}
func (e element) NeedsValidation(callName string) (ValidationContainer, bool) {
list := ValidationContainer{}
if strings.HasSuffix(callName, "Response") {
return list, false
}
if e.Annotation == nil {
return list, false
}
a := e.Annotation
if a.RequiredFor(callName) {
list.New(ValTypRequired, nil)
} else {
return list, list.Len() > 0
}
if nlist, ok := a.AppInfo.ValidationRules(callName); ok {
list = append(list, nlist...)
}
return list, list.Len() > 0
}
func (a annotation) RequiredFor(callName string) bool {
for _, ci := range a.AppInfo.CallInfo {
if ci.AllCallsExcept != "" {
excepts := strings.Split(strings.Replace(ci.AllCallsExcept, " ", "", -1), ",")
if contains(excepts, callName) {
return false
}
return true
}
if ci.AllCalls != nil {
return ci.RequiredInput == "Yes"
}
for _, c := range ci.CallName {
if c == callName {
return ci.RequiredInput == "Yes"
}
}
}
return false
}
func (a annotation) RequiredInput() bool {
isRequiredInput := false
for _, ci := range a.AppInfo.CallInfo {
if ci.RequiredInput != "" {
isRequiredInput = true
}
}
return isRequiredInput
}
func (a annotation) Skip() bool {
if a.AppInfo.NoCall() {
return true
}
if a.AppInfo.CallName != "" && !contains(exportedElements, a.AppInfo.CallName) {
return true
}
for _, p := range a.AppInfo.CallInfo {
if p.AllCalls != nil {
return false
}
if p.NoCall() {
return true
}
if p.AllCallsExcept != "" {
excepts := strings.Split(strings.Replace(p.AllCallsExcept, " ", "", -1), ",")
found := 0
for _, m := range exportedElements {
if contains(excepts, m) {
found++
}
}
if found == len(exportedElements) {
return true
}
return false
}
for _, m := range p.CallName {
if contains(exportedElements, m) {
return false
}
}
}
return len(a.AppInfo.CallInfo) != 0
}
// https://msdn.microsoft.com/en-us/library/ms256134(v=vs.110).aspx
type appInfo struct {
//Source string `xml:"source,attr"`
EbAppInfo
}
// https://msdn.microsoft.com/en-us/library/ms256112(v=vs.110).aspx
type documentation struct {
Source string `xml:"source,attr"`
XmlLang string `xml:"lang,attr"`
//Any well-formed XML content.
Version string
Contents string `xml:",chardata"`
}
// https://msdn.microsoft.com/en-us/library/ms256089(v=vs.110).aspx
// One time within group; otherwise, unlimited.
type sequence struct {
ID string `xml:"id,attr"`
MaxOccurs string `xml:"maxOccurs,attr"`
MinOccurs string `xml:"minOccurs,attr"`
Annotation annotation `xml:"annotation"`
//any
//choice
Element []element `xml:"element"`
//group
//Sequence []sequence `xml:"sequence"`
}
|
// This file was generated by counterfeiter
package fakes
import (
"sync"
"github.com/cloudfoundry-incubator/garden-shed/repository_fetcher"
"github.com/cloudfoundry-incubator/garden-shed/rootfs_provider"
)
type FakeLayerCreator struct {
CreateStub func(id string, parentImage *repository_fetcher.Image, spec rootfs_provider.Spec) (string, []string, error)
createMutex sync.RWMutex
createArgsForCall []struct {
id string
parentImage *repository_fetcher.Image
spec rootfs_provider.Spec
}
createReturns struct {
result1 string
result2 []string
result3 error
}
}
func (fake *FakeLayerCreator) Create(id string, parentImage *repository_fetcher.Image, spec rootfs_provider.Spec) (string, []string, error) {
fake.createMutex.Lock()
fake.createArgsForCall = append(fake.createArgsForCall, struct {
id string
parentImage *repository_fetcher.Image
spec rootfs_provider.Spec
}{id, parentImage, spec})
fake.createMutex.Unlock()
if fake.CreateStub != nil {
return fake.CreateStub(id, parentImage, spec)
} else {
return fake.createReturns.result1, fake.createReturns.result2, fake.createReturns.result3
}
}
func (fake *FakeLayerCreator) CreateCallCount() int {
fake.createMutex.RLock()
defer fake.createMutex.RUnlock()
return len(fake.createArgsForCall)
}
func (fake *FakeLayerCreator) CreateArgsForCall(i int) (string, *repository_fetcher.Image, rootfs_provider.Spec) {
fake.createMutex.RLock()
defer fake.createMutex.RUnlock()
return fake.createArgsForCall[i].id, fake.createArgsForCall[i].parentImage, fake.createArgsForCall[i].spec
}
func (fake *FakeLayerCreator) CreateReturns(result1 string, result2 []string, result3 error) {
fake.CreateStub = nil
fake.createReturns = struct {
result1 string
result2 []string
result3 error
}{result1, result2, result3}
}
var _ rootfs_provider.LayerCreator = new(FakeLayerCreator)
|
package metadata
import "github.com/caicloud/simple-object-storage/pkg/metadata/apis"
type Bucket interface {
ListBucket() ([]apis.Bucket, error)
PutBucket(bucket *apis.Bucket) error
GetBucket(name string) (*apis.Bucket, error)
DeleteBucket(name string) error
Close() error
}
type Object interface {
ListObject(bucket, prefix string, start, limit int) ([]apis.Object, error)
PutObject(object *apis.Object) error
GetObject(bucket, key string) (*apis.Object, error)
DeleteObject(bucket, key string) error
Close() error
}
|
package controllers
import (
"errors"
"github.com/gin-gonic/gin"
"go-architecture-mysql/api/exceptions"
"go-architecture-mysql/api/middlewares"
"go-architecture-mysql/api/payloads"
"go-architecture-mysql/api/securities"
"go-architecture-mysql/api/services"
"go-architecture-mysql/api/utils"
"net/http"
"strconv"
"strings"
)
type UserController struct {
userService services.UserService
}
func CreateUserRoutes(r *gin.RouterGroup, userService services.UserService) {
userHandler := UserController{
userService: userService,
}
r.Use(middlewares.SetupAuthenticationMiddleware())
r.GET("/ViewAllUser", userHandler.ViewAllUser)
r.GET("/FindMe", userHandler.FindMe)
r.GET("/FindByUsername/:username", userHandler.FindByUser)
r.POST("/UpdateUser/:user_id", userHandler.UpdateUser)
r.POST("/DeleteUser/:user_id", userHandler.DeleteUser)
}
// @Summary View All User
// @Description REST API User
// @Accept json
// @Produce json
// @Tags User Controller
// @Security BearerAuth
// @Success 200 {object} payloads.Respons
// @Failure 500,400,401,404,403,422 {object} exceptions.Error
// @Router /User/ViewAllUser [get]
func (r *UserController) ViewAllUser(c *gin.Context) {
get, err := r.userService.ViewUser()
if err != nil {
exceptions.AppException(c, err.Error())
return
}
payloads.HandleSuccess(c, get, "Get Data Successfully", http.StatusOK)
}
// @Summary Find User
// @Description REST API User
// @Accept json
// @Produce json
// @Tags User Controller
// @Security BearerAuth
// @Success 200 {object} payloads.Respons
// @Param username path string true "Username"
// @Failure 500,400,401,404,403,422 {object} exceptions.Error
// @Router /User/FindByUsername/{username} [get]
func (r *UserController) FindByUser(c *gin.Context) {
username := c.Param("username")
get, err := r.userService.FindUser(username)
if err != nil {
exceptions.AppException(c, err.Error())
return
}
payloads.HandleSuccess(c, get, "Get Data Successfully", http.StatusOK)
}
// @Summary Find Me
// @Description REST API User
// @Accept json
// @Produce json
// @Tags User Controller
// @Security BearerAuth
// @Success 200 {object} payloads.Respons
// @Failure 500,400,401,404,403,422 {object} exceptions.Error
// @Router /User/FindMe [get]
func (r *UserController) FindMe(c *gin.Context) {
check, err := securities.ExtractAuthToken(c)
if err != nil {
exceptions.AppException(c, err.Error())
return
}
get, err := r.userService.FindUser(check.Username)
if err != nil {
exceptions.AppException(c, err.Error())
return
}
payloads.HandleSuccess(c, get, "Get Data Successfully", http.StatusOK)
}
// @Summary Update User
// @Description REST API User
// @Accept json
// @Produce json
// @Tags User Controller
// @Security BearerAuth
// @Param user_id path string true "User ID"
// @Param reqBody body payloads.CreateRequest true "Form Request"
// @Success 200 {object} payloads.Respons
// @Failure 500,400,401,404,403,422 {object} exceptions.Error
// @Router /User/UpdateUser/{user_id} [post]
func (r *UserController) UpdateUser(c *gin.Context) {
userId, _ := strconv.Atoi(c.Param("user_id"))
var updateData payloads.CreateRequest
if err := c.ShouldBindJSON(&updateData); err != nil {
exceptions.EntityException(c, err.Error())
return
}
check := utils.ValidationForm(updateData)
if check != "" {
exceptions.BadRequestException(c, check)
return
}
findUser, _ := r.userService.FindById(uint(userId))
if findUser.Username == "" {
exceptions.NotFoundException(c, errors.New("User not found").Error())
return
}
hash, err := securities.HashPassword(updateData.Password)
if err != nil {
exceptions.AppException(c, err.Error())
return
}
updateData.Username = strings.ToLower(strings.ReplaceAll(updateData.Username, " ", ""))
updateData.Password = strings.ReplaceAll(updateData.Password, " ", "")
updateData.Password = hash
get, err := r.userService.UpdateUser(updateData, uint(userId))
if err != nil {
exceptions.AppException(c, err.Error())
return
}
payloads.HandleSuccess(c, get, "Update Data Successfully", http.StatusOK)
}
// @Summary Delete User
// @Description REST API User
// @Accept json
// @Produce json
// @Tags User Controller
// @Security BearerAuth
// @Param user_id path string true "User ID"
// @Success 200 {object} payloads.Respons
// @Failure 500,400,401,404,403,422 {object} exceptions.Error
// @Router /User/DeleteUser/{user_id} [post]
func (r *UserController) DeleteUser(c *gin.Context) {
userId, _ := strconv.Atoi(c.Param("user_id"))
get, err := r.userService.DeleteUser(uint(userId))
if err != nil {
exceptions.AppException(c, err.Error())
return
}
payloads.HandleSuccess(c, get, "Delete Data Successfully", http.StatusOK)
}
|
package service
import godd "github.com/pagongamedev/go-dd"
// Service interface
type Service interface {
MessageRead(str string) (*godd.Map, *godd.Error)
}
// Repository interface
type Repository interface {
GetMessage(str string) (*godd.Map, *godd.Error)
}
// ======== service.go ============
// NewService New Service
func NewService(repo Repository) (Service, error) {
svc := DemoService{repo}
return &svc, nil
}
// DemoService struct
type DemoService struct {
repo Repository
}
// ============== API File ====================
//MessageRead func
func (svc *DemoService) MessageRead(str string) (*godd.Map, *godd.Error) {
return svc.repo.GetMessage(str)
}
|
package extract
import (
"bufio"
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"github.com/jszwec/csvutil"
)
type ExtractCmd struct{}
type LineCsau struct {
DtEpreuve string
Organisateur string
CdRace string
CdLO string
NumLO string
TatooChip string
CdResultat string
}
type LineTc struct {
DtEpreuve string
Organisateur string
CdFci string
CdLO string
NumLO string
TatooChip string
CdResultat string
Niveau string
}
func visit(prefix *string, files *[]string) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Fatal(err)
}
if filepath.Ext(path) == ".csv" && strings.HasPrefix(info.Name(), *prefix) {
*files = append(*files, path)
}
return nil
}
}
func (extract *ExtractCmd) FindCSV(prefix string, directory string) (files []string, _err error) {
err := filepath.Walk(directory, visit(&prefix, &files))
if err != nil {
return files, err
}
if len(files) == 0 {
return files, errors.New("Aucun fichier trouvé")
}
return files, nil
}
func setDecoder(csvfile *os.File, lineType interface{}) (dec *csvutil.Decoder, _err error) {
// Skip first row (line)
row1, err := bufio.NewReader(csvfile).ReadSlice('\n')
if err != nil {
return nil, errors.New("Couldn't read the csv file")
}
_, err = csvfile.Seek(int64(len(row1)), io.SeekStart)
if err != nil {
return nil, errors.New("Couldn't skip first line the csv file")
}
// Read remaining rows
r := csv.NewReader(csvfile)
r.Comma = ';'
csvHeader, err := csvutil.Header(lineType, "csv")
if err != nil {
return nil, errors.New("Couldn't fix header")
}
dec, err1 := csvutil.NewDecoder(r, csvHeader...)
if err1 != nil {
return nil, errors.New("Couldn't configure decoder")
}
return dec, nil
}
func parseTcCSV(files []string) (lines []LineTc, _err error) {
for _, file := range files {
log.Printf("ParseCSV > %s", file)
csvfile, err := os.Open(file)
if err != nil {
return lines, errors.New("Couldn't open the csv file")
}
defer csvfile.Close()
dec, err := setDecoder(csvfile, LineTc{})
if err != nil {
return lines, errors.New("Couldn't configure decoder")
}
for {
var l LineTc
if err := dec.Decode(&l); err == io.EOF {
break
} else if err != nil {
return lines, errors.New("Couldn't decode csv line")
}
lines = append(lines, l)
}
}
return lines, nil
}
func parseCsauCSV(files []string) (lines []LineCsau, _err error) {
for _, file := range files {
log.Printf("ParseCSV > %s", file)
csvfile, err := os.Open(file)
if err != nil {
return lines, errors.New("Couldn't open the csv file")
}
defer csvfile.Close()
dec, err := setDecoder(csvfile, LineCsau{})
if err != nil {
return lines, errors.New("Couldn't configure decoder")
}
for {
var l LineCsau
if err := dec.Decode(&l); err == io.EOF {
break
} else if err != nil {
return lines, fmt.Errorf("Couldn't decode csv line %s", err)
}
lines = append(lines, l)
}
}
return lines, nil
}
func (extrac *ExtractCmd) ParseCSV(prefix string, files []string) (lines []interface{}, _err error) {
switch prefix {
case "csau":
var lines []LineCsau
lines, _err := parseCsauCSV(files)
return []interface{}{lines, nil}, _err
case "tc":
var lines []LineTc
lines, _err := parseTcCSV(files)
return []interface{}{nil, lines}, _err
default:
return []interface{}{nil, nil}, fmt.Errorf("Couldn't recognized prefix %s", prefix)
}
}
func (extrac *ExtractCmd) Write(file string, outputs []string) {
f, err := os.Create(file)
if err != nil {
log.Panic(err)
}
defer f.Close()
writer := bufio.NewWriter(f)
for _, line := range outputs {
_, err := writer.WriteString(line + "\n")
if err != nil {
log.Fatalf("Got error while writing to a file. Err: %s", err.Error())
}
}
writer.Flush()
}
|
// Copyright 2014 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.
package server
import (
"errors"
"regexp"
"golang.org/x/debug/dwarf"
)
func (s *Server) lookupRE(re *regexp.Regexp) (result []string, err error) {
r := s.dwarfData.Reader()
for {
entry, err := r.Next()
if err != nil {
return nil, err
}
if entry == nil {
// TODO: why don't we get an error here.
break
}
nameAttr := entry.Val(dwarf.AttrName)
if nameAttr == nil {
// TODO: this shouldn't be possible.
continue
}
name, ok := nameAttr.(string)
if !ok || !re.MatchString(name) {
continue
}
result = append(result, name)
}
return result, nil
}
func (s *Server) lookupFunction(name string) (uint64, error) {
return s.dwarfData.LookupFunction(name)
}
func (s *Server) lookupVariable(name string) (uint64, error) {
return s.dwarfData.LookupVariable(name)
}
func (s *Server) lookupPC(pc uint64) (string, error) {
return s.dwarfData.LookupPC(pc)
}
func (s *Server) entryForPC(pc uint64) (entry *dwarf.Entry, lowpc uint64, err error) {
return s.dwarfData.EntryForPC(pc)
}
// evalLocation parses a DWARF location description encoded in v. It works for
// cases where the variable is stored at an offset from the Canonical Frame
// Address. The return value is this offset.
// TODO: a more general location-description-parsing function.
func evalLocation(v []uint8) (int64, error) {
// Some DWARF constants.
const (
opConsts = 0x11
opPlus = 0x22
opCallFrameCFA = 0x9C
)
if len(v) == 0 {
return 0, errors.New("empty location specifier")
}
if v[0] != opCallFrameCFA {
return 0, errors.New("unsupported location specifier")
}
if len(v) == 1 {
// The location description was just DW_OP_call_frame_cfa, so the location is exactly the CFA.
return 0, nil
}
if v[1] != opConsts {
return 0, errors.New("unsupported location specifier")
}
offset, v, err := sleb128(v[2:])
if err != nil {
return 0, err
}
if len(v) == 1 && v[0] == opPlus {
// The location description was DW_OP_call_frame_cfa, DW_OP_consts <offset>, DW_OP_plus.
// So return the offset.
return offset, nil
}
return 0, errors.New("unsupported location specifier")
}
func uleb128(v []uint8) (u uint64) {
var shift uint
for _, x := range v {
u |= (uint64(x) & 0x7F) << shift
shift += 7
if x&0x80 == 0 {
break
}
}
return u
}
// sleb128 parses a signed integer encoded with sleb128 at the start of v, and
// returns the integer and the remainder of v.
func sleb128(v []uint8) (s int64, rest []uint8, err error) {
var shift uint
var sign int64 = -1
var i int
var x uint8
for i, x = range v {
s |= (int64(x) & 0x7F) << shift
shift += 7
sign <<= 7
if x&0x80 == 0 {
if x&0x40 != 0 {
s |= sign
}
break
}
}
if i == len(v) {
return 0, nil, errors.New("truncated sleb128")
}
return s, v[i+1:], nil
}
|
package bip39
import (
"encoding/hex"
"fmt"
"reflect"
"testing"
)
func TestIsMnemonicValid(t *testing.T) {
type args struct {
mnemonic string
lang Language
}
tests := []struct {
name string
args args
want bool
}{
{
name: "English",
args: args{
mnemonic: "check fiscal fit sword unlock rough lottery tool sting pluck bulb random",
lang: English,
},
want: true,
},
{
name: "Englishx2",
args: args{
mnemonic: "rich soon pool legal busy add couch tower goose security raven anger",
lang: English,
},
want: true,
},
{
name: "EnglishValidLength",
args: args{
mnemonic: "rich soon pool legal busy add couch tower goose security raven",
lang: English,
},
want: false,
},
{
name: "EnglishNoWord",
args: args{
mnemonic: "rich soon pool legal busy add couch tower goose security women",
lang: English,
},
want: false,
},
{
name: "EnglishChecksumError",
args: args{
mnemonic: "rich soon pool legal busy add couch tower goose security base",
lang: English,
},
want: false,
},
{
name: "ChineseSimplified",
args: args{
mnemonic: "氮 冠 锋 枪 做 到 容 枯 获 槽 弧 部",
lang: ChineseSimplified,
},
want: true,
},
{
name: "ChineseTraditional",
args: args{
mnemonic: "氮 冠 鋒 槍 做 到 容 枯 獲 槽 弧 部",
lang: ChineseTraditional,
},
want: true,
},
{
name: "Japanese",
args: args{
mnemonic: "ねほりはほり ひらがな とさか そつう おうじ あてな きくらげ みもと してつ ぱそこん にってい いこつ",
lang: Japanese,
},
want: true,
},
{
name: "Spanish",
args: args{
mnemonic: "posible ruptura ozono ligero bobina acto chuleta tetera gol realidad pez alerta",
lang: Spanish,
},
want: true,
},
{
name: "French",
args: args{
mnemonic: "pieuvre revivre nuptial implorer blinder accroche chute syntaxe félin promener parcelle aimable",
lang: French,
},
want: true,
},
{
name: "Italian",
args: args{
mnemonic: "risultato siccome prenotare mimosa bosco adottare continuo tifare ignaro sbloccato residente alticcio",
lang: Italian,
},
want: true,
},
{
name: "Korean",
args: args{
mnemonic: "전망 차선 이전 실장 기간 간판 대접 판단 생명 존재 잠깐 건축",
lang: Korean,
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsMnemonicValid(tt.args.mnemonic, tt.args.lang); got != tt.want {
t.Errorf("IsMnemonicValid() = %v, want %v", got, tt.want)
}
})
}
}
func ExampleIsMnemonicValid() {
var mnemonic = "check fiscal fit sword unlock" +
" rough lottery tool sting pluck bulb random"
fmt.Println(IsMnemonicValid(mnemonic, English))
// Output:
// true
}
func TestNewMnemonic(t *testing.T) {
type args struct {
wordsLen int
lang Language
skip bool
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "words length less than 12",
args: args{wordsLen: 1},
want: "",
wantErr: true,
},
{
name: "words length greater than 24",
args: args{wordsLen: 25},
want: "",
wantErr: true,
},
{
name: "words length isn't multiple of 3",
args: args{wordsLen: 13},
want: "",
wantErr: true,
},
{
name: "words length is ok",
args: args{wordsLen: 12, skip: true},
want: "",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewMnemonic(tt.args.wordsLen, tt.args.lang)
if (err != nil) != tt.wantErr {
t.Errorf("NewMnemonic() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want && !tt.args.skip {
t.Errorf("NewMnemonic() = %v, want %v", got, tt.want)
}
})
}
}
func TestMnemonicByEntropy(t *testing.T) {
type args struct {
entropy []byte
lang Language
skip bool
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "entropy length is less than 16",
args: args{entropy: make([]byte, 1)},
want: "",
wantErr: true,
},
{
name: "entropy length is greater than 32",
args: args{entropy: make([]byte, 33)},
want: "",
wantErr: true,
},
{
name: "entropy length is not multiple of 4",
args: args{entropy: make([]byte, 17)},
want: "",
wantErr: true,
},
{
name: "entropy length is ok",
args: args{entropy: make([]byte, 16), skip: true},
want: "",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewMnemonicByEntropy(tt.args.entropy, tt.args.lang)
if (err != nil) != tt.wantErr {
t.Errorf("MnemonicByEntropy() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want && !tt.args.skip {
t.Errorf("MnemonicByEntropy() = %v, want %v", got, tt.want)
}
})
}
}
func TestMnemonicToSeed(t *testing.T) {
type args struct {
mnemonic string
passwd string
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "Mnemonic is empty",
args: args{
mnemonic: "",
passwd: "",
},
want: "",
wantErr: true,
},
{
name: "Without password",
args: args{
mnemonic: "moment butter trigger coffee divert choose slim tiger ice series cup enough",
passwd: "",
},
want: "4b8c14466dbad77f6ff3adf016d372fbccfb0308ea5a36c9ab0c6f6eb1162ca461c02a1df2a1b854291785e59f0d98eb39af4d02a0ca8ffae5f66ff2dd0e2a48",
wantErr: false,
},
{
name: "With password",
args: args{
mnemonic: "coffee purity language speed anger whisper ramp burden response brief coast trigger",
passwd: "bip39",
},
want: "ddfb143f00d7c135a59f1a05d00d2477a3eaa8ebfc1d4a4ddf2875d03cb74635458161a40faab128b4b8e1aeed75a919508a2816e7ef0a282105ad8ae48c91eb",
wantErr: false,
},
{
name: "Janpanese",
args: args{
mnemonic: "こころ いどう きあつ そうがんきょう へいあん せつりつ ごうせい はいち いびき きこく あんい おちつく きこえる けんとう たいこ すすめる はっけん ていど はんおん いんさつ うなぎ しねま れいぼう みつかる",
passwd: "㍍ガバヴァぱばぐゞちぢ十人十色",
},
want: "43de99b502e152d4c198542624511db3007c8f8f126a30818e856b2d8a20400d29e7a7e3fdd21f909e23be5e3c8d9aee3a739b0b65041ff0b8637276703f65c2",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := MnemonicToSeed(tt.args.mnemonic, tt.args.passwd)
if (err != nil) != tt.wantErr {
t.Errorf("MnemonicToSeed() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(hex.EncodeToString(got), tt.want) {
t.Errorf("MnemonicToSeed() = %v, want %v", got, tt.want)
}
})
}
}
func Test_entropyToMnemonic(t *testing.T) {
type args struct {
hexdata string
wordsLen int
language Language
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "0",
args: args{
hexdata: "00000000000000000000000000000000",
language: English,
},
want: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
wantErr: false,
},
{
name: "1",
args: args{
hexdata: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
language: English,
},
want: "legal winner thank year wave sausage worth useful legal winner thank yellow",
wantErr: false,
},
{
name: "2",
args: args{
hexdata: "000000000000000000000000000000000000000000000000",
language: English,
},
want: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent",
wantErr: false,
},
{
name: "3",
args: args{
hexdata: "8080808080808080808080808080808080808080808080808080808080808080",
language: Japanese,
},
want: "そとづら あまど おおう あこがれる いくぶん けいけん あたえる いよく そとづら あまど おおう あこがれる いくぶん けいけん あたえる いよく そとづら あまど おおう あこがれる いくぶん けいけん あたえる うめる",
wantErr: false,
},
{
name: "4",
args: args{
hexdata: "3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982",
language: Japanese,
},
want: "くのう てぬぐい そんかい すろっと ちきゅう ほあん とさか はくしゅ ひびく みえる そざい てんすう たんぴん くしょう すいようび みけん きさらぎ げざん ふくざつ あつかう はやい くろう おやゆび こすう",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
entropy, err := hex.DecodeString(tt.args.hexdata)
if err != nil {
t.Errorf("entropyToMnemonic() decode hex string error %v", err)
return
}
got, err := entropyToMnemonic(entropy, tt.args.wordsLen, tt.args.language)
if (err != nil) != tt.wantErr {
t.Errorf("entropyToMnemonic() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("entropyToMnemonic() = %v, want %v", got, tt.want)
}
})
}
}
func ExampleNewMnemonic() {
// Words length can be 12 | 15 | 18 | 21 | 24
NewMnemonic(12, ChineseSimplified)
NewMnemonic(24, ChineseTraditional)
NewMnemonic(12, English)
NewMnemonic(15, French)
NewMnemonic(18, Italian)
NewMnemonic(21, Japanese)
NewMnemonic(24, French)
NewMnemonic(15, Korean)
NewMnemonic(15, Spanish)
}
func ExampleMnemonicToSeed() {
mnemonic := "jungle devote wisdom slim" +
" census orbit merge order flip sketch add mass"
fmt.Println(IsMnemonicValid(mnemonic, English))
// Output:
// true
}
func ExampleNewMnemonicByEntropy() {
entropy, _ := hex.DecodeString("79079bf165e25537e2dce15919440cc4")
mnemonic, _ := NewMnemonicByEntropy(entropy, English)
fmt.Println(mnemonic)
// Output:
// jungle devote wisdom slim census orbit merge order flip sketch add mass
}
|
package main
func foo(a, a int) {
}
|
/*
Copyright 2021-2023 ICS-FORTH.
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 netutils
import (
"io"
"log"
"net"
"net/http"
"github.com/pkg/errors"
)
// GetPublicIP asks a public IP API to return our public IP.
func GetPublicIP() (net.IP, error) {
url := "https://api.ipify.org?format=text"
// https://www.ipify.org
// http://myexternalip.com
// http://api.ident.me
// http://whatismyipaddress.com/api
resp, err := http.Get(url)
if err != nil {
return nil, errors.Wrap(err, "cannot contact public IP address API")
}
ipStr, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "ip decoding error")
}
if err := resp.Body.Close(); err != nil {
return nil, errors.Wrapf(err, "cannot close body")
}
return net.ParseIP(string(ipStr)), nil
}
// GetOutboundIP returns the preferred outbound ip of this machine
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
|
/*
Copyright 2020 The Kubermatic Kubernetes Platform contributors.
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 provider
import (
"context"
"net/http"
"github.com/go-kit/kit/endpoint"
apiv1 "k8c.io/kubermatic/v2/pkg/api/v1"
providercommon "k8c.io/kubermatic/v2/pkg/handler/common/provider"
"k8c.io/kubermatic/v2/pkg/handler/v1/common"
"k8c.io/kubermatic/v2/pkg/handler/v2/cluster"
"k8c.io/kubermatic/v2/pkg/provider"
)
func AzureSizeWithClusterCredentialsEndpoint(projectProvider provider.ProjectProvider, privilegedProjectProvider provider.PrivilegedProjectProvider, seedsGetter provider.SeedsGetter, userInfoGetter provider.UserInfoGetter) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(azureSizeNoCredentialsReq)
return providercommon.AzureSizeWithClusterCredentialsEndpoint(ctx, userInfoGetter, projectProvider, privilegedProjectProvider, seedsGetter, req.ProjectID, req.ClusterID)
}
}
func AzureAvailabilityZonesWithClusterCredentialsEndpoint(projectProvider provider.ProjectProvider, privilegedProjectProvider provider.PrivilegedProjectProvider, seedsGetter provider.SeedsGetter, userInfoGetter provider.UserInfoGetter) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(azureAvailabilityZonesNoCredentialsReq)
return providercommon.AzureAvailabilityZonesWithClusterCredentialsEndpoint(ctx, userInfoGetter, projectProvider, privilegedProjectProvider, seedsGetter, req.ProjectID, req.ClusterID, req.SKUName)
}
}
// azureSizeNoCredentialsReq represent a request for Azure VM sizes
// note that the request doesn't have credentials for authN
// swagger:parameters listAzureSizesNoCredentialsV2
type azureSizeNoCredentialsReq struct {
cluster.GetClusterReq
}
// GetSeedCluster returns the SeedCluster object
func (req azureSizeNoCredentialsReq) GetSeedCluster() apiv1.SeedCluster {
return apiv1.SeedCluster{
ClusterID: req.ClusterID,
}
}
func DecodeAzureSizesNoCredentialsReq(c context.Context, r *http.Request) (interface{}, error) {
var req azureSizeNoCredentialsReq
clusterID, err := common.DecodeClusterID(c, r)
if err != nil {
return nil, err
}
req.ClusterID = clusterID
pr, err := common.DecodeProjectRequest(c, r)
if err != nil {
return nil, err
}
req.ProjectReq = pr.(common.ProjectReq)
return req, nil
}
// azureAvailabilityZonesNoCredentialsReq represent a request for Azure Availability Zones
// note that the request doesn't have credentials for authN
// swagger:parameters listAzureAvailabilityZonesNoCredentialsV2
type azureAvailabilityZonesNoCredentialsReq struct {
azureSizeNoCredentialsReq
// in: header
// name: SKUName
SKUName string
}
// GetSeedCluster returns the SeedCluster object
func (req azureAvailabilityZonesNoCredentialsReq) GetSeedCluster() apiv1.SeedCluster {
return apiv1.SeedCluster{
ClusterID: req.ClusterID,
}
}
func DecodeAzureAvailabilityZonesNoCredentialsReq(c context.Context, r *http.Request) (interface{}, error) {
var req azureAvailabilityZonesNoCredentialsReq
lr, err := DecodeAzureSizesNoCredentialsReq(c, r)
if err != nil {
return nil, err
}
req.azureSizeNoCredentialsReq = lr.(azureSizeNoCredentialsReq)
req.SKUName = r.Header.Get("SKUName")
return req, nil
}
|
package imagechange
import (
"flag"
"testing"
kapi "k8s.io/kubernetes/pkg/api"
ktestclient "k8s.io/kubernetes/pkg/client/unversioned/testclient"
"k8s.io/kubernetes/pkg/runtime"
"github.com/openshift/origin/pkg/client/testclient"
deployapi "github.com/openshift/origin/pkg/deploy/api"
testapi "github.com/openshift/origin/pkg/deploy/api/test"
imageapi "github.com/openshift/origin/pkg/image/api"
)
func init() {
flag.Set("v", "5")
}
func makeStream(name, tag, dir, image string) *imageapi.ImageStream {
return &imageapi.ImageStream{
ObjectMeta: kapi.ObjectMeta{Name: name, Namespace: kapi.NamespaceDefault},
Status: imageapi.ImageStreamStatus{
Tags: map[string]imageapi.TagEventList{
tag: {
Items: []imageapi.TagEvent{
{
DockerImageReference: dir,
Image: image,
},
},
},
},
},
}
}
// TestHandle_changeForNonAutomaticTag ensures that an image update for which
// there is a matching trigger results in a no-op due to the trigger's
// automatic flag being set to false.
func TestHandle_changeForNonAutomaticTag(t *testing.T) {
fake := &testclient.Fake{}
fake.AddReactor("update", "deploymentconfigs", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) {
t.Fatalf("unexpected deploymentconfig update")
return true, nil, nil
})
controller := &ImageChangeController{
listDeploymentConfigs: func() ([]*deployapi.DeploymentConfig, error) {
config := testapi.OkDeploymentConfig(1)
config.Namespace = kapi.NamespaceDefault
config.Spec.Triggers[0].ImageChangeParams.Automatic = false
// The image has been resolved at least once before.
config.Spec.Triggers[0].ImageChangeParams.LastTriggeredImage = testapi.DockerImageReference
return []*deployapi.DeploymentConfig{config}, nil
},
client: fake,
}
// verify no-op
tagUpdate := makeStream(testapi.ImageStreamName, imageapi.DefaultImageTag, testapi.DockerImageReference, testapi.ImageID)
if err := controller.Handle(tagUpdate); err != nil {
t.Fatalf("unexpected err: %v", err)
}
if len(fake.Actions()) > 0 {
t.Fatalf("unexpected actions: %v", fake.Actions())
}
}
// TestHandle_changeForInitialNonAutomaticDeployment ensures that an image update for which
// there is a matching trigger will actually update the deployment config if it hasn't been
// deployed before.
func TestHandle_changeForInitialNonAutomaticDeployment(t *testing.T) {
fake := &testclient.Fake{}
controller := &ImageChangeController{
listDeploymentConfigs: func() ([]*deployapi.DeploymentConfig, error) {
config := testapi.OkDeploymentConfig(0)
config.Namespace = kapi.NamespaceDefault
config.Spec.Triggers[0].ImageChangeParams.Automatic = false
return []*deployapi.DeploymentConfig{config}, nil
},
client: fake,
}
// verify no-op
tagUpdate := makeStream(testapi.ImageStreamName, imageapi.DefaultImageTag, testapi.DockerImageReference, testapi.ImageID)
if err := controller.Handle(tagUpdate); err != nil {
t.Fatalf("unexpected err: %v", err)
}
actions := fake.Actions()
if len(actions) != 1 {
t.Fatalf("unexpected amount of actions: expected 1, got %d (%v)", len(actions), actions)
}
if !actions[0].Matches("update", "deploymentconfigs") {
t.Fatalf("unexpected action: %v", actions[0])
}
}
// TestHandle_changeForUnregisteredTag ensures that an image update for which
// there is a matching trigger results in a no-op due to the tag specified on
// the trigger not matching the tags defined on the image stream.
func TestHandle_changeForUnregisteredTag(t *testing.T) {
fake := &testclient.Fake{}
fake.AddReactor("update", "deploymentconfigs", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) {
t.Fatalf("unexpected deploymentconfig update")
return true, nil, nil
})
controller := &ImageChangeController{
listDeploymentConfigs: func() ([]*deployapi.DeploymentConfig, error) {
return []*deployapi.DeploymentConfig{testapi.OkDeploymentConfig(0)}, nil
},
client: fake,
}
// verify no-op
tagUpdate := makeStream(testapi.ImageStreamName, "unrecognized", testapi.DockerImageReference, testapi.ImageID)
if err := controller.Handle(tagUpdate); err != nil {
t.Fatalf("unexpected err: %v", err)
}
if len(fake.Actions()) > 0 {
t.Fatalf("unexpected actions: %v", fake.Actions())
}
}
// TestHandle_matchScenarios comprehensively tests trigger definitions against
// image stream updates to ensure that the image change triggers match (or don't
// match) properly.
func TestHandle_matchScenarios(t *testing.T) {
tests := []struct {
name string
param *deployapi.DeploymentTriggerImageChangeParams
matches bool
}{
{
name: "automatic=true, initial trigger, explicit namespace",
param: &deployapi.DeploymentTriggerImageChangeParams{
Automatic: true,
ContainerNames: []string{"container1"},
From: kapi.ObjectReference{Namespace: kapi.NamespaceDefault, Name: imageapi.JoinImageStreamTag(testapi.ImageStreamName, imageapi.DefaultImageTag)},
LastTriggeredImage: "",
},
matches: true,
},
{
name: "automatic=true, initial trigger, implicit namespace",
param: &deployapi.DeploymentTriggerImageChangeParams{
Automatic: true,
ContainerNames: []string{"container1"},
From: kapi.ObjectReference{Name: imageapi.JoinImageStreamTag(testapi.ImageStreamName, imageapi.DefaultImageTag)},
LastTriggeredImage: "",
},
matches: true,
},
{
name: "automatic=false, initial trigger",
param: &deployapi.DeploymentTriggerImageChangeParams{
Automatic: false,
ContainerNames: []string{"container1"},
From: kapi.ObjectReference{Namespace: kapi.NamespaceDefault, Name: imageapi.JoinImageStreamTag(testapi.ImageStreamName, imageapi.DefaultImageTag)},
LastTriggeredImage: "",
},
matches: true,
},
{
name: "(no-op) automatic=false, already triggered",
param: &deployapi.DeploymentTriggerImageChangeParams{
Automatic: false,
ContainerNames: []string{"container1"},
From: kapi.ObjectReference{Namespace: kapi.NamespaceDefault, Name: imageapi.JoinImageStreamTag(testapi.ImageStreamName, imageapi.DefaultImageTag)},
LastTriggeredImage: testapi.DockerImageReference,
},
matches: false,
},
{
name: "(no-op) automatic=true, image is already deployed",
param: &deployapi.DeploymentTriggerImageChangeParams{
Automatic: true,
ContainerNames: []string{"container1"},
From: kapi.ObjectReference{Name: imageapi.JoinImageStreamTag(testapi.ImageStreamName, imageapi.DefaultImageTag)},
LastTriggeredImage: testapi.DockerImageReference,
},
matches: false,
},
{
name: "(no-op) trigger doesn't match the stream",
param: &deployapi.DeploymentTriggerImageChangeParams{
Automatic: true,
ContainerNames: []string{"container1"},
From: kapi.ObjectReference{Namespace: kapi.NamespaceDefault, Name: imageapi.JoinImageStreamTag("other-stream", imageapi.DefaultImageTag)},
LastTriggeredImage: "",
},
matches: false,
},
}
for _, test := range tests {
updated := false
fake := &testclient.Fake{}
fake.AddReactor("update", "deploymentconfigs", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) {
if !test.matches {
t.Fatal("unexpected deploymentconfig update")
}
updated = true
return true, nil, nil
})
config := testapi.OkDeploymentConfig(1)
config.Namespace = kapi.NamespaceDefault
config.Spec.Triggers = []deployapi.DeploymentTriggerPolicy{
{
Type: deployapi.DeploymentTriggerOnImageChange,
ImageChangeParams: test.param,
},
}
controller := &ImageChangeController{
listDeploymentConfigs: func() ([]*deployapi.DeploymentConfig, error) {
return []*deployapi.DeploymentConfig{config}, nil
},
client: fake,
}
t.Logf("running test %q", test.name)
stream := makeStream(testapi.ImageStreamName, imageapi.DefaultImageTag, testapi.DockerImageReference, testapi.ImageID)
if err := controller.Handle(stream); err != nil {
t.Fatalf("unexpected error: %v", err)
}
// assert updates occurred
if test.matches && !updated {
t.Fatal("expected an update")
}
}
}
|
package kiteroot
import (
"net/http"
"strings"
"sync"
"testing"
)
func TestParse(t *testing.T) {
html := `
<html>
<head>
<title> KiteRoot </title>
<meta name="user" content="phynalle"/>
<meta name="profile" content="nothing"/>
</head>
<body>
omg
</body>
</html>
`
r := strings.NewReader(html)
_, err := Parse(r)
if err != nil {
t.Fatal(err)
}
}
func TestParseWebPages(t *testing.T) {
list := []string{
"http://golang.org",
"http://google.com",
"http://facebook.com",
"http://apple.com",
"http://github.com",
}
var wg sync.WaitGroup
wg.Add(len(list))
for _, url := range list {
go func(url string) {
resp, err := http.Get(url)
if err != nil {
t.Skipf("[%s] %s", url, err)
wg.Done()
return
}
defer resp.Body.Close()
_, err = Parse(resp.Body)
if err != nil {
t.Errorf("[%s] %s", url, err)
}
wg.Done()
}(url)
}
wg.Wait()
}
|
package routers
import (
"github.com/astaxie/beego"
"z2665/t12/controllers"
"z2665/t12/fliters"
)
//20150928移除命名空间只使用注解路由
//20150929将表单控制器加入路由,将过滤器加入路由
//20151004加入index路由
func init() {
beego.InsertFilter("/api/froms/changs/*", beego.BeforeRouter, fliters.UserFliter)
beego.InsertFilter("/api/users/changs/*", beego.BeforeRouter, fliters.UserFliter)
beego.Include(&controllers.UserController{})
beego.Include(&controllers.FromController{})
beego.Include(&controllers.IndexController{})
}
|
package main
import (
"fmt"
"sync"
"time"
)
var (
in chan int
a chan int
b chan int
c chan int
done chan struct{}
//wg sync.WaitGroup
lock sync.Mutex
)
func init() {
in = make(chan int, 1)
a = make(chan int, 1)
b = make(chan int, 1)
c = make(chan int, 1)
done = make(chan struct{})
}
func printA() {
for{
select {
case num := <-a:
if num % 3 == 0 {
fmt.Println("A")
} else {
b <- num
}
case <-done:
break
}
}
}
func printB() {
for{
select {
case num := <-b:
if num % 3 == 1 {
fmt.Println("B")
} else {
c <- num
}
case <-done:
break
}
}
}
func printC() {
for{
select {
case num := <-c:
if num % 3 == 2 {
fmt.Println("C")
}
case <-done:
break
}
}
}
func main() {
go printA()
go printB()
go printC()
for i:=0; i<30; i++ {
a <- i
}
time.Sleep(time.Second * 2)
close(done)
}
|
package main
import "fmt"
type User struct {
Id int `json-converter:"json:id"`
Name string `json-converter:"json:name"`
Address string `json-converter:"json:address"`
}
func main() {
var (
hogeUser User
hogeStr string = `{"id":5,"name":"hoge","address":"東京"}`
)
Decode(&hogeUser, hogeStr)
fmt.Println(hogeUser)
}
|
// Copyright © 2020. All rights reserved.
// Author: Ilya Stroy.
// Contacts: qioalice@gmail.com, https://github.com/qioalice
// License: https://opensource.org/licenses/MIT
package ekasys
import (
"os"
"sync"
)
type (
stdSynced struct {
f *os.File
sync.Mutex
}
)
var (
stdout *stdSynced
)
func (ss *stdSynced) Write(b []byte) (n int, err error) {
ss.Lock()
n, err = ss.f.Write(b)
ss.Unlock()
return n, err
}
func initStdoutSynced() {
stdout = new(stdSynced)
stdout.f = os.Stdout
}
|
package main
import (
"firstgo_app/src/controllers"
"fmt"
"log"
"net/http"
"github.com/gofiber/fiber/v2"
)
func indexRoute(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Bienvenido a mi API")
}
func setupRoutes(app *fiber.App) {
api := app.Group("/api")
v1 := api.Group("/v1")
v1.Get("/task", controllers.GetTasks)
v1.Get("/task/:id", controllers.GetTask)
v1.Post("/task", controllers.CreateTask)
v1.Put("/task/:id", controllers.UpdateTask)
v1.Delete("/task/:id", controllers.DeleteTask)
v1.Get("/todo", controllers.GetTodos)
v1.Post("/todo", controllers.CreateTodo)
v1.Get("/todo/:id", controllers.GetTodo)
v1.Delete("/todo/:id", controllers.DeleteTodo)
v1.Put("/todo/:id", controllers.UpdateTodo)
}
func main() {
var port string = "3000"
app := fiber.New()
setupRoutes(app)
fmt.Printf("Server running at port %s", port)
log.Fatal(app.Listen(":3000"))
}
|
package main
import (
"log"
"net/http"
)
func main() {
// calling our run function and handling the error
if err := run(); err != nil {
log.Fatal(err)
}
}
// run is used so we can just return errors and handle a single exit point in main.
func run() error {
// START OMIT
http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
authValue := request.Header.Get("Authorization")
if authValue == "" {
http.Error(writer, "authorization required", http.StatusUnauthorized)
return
}
// validate the auth provided
})
// END OMIT
// SERV_START OMIT
if err := http.ListenAndServe(":8080", nil); err != nil {
return err
}
// SERV_END OMIT
return nil
}
|
package ship
type Ship struct{}
func (S Ship) GetTransport() string {
return "Ship"
}
|
package module
import (
"context"
"github.com/go-redis/redis/v8"
clientv3 "go.etcd.io/etcd/client/v3"
"shared/utility/key"
)
// server discover
type Discover struct {
prefix string
client *clientv3.Client
}
func NewDiscover(service string, client *clientv3.Client) *Discover {
return &Discover{
prefix: key.MakeEtcdKey(service),
client: client,
}
}
func (d *Discover) SetServer(ctx context.Context, server, addr string) error {
_, err := d.client.Put(ctx, d.makeKey(server), addr)
if err != nil {
return err
}
return nil
}
func (d *Discover) DelServer(ctx context.Context, server string) error {
_, err := d.client.Delete(ctx, d.makeKey(server))
if err != nil {
return err
}
return nil
}
func (d *Discover) ListAddrs(ctx context.Context) ([]string, error) {
resp, err := d.client.Get(ctx, d.prefix, clientv3.WithPrefix())
if err != nil {
if err == redis.Nil {
return []string{}, nil
}
return nil, err
}
ret := make([]string, 0, len(resp.Kvs))
for _, v := range resp.Kvs {
ret = append(ret, string(v.Value))
}
return ret, nil
}
func (d *Discover) ListServers(ctx context.Context) ([]string, error) {
resp, err := d.client.Get(ctx, d.prefix, clientv3.WithPrefix())
if err != nil {
if err == redis.Nil {
return []string{}, nil
}
return nil, err
}
ret := make([]string, 0, len(resp.Kvs))
for _, v := range resp.Kvs {
keys := key.SplitEtcdKey(string(v.Key))
if len(keys) >= 2 {
ret = append(ret, keys[1])
}
}
return ret, nil
}
func (d *Discover) makeKey(server string) string {
return key.MakeEtcdKey(d.prefix, server)
}
|
package dao
import (
"db"
"errors"
"strconv"
"time"
"types"
"utils"
"github.com/google/uuid"
"github.com/kisielk/sqlstruct"
)
//AccountDAO - data access for accounts
type AccountDAO struct {
}
//CheckDuplicates - checks if account info already exists.
//Returns empty string and no error if no duplicates are found
//Returns string with an error message if duplicates are found
func (dao AccountDAO) CheckDuplicates(ID string, email string, db *db.MySQL) (string, error) {
stmt, err := db.PreparedQuery("SELECT * FROM users WHERE email = ? AND id <> ?")
if err != nil {
return "", err
}
rows, err := stmt.Query(email, ID)
if err != nil {
return "", err
}
stmt.Close()
defer rows.Close()
for rows.Next() {
return "Email is taken: " + email, nil
}
return "", nil
}
//CreateAccount - verifies and creates a new account
func (dao AccountDAO) CreateAccount(account *types.Account, db *db.MySQL) (string, error) {
if err := account.CheckName(); err != nil {
return err.Error(), nil
}
if err := account.CheckPassword(); err != nil {
return err.Error(), nil
}
if err := account.CheckEmail(); err != nil {
return err.Error(), nil
}
if err := account.CheckPhone(); err != nil {
return err.Error(), nil
}
//Check if account details already exist with another account
isDuplicate, err := dao.CheckDuplicates(account.ID, account.Email, db)
if err != nil {
return "", err
}
if isDuplicate != "" {
return isDuplicate, nil
}
//Setup account details
account.ID = uuid.New().String()
account.Created = time.Now()
account.Role = 100 //default
//Hash password
account.Password, err = utils.HashPassword(account.Password)
if err != nil {
return "", err
}
//Insert into database
stmt, err := db.PreparedQuery("INSERT INTO users (id, password, role, firstName, lastName, phone, email, created) VALUES(?,?,?,?,?,?,?,?)")
if err != nil {
return "", err
}
_, err = stmt.Query(account.ID, account.Password, account.Role, account.FirstName, account.LastName, account.Phone, account.Email, account.Created)
if err != nil {
return "", err
}
stmt.Close()
return "", nil
}
//DeleteAccount - deletes account from DB
func (dao AccountDAO) DeleteAccount(account *types.Account, db *db.MySQL) error {
stmt, err := db.PreparedQuery("DELETE FROM users WHERE id = ?")
if err != nil {
return err
}
_, err = stmt.Query(account.ID)
if err != nil {
return err
}
stmt.Close()
return nil
}
//GetAccountByEmail - returns an account by email
func (dao AccountDAO) GetAccountByEmail(email string, db *db.MySQL) (*types.Account, error) {
stmt, err := db.PreparedQuery("SELECT * FROM users WHERE email = ?")
if err != nil {
return nil, err
}
rows, err := stmt.Query(email)
if err != nil {
return nil, err
}
stmt.Close()
defer rows.Close()
for rows.Next() {
account := types.Account{}
err = sqlstruct.Scan(&account, rows)
if err != nil {
return nil, err
}
return &account, nil
}
return nil, nil
}
//GetAccountByID - returns an account by ID
func (dao AccountDAO) GetAccountByID(id string, db *db.MySQL) (*types.Account, error) {
stmt, err := db.PreparedQuery("SELECT * FROM users WHERE id = ?")
if err != nil {
return nil, err
}
rows, err := stmt.Query(id)
if err != nil {
return nil, err
}
stmt.Close()
defer rows.Close()
for rows.Next() {
account := types.Account{}
err = sqlstruct.Scan(&account, rows)
if err != nil {
return nil, err
}
return &account, nil
}
return nil, nil
}
//GetAccounts - returns all accounts with the role given
func (dao AccountDAO) GetAccounts(roles []int, db *db.MySQL) (*[]types.Account, error) {
if len(roles) <= 0 {
return nil, errors.New("Roles array is empty")
}
query := "SELECT * FROM users WHERE role = '" + strconv.Itoa(roles[0]) + "'"
for i, r := range roles {
if i == 0 {
continue
}
query += " OR role = '" + strconv.Itoa(r) + "'"
}
//If the first role is 0, then we get all accounts
if roles[0] == 0 {
query = "SELECT * FROM users"
}
rows, err := db.SimpleQuery(query + " ORDER BY firstName ASC")
if err != nil {
return nil, err
}
accounts := []types.Account{}
defer rows.Close()
for rows.Next() {
account := types.Account{}
err := sqlstruct.Scan(&account, rows)
if err != nil {
//fmt.Println(err) -> fails to convert NULL to datatype
}
account.HideImportant()
account.GetAccountPermissions()
accounts = append(accounts, account)
}
return &accounts, nil
}
//UpdateSettings - updates the requesting accounts settings
func (dao AccountDAO) UpdateSettings(updatedAccount *types.Account, id string, db *db.MySQL) (string, error) {
if err := updatedAccount.CheckName(); err != nil {
return err.Error(), nil
}
if err := updatedAccount.CheckPhone(); err != nil {
return err.Error(), nil
}
stmt, err := db.PreparedQuery("UPDATE users SET firstName = ?, lastName = ?, phone = ? WHERE id = ?")
if err != nil {
return "", err
}
_, err = stmt.Query(updatedAccount.FirstName, updatedAccount.LastName, updatedAccount.Phone, id)
if err != nil {
return "", err
}
stmt.Close()
return "", nil
}
//UpdateAccount - updates the another users account settings
func (dao AccountDAO) UpdateAccount(updatedAccount *types.Account, db *db.MySQL) (string, error) {
if err := updatedAccount.CheckPhone(); err != nil {
return err.Error(), nil
}
if err := updatedAccount.CheckEmail(); err != nil {
return err.Error(), nil
}
//Check if account details already exist with another account
isDuplicate, err := dao.CheckDuplicates(updatedAccount.ID, updatedAccount.Email, db)
if err != nil {
return "", err
}
if isDuplicate != "" {
return isDuplicate, nil
}
stmt, err := db.PreparedQuery("UPDATE users SET firstName = ?, lastName = ?, email = ?, phone = ?, role = ? WHERE id = ?")
if err != nil {
return "", err
}
_, err = stmt.Query(updatedAccount.FirstName, updatedAccount.LastName, updatedAccount.Email, updatedAccount.Phone, updatedAccount.Role, updatedAccount.ID)
if err != nil {
return "", err
}
stmt.Close()
return "", nil
}
//ChangeAccountPassword - updates the requesting accounts password
func (dao AccountDAO) ChangeAccountPassword(account *types.Account, passwordRequest *types.UpdateAccountPassword, db *db.MySQL) (string, error) {
//Set the new password
account.Password = passwordRequest.NewPassword
//Check the password
if err := account.CheckPassword(); err != nil {
return err.Error(), nil
}
//Hash password
hash, err := utils.HashPassword(account.Password)
if err != nil {
return "", err
}
account.Password = hash
stmt, err := db.PreparedQuery("UPDATE users SET password = ? WHERE id = ?")
if err != nil {
return "", err
}
_, err = stmt.Query(account.Password, account.ID)
if err != nil {
return "", err
}
stmt.Close()
return "", nil
}
|
package noolite
import (
"errors"
"reflect"
"unsafe"
)
type Response struct {
st byte
Mode byte
Ctr byte
Togl byte
Ch byte
Cmd byte
Fmt byte
D0 byte
D1 byte
D2 byte
D3 byte
ID0 byte
ID1 byte
ID2 byte
ID3 byte
crc byte
sp byte
}
var (
ErrWrongST = errors.New("wrong st")
ErrWrongSP = errors.New("wrong sp")
ErrWrongCRC = errors.New("wrong crc")
)
func (r Response) validate() error {
if r.st != 173 {
return ErrWrongST
}
if r.sp != 174 {
return ErrWrongSP
}
crc := r.st + r.Mode + r.Ctr + r.Togl + r.Ch + r.Cmd + r.Fmt
crc += r.D0 + r.D1 + r.D2 + r.D3 + r.ID0 + r.ID1 + r.ID2 + r.ID3
if r.crc != crc {
return ErrWrongCRC
}
return nil
}
func bytesToResponse(raw []byte) (*Response, error) {
if len(raw) != 17 {
return nil, errors.New("short response")
}
sh := (*reflect.SliceHeader)(unsafe.Pointer(&raw))
r := (*Response)(unsafe.Pointer(sh.Data))
err := r.validate()
if err != nil {
return nil, err
}
return r, nil
}
|
package commands
import "github.com/genevieve/leftovers/app"
type Delete struct {
leftovers leftovers
}
func NewDelete(l leftovers) Delete {
return Delete{
leftovers: l,
}
}
func (d Delete) Execute(o app.Options) error {
if o.Type == "" {
return d.leftovers.Delete(o.Filter, o.RegexFiltered)
}
return d.leftovers.DeleteByType(o.Filter, o.Type, o.RegexFiltered)
}
|
package p_00101_00200
// 153. Find Minimum in Rotated Sorted Array, https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
func findMin(nums []int) int {
lo, hi := 0, len(nums)-1
for lo < hi {
mid := lo + (hi-lo)/2
if nums[mid] > nums[hi] {
lo = mid + 1
} else {
hi = mid
}
}
return nums[lo]
}
|
/*
Copyright © 2021 Damien Coraboeuf <damien.coraboeuf@nemerosa.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"github.com/spf13/cobra"
client "ontrack-cli/client"
config "ontrack-cli/config"
)
// validateCHMLCmd represents the validateCHML command
var validateCHMLCmd = &cobra.Command{
Use: "chml",
Short: "Validation with CHML data",
Long: `Validation with CHML data.
For example:
ontrack-cli validate -p PROJECT -b BRANCH -n BUILD -v VALIDATION chml --critical 1 --high 2
`,
RunE: func(cmd *cobra.Command, args []string) error {
project, err := cmd.Flags().GetString("project")
if err != nil {
return err
}
branch, err := cmd.Flags().GetString("branch")
if err != nil {
return err
}
branch = NormalizeBranchName(branch)
build, err := cmd.Flags().GetString("build")
if err != nil {
return err
}
validation, err := cmd.Flags().GetString("validation")
if err != nil {
return err
}
description, err := cmd.Flags().GetString("description")
if err != nil {
return err
}
critical, err := cmd.Flags().GetInt("critical")
if err != nil {
return err
}
high, err := cmd.Flags().GetInt("high")
if err != nil {
return err
}
medium, err := cmd.Flags().GetInt("medium")
if err != nil {
return err
}
low, err := cmd.Flags().GetInt("low")
if err != nil {
return err
}
runInfo, err := GetRunInfo(cmd)
if err != nil {
return err
}
// Get the configuration
cfg, err := config.GetSelectedConfiguration()
if err != nil {
return err
}
// Mutation payload
var payload struct {
ValidateBuildWithCHML struct {
Errors []struct {
Message string
}
}
}
// Runs the mutation
if err := client.GraphQLCall(cfg, `
mutation ValidateBuildWithCHML(
$project: String!,
$branch: String!,
$build: String!,
$validationStamp: String!,
$description: String!,
$runInfo: RunInfoInput,
$critical: Int!,
$high: Int!,
$medium: Int!,
$low: Int!
) {
validateBuildWithCHML(input: {
project: $project,
branch: $branch,
build: $build,
validation: $validationStamp,
description: $description,
runInfo: $runInfo,
critical: $critical,
high: $high,
medium: $medium,
low: $low
}) {
errors {
message
}
}
}
`, map[string]interface{}{
"project": project,
"branch": branch,
"build": build,
"validationStamp": validation,
"description": description,
"runInfo": runInfo,
"critical": critical,
"high": high,
"medium": medium,
"low": low,
}, &payload); err != nil {
return err
}
// Checks for errors
if err := client.CheckDataErrors(payload.ValidateBuildWithCHML.Errors); err != nil {
return err
}
// OK
return nil
},
}
func init() {
validateCmd.AddCommand(validateCHMLCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// validateCHMLCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
validateCHMLCmd.Flags().Int("critical", 0, "Number of critical issues")
validateCHMLCmd.Flags().Int("high", 0, "Number of high issues")
validateCHMLCmd.Flags().Int("medium", 0, "Number of medium issues")
validateCHMLCmd.Flags().Int("low", 0, "Number of low issues")
// Run info arguments
InitRunInfoCommandFlags(validateCHMLCmd)
}
|
package provider
import (
"github.com/fnbk/pim/app/model"
)
type ProductProvider struct {
Products []model.Product
}
func (s *ProductProvider) ProductIDs() []string {
IDs := []string{}
for _, p := range s.Products {
IDs = append(IDs, p.ID)
}
return IDs
}
func (s *ProductProvider) GetProduct(id string) *model.Product {
for _, p := range s.Products {
if p.ID == id {
return &p
}
}
return &model.Product{}
}
|
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package stacktrace
import (
"regexp"
)
// Matcher is a predicate for stack entries.
type Matcher func(Entry) bool
// Filter returns a filtered set of stack entries.
type Filter func([]Entry) []Entry
// MatchPackage returns a predicate that matches the specified package by
// regular expression.
func MatchPackage(pkg string) Matcher {
re := regexp.MustCompile(pkg)
return func(entry Entry) bool {
return re.MatchString(entry.Function.Package)
}
}
// MatchFunction returns a predicate that matches the specified function by
// regular expression.
func MatchFunction(fun string) Matcher {
re := regexp.MustCompile(fun)
return func(entry Entry) bool {
return re.MatchString(entry.Function.Name)
}
}
// Filter returns a new capture filtered by f.
func (c Callstack) Filter(f ...Filter) Callstack {
entries := And(f...)(c.Entries())
out := make(Callstack, len(entries))
for i, e := range entries {
out[i] = e.PC
}
return out
}
// And returns a filter where all of the filters need to pass.
func And(filters ...Filter) Filter {
return func(entries []Entry) []Entry {
for _, f := range filters {
entries = f(entries)
}
return entries
}
}
// Trim returns a filter combining the TrimTop and TrimBottom filters with m.
func Trim(m Matcher) Filter {
return And(TrimTop(m), TrimBottom(m))
}
// TrimTop returns a filter that removes all the deepest entries that doesn't
// satisfy m.
func TrimTop(m Matcher) Filter {
return func(entries []Entry) []Entry {
for i, e := range entries {
if m(e) {
return entries[i:]
}
}
return []Entry{}
}
}
// TrimBottom returns a filter that removes all the shallowest entries that
// doesn't satisfy m.
func TrimBottom(m Matcher) Filter {
return func(entries []Entry) []Entry {
for i := len(entries) - 1; i >= 0; i-- {
if m(entries[i]) {
return entries[:i+1]
}
}
return []Entry{}
}
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package meta
import (
"context"
"strconv"
"time"
"chromiumos/tast/local/shill"
"chromiumos/tast/testing"
)
var (
sleepDuration = testing.RegisterVarString(
"meta.LocalDisableNetwork.SleepDuration",
"180",
"The duration of the sleep in seconds")
)
func init() {
testing.AddTest(&testing.Test{
Func: LocalDisableNetwork,
Desc: "Disable network temporary and then reenable it",
Contacts: []string{"tast-owners@google.com", "seewaifu@google.com"},
BugComponent: "b:1034625",
Timeout: time.Minute * 4,
})
}
// LocalDisableNetwork will disable the network, sleep for a number of seconds
// according the runtime variable meta.LocalDisableNetwork.SleepDuration, and
// reenable the network at the end.
func LocalDisableNetwork(ctx context.Context, s *testing.State) {
manager, err := shill.NewManager(ctx)
if err != nil {
s.Fatal("Failed creating shill manager proxy: ", err)
}
ethEnabled, err := manager.IsEnabled(ctx, shill.TechnologyEthernet)
if err != nil {
s.Fatal("Failed to check if ethernet is enabled: ", err)
}
if ethEnabled {
ethEnableFunc, err := manager.DisableTechnologyForTesting(ctx, shill.TechnologyEthernet)
if err != nil {
s.Fatal("Failed to disable ethernet: ", err)
}
s.Log("Ethernet has been disabled")
defer func() {
ethEnableFunc(ctx)
s.Log("Ethernet has been re-enabled")
}()
}
wifiEnabled, err := manager.IsEnabled(ctx, shill.TechnologyWifi)
if err != nil {
s.Fatal("Failed to check if wifi is enabled: ", err)
}
if wifiEnabled {
wifiEnableFunc, err := manager.DisableTechnologyForTesting(ctx, shill.TechnologyWifi)
if err != nil {
s.Fatal("Failed to disable wifi: ", err)
}
s.Log("Wifi has been disabled")
defer func() {
wifiEnableFunc(ctx)
s.Log("Wifi has been re-enabled")
}()
}
sec, err := strconv.Atoi(sleepDuration.Value())
if err != nil {
s.Fatalf("Bad value %v is set for variable %v: %v", sleepDuration.Value(), sleepDuration.Name(), err)
}
s.Logf("Sleeping for %d seconds", sec)
testing.Sleep(ctx, time.Duration(sec)*time.Second)
}
|
/*
Copyright 2019 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package manifest
import (
"regexp"
"github.com/segmentio/encoding/json"
)
type GroupKindSelector interface {
Matches(group, kind string) bool
}
type ResourceSelectorList struct {
Selectors []WildcardGroupKind `json:"selectors"`
}
type WildcardGroupKind struct {
Group *regexp.Regexp `json:"group"`
Kind *regexp.Regexp `json:"kind"`
}
func (w *WildcardGroupKind) UnmarshalJSON(value []byte) error {
var v map[string]interface{}
err := json.Unmarshal(value, &v)
if err != nil {
return err
}
if vv, ok := v["group"]; ok {
w.Group = regexp.MustCompile(vv.(string))
}
if vv, ok := v["kind"]; ok {
w.Kind = regexp.MustCompile(vv.(string))
}
return nil
}
func (w *WildcardGroupKind) Matches(group, kind string) bool {
return (w.Group == nil || w.Group.Match([]byte(group))) && (w.Kind == nil || w.Kind.Match([]byte(kind)))
}
// ConfigConnectorResourceSelector provides a resource selector for Google Cloud Config Connector resources
// See https://cloud.google.com/config-connector/docs/overview
var ConfigConnectorResourceSelector = []GroupKindSelector{
// add preliminary support for config connector services; group name is currently in flux
&WildcardGroupKind{Group: regexp.MustCompile(`([[:alpha:]]+\.)+cnrm\.cloud\.google\.com`)},
}
|
package LeetCode
func Code105() {
headTree := InitTree()
headTree = &TreeNode{3, nil, nil}
headTree.Left = &TreeNode{9, nil, nil}
headTree.Right = &TreeNode{20, nil, nil}
headTree.Right.Left = &TreeNode{15, nil, nil}
headTree.Right.Right = &TreeNode{7, nil, nil}
levelOrder(headTree)
//fmt.Println("leetcode 102 ")
//nums := []int{2, 3, 4, 6, 8}
//target := 8
//fmt.Println(twoSum(nums, target))
}
/**
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
*/
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) < 1 {
return nil
}
root := &TreeNode{}
for i := 0; i < len(preorder); i++ {
if preorder[0] == inorder[i] {
root.Left = buildTree(preorder[1:i+1], inorder[0:i])
root.Right = buildTree(preorder[i+2:], inorder[i+1:])
}
}
return root
}
|
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package owner_test
import (
"crypto/ed25519"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/bitmark-inc/bitmarkd/account"
"github.com/bitmark-inc/bitmarkd/chain"
"github.com/bitmark-inc/bitmarkd/merkle"
"github.com/bitmark-inc/bitmarkd/mode"
"github.com/bitmark-inc/bitmarkd/ownership"
"github.com/bitmark-inc/bitmarkd/reservoir"
"github.com/bitmark-inc/bitmarkd/rpc/fixtures"
"github.com/bitmark-inc/bitmarkd/rpc/mocks"
"github.com/bitmark-inc/bitmarkd/rpc/owner"
"github.com/bitmark-inc/bitmarkd/transactionrecord"
"github.com/bitmark-inc/logger"
)
func TestOwnerBitmarks(t *testing.T) {
fixtures.SetupTestLogger()
defer fixtures.TeardownTestLogger()
mode.Initialise(chain.Testing)
defer mode.Finalise()
ctl := gomock.NewController(t)
defer ctl.Finish()
tr := mocks.NewMockHandle(ctl)
a := mocks.NewMockHandle(ctl)
os := mocks.NewMockOwnership(ctl)
o := owner.New(
logger.New(fixtures.LogCategory),
reservoir.Handles{
Assets: a,
Transactions: tr,
},
os,
)
acc := account.Account{
AccountInterface: &account.ED25519Account{
Test: true,
PublicKey: fixtures.IssuerPublicKey,
},
}
arg := owner.BitmarksArguments{
Owner: &acc,
Start: 5,
Count: 10,
}
n := uint64(3)
ass := transactionrecord.NewAssetIdentifier([]byte{1, 2, 3, 4})
r := ownership.Record{
N: 1,
TxId: merkle.Digest{},
IssueTxId: merkle.Digest{},
Item: ownership.OwnedAsset,
AssetId: &ass,
BlockNumber: &n,
}
ad := transactionrecord.AssetData{
Name: "test",
Fingerprint: "fingerprint",
Metadata: "owner\x00me",
Registrant: &acc,
Signature: nil,
}
packed, _ := ad.Pack(&acc)
ad.Signature = ed25519.Sign(fixtures.IssuerPrivateKey, packed)
packed, _ = ad.Pack(&acc)
os.EXPECT().ListBitmarksFor(arg.Owner, arg.Start, arg.Count).Return([]ownership.Record{r}, nil).Times(1)
tr.EXPECT().GetNB(r.TxId[:]).Return(uint64(1), packed).Times(1)
a.EXPECT().GetNB(r.AssetId[:]).Return(uint64(1), packed).Times(1)
var reply owner.BitmarksReply
err := o.Bitmarks(&arg, &reply)
assert.Nil(t, err, "wrong Bitmarks")
assert.Equal(t, r.N+1, reply.Next, "wrong next")
assert.Equal(t, 1, len(reply.Data), "wrong record count")
assert.Equal(t, r, reply.Data[0], "wrong asset")
assert.Equal(t, 2, len(reply.Tx), "wrong tx count")
assert.Equal(t, ad, *reply.Tx[r.TxId.String()].Data.(*transactionrecord.AssetData), "wrong first record")
assert.Equal(t, ad, *reply.Tx[r.TxId.String()].Data.(*transactionrecord.AssetData))
}
|
package card
import (
"bank/pkg/bank/types"
"fmt"
)
func ExampleWithdraw_positive() {
result := Withdraw(types.Card{Balance: 20000_00, Active: true}, 10000_00)
fmt.Println(result.Balance)
// Output:
// 1000000
}
func ExampleWithdraw_noMoney() {
result := Withdraw(types.Card{Balance: 1000, Active: true}, 1500)
fmt.Println(result.Balance)
// Output:
// 1000
}
func ExampleWithdraw_inactive() {
result := Withdraw(types.Card{Balance: 1000, Active: false}, 1500)
fmt.Println(result.Balance)
// Output:
// 1000
}
func ExampleWithdraw_limit() {
result := Withdraw(types.Card{Balance: 600000_00, Active: true}, 21000_00)
fmt.Println(result.Balance)
// Output:
// 60000000
}
func ExampleDeposit_normal() {
card := types.Card{
Balance: 20_000_00,
Active: true,
}
var amount types.Money = 10_000_00
Deposit(&card, amount)
fmt.Println(card.Balance)
// Output:
// 3000000
}
func ExampleDeposit_inactive() {
card := types.Card{
Balance: 20_000_00,
Active: false,
}
var amount types.Money = 10_000_00
Deposit(&card, amount)
fmt.Println(card.Balance)
// Output:
// 2000000
}
func ExampleDeposit_overDepositLimit() {
card := types.Card{
Balance: 20_000_00,
Active: false,
}
var amount types.Money = 50_000_01
Deposit(&card, amount)
fmt.Println(card.Balance)
// Output:
// 2000000
}
func ExampleDeposit_negativeBalance() {
card := types.Card{
Balance: -20_000_00,
Active: true,
}
var amount types.Money = 50_000_00
Deposit(&card, amount)
fmt.Println(card.Balance)
// Output:
// 3000000
}
func ExampleAddBonus_positive() {
card := types.Card{
Balance: 20_000_00,
MinBalance: 10_000_00,
Active: true,
}
oldBalance := card.Balance
AddBonus(&card, 3, 30, 365)
newBalance := card.Balance
fmt.Println(newBalance - oldBalance)
// Output:
// 2465
}
func ExampleAddBonus_inactive() {
card := types.Card{
Balance: 20_000_00,
MinBalance: 10_000_00,
Active: false,
}
oldBalance := card.Balance
AddBonus(&card, 3, 30, 365)
newBalance := card.Balance
fmt.Println(newBalance - oldBalance)
// Output:
// 0
}
func ExampleAddBonus_negativeBalance() {
card := types.Card{
Balance: -20_000_00,
MinBalance: 10_000_00,
Active: true,
}
oldBalance := card.Balance
AddBonus(&card, 3, 30, 365)
newBalance := card.Balance
fmt.Println(newBalance - oldBalance)
// Output:
// 0
}
func ExampleAddBonus_overBonusLimit() {
card := types.Card{
Balance: 20_000_00,
MinBalance: 25_000_00,
Active: true,
}
oldBalance := card.Balance
AddBonus(&card, 3, 30, 365)
newBalance := card.Balance
fmt.Println(newBalance - oldBalance)
// Output:
// 6164
}
func ExampleAddBonus_equalBonusLimit() {
card := types.Card{
Balance: 20_000_00,
MinBalance: 20_277_78,
Active: true,
}
oldBalance := card.Balance
AddBonus(&card, 3, 30, 365)
newBalance := card.Balance
fmt.Println(newBalance - oldBalance)
// Output:
// 5000
}
func ExampleTotal_positive() {
cards := []types.Card{
{
Balance: 10_000_00,
Active: true,
},
{
Balance: 10_000_00,
Active: true,
},
{
Balance: 10_000_00,
Active: true,
},
}
fmt.Println(Total(cards))
// Output: 3000000
}
func ExampleTotal_negativeBalance() {
cards := []types.Card{
{
Balance: 10_000_00,
Active: true,
},
{
Balance: -10_000_00,
Active: true,
},
{
Balance: 10_000_00,
Active: true,
},
}
fmt.Println(Total(cards))
// Output: 2000000
}
func ExampleTotal_inactive() {
cards := []types.Card{
{
Balance: 10_000_00,
Active: false,
},
{
Balance: 10_000_00,
Active: false,
},
{
Balance: 10_000_00,
Active: false,
},
}
fmt.Println(Total(cards))
// Output: 0
}
func ExamplePaymentSources() {
cards := []types.Card{
{
PAN: "card1",
Balance: 10_000_00,
Active: true,
},
{
PAN: "card2",
Balance: -10_000_00,
Active: true,
},
{
PAN: "card3",
Balance: 10_000_00,
Active: true,
},
{
PAN: "card4",
Balance: 10_000_00,
Active: false,
},
}
pss := PaymentSources(cards)
for _, ps := range pss {
fmt.Println(ps.Number)
}
// Output:
// card1
// card3
}
|
// 关闭 一个通道意味着不能再向这个通道发送值了。 该特性可以向通道的接收方传达工作已经完成的信息
package main
import "fmt"
func main() {
// 在这个例子中,我们将使用一个 jobs 通道,将工作内容, 从 main() 协程传递到一个工作协程中
// 当我们没有更多的任务传递给工作协程时,我们将 close 这个 jobs 通道
jobs := make(chan int, 5)
done := make(chan bool)
// 这是工作协程。
go func() {
for {
// 使用 j, more := <- jobs 循环的从 jobs 接收数据
j, more := <-jobs
// 根据接收的第二个值,如果 jobs 已经关闭了, 并且通道中所有的值都已经接收完毕,那么 more 的值将是 false
if more {
fmt.Println("received job: ", j)
} else {
// 当我们完成所有的任务时,会使用这个特性通过 done 通道通知 main 协程
fmt.Println("received all jobs")
done <- true
return
}
}
}()
// 使用 jobs 发送 3 个任务到工作协程中,然后关闭 jobs
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job: ", j)
}
close(jobs)
fmt.Println("sent all jobs")
// 使用前面学到的通道同步方法等待任务结束
<-done
}
|
//go:generate gen-static-data-go
//go:generate protoc --enum-go_out=. enum.proto global.proto
package sd
import "mlgs/src/conf"
func init() {
success := LoadAll(conf.Server.XlsxPath)
if success != true {
panic("sd LoadAll faild")
}
success = AfterLoadAll(conf.Server.XlsxPath)
if success != true {
panic("sd AfterLoadAll faild")
}
}
|
package deque
import (
"reflect"
"testing"
)
func TestDeque(t *testing.T) {
q := &Deque{}
q.EnqueueBack(12) // 12
q.EnqueueFront(1) // 1 12
q.EnqueueBack(23) // 1 12 23
q.EnqueueFront(908) // 908 1 12 23
a := []int{908, 1, 12, 23}
b := []int{}
for v := range q.Traverse() {
b = append(b, v)
}
if !reflect.DeepEqual(a, b) {
t.Errorf("a %v is not equal to b %v", a, b)
}
q.DequeueFront() // 1 12 23
q.DequeueBack() // 1 12
a = []int{1, 12}
b = []int{}
for v := range q.Traverse() {
b = append(b, v)
}
if !reflect.DeepEqual(a, b) {
t.Errorf("a %v is not equal to b %v", a, b)
}
if v, _ := q.PeekFront(); v != 1 {
t.Errorf("q.PeekFront() is not equal to %d, got: %d", 1, v)
}
if v, _ := q.PeekBack(); v != 12 {
t.Errorf("q.PeekFront() is not equal to %d, got: %d", 12, v)
}
}
|
package entity
import (
DB "rnl360-api/database"
"rnl360-api/models"
)
func GetAllCommunication(communicationModel *[]models.CommunicationModel) (err error) {
if err = DB.GetDB().Where("status = ?", 1).Order("id DESC").Find(&communicationModel).Error; err != nil {
return err
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.