text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
"time"
"github.com/rwcarlsen/money/set"
)
func main() {
simulateLife()
//simulateMortgage()
}
func simulateLife() {
now := time.Now()
// income
salary := set.PieceWise(set.Month,
set.Uniform(now, set.Month, 12 * 3, 75e3 / 12),
set.Uniform(now, set.Month, 12 * 4, 93e3 / 12),
set.Uniform(now, set.Month, 12 * 9, 112e3 / 12),
set.Uniform(now, set.Month, 12 * 9, 136e3 / 12),
set.Uniform(now, set.Month, 12 * 20, 40e3 / 12),
)
// expenses
incomeTax := set.Mult(salary, -0.4)
propertyTax := set.Uniform(now, set.Year, 100, 3000)
gas := set.PieceWise(set.Month,
set.Uniform(now, set.Month, 24, 150),
set.Uniform(now, set.Month, 1200, 350),
)
food := set.PieceWise(set.Month,
set.Uniform(now, set.Month, 12 * 4, 200),
set.Uniform(now, set.Month, 12 * 4, 400),
set.Uniform(now, set.Month, 12 * 4, 600),
set.Uniform(now, set.Month, 12 * 4, 400),
set.Uniform(now, set.Month, 12 * 50, 200),
)
misc := set.PieceWise(set.Month,
set.Uniform(now, set.Month, 12 * 25, 500),
set.Uniform(now, set.Month, 12 * 100, 1000),
)
// allocations
net := set.Cumulative(set.Append(salary, gas, food, misc, incomeTax, propertyTax))
investments := set.Mimic(net, func(e set.Event) float64 {
return max(0, e.Amount - 25000)
})
savings := set.Consolidate(net, set.Mult(investments, -1))
// interest
interest := set.Compound(investments, 0.03, set.Year)
netWorth := set.Consolidate(net, set.Cumulative(interest))
_, _= savings, netWorth
//fmt.Printf("salary: \n%v", salary)
//fmt.Printf("incomeTax: \n%v", incomeTax)
//fmt.Printf("gas: \n%v", gas)
//fmt.Printf("food: \n%v", food)
//fmt.Printf("misc: \n%v", misc)
fmt.Printf("savings: \n%v", savings)
//fmt.Printf("investments: \n%v", investments)
//fmt.Printf("interest: \n%v", interest)
//fmt.Printf("netWorth: \n%v", netWorth)
//fmt.Printf("tot interest: %v\n", set.Sum(interest))
}
func simulateMortgage() {
mortgage := set.Uniform(time.Now(), set.Month, 500, 150000)
payments := set.Mimic(mortgage, func(set.Event)float64{return -10000})
net := set.Consolidate(mortgage, set.Cumulative(payments))
interest := set.Compound(net, 0.05, set.Year)
fracInterest := set.Mult(interest, 1.0/1200)
balance := set.TrimBelow(set.Consolidate(net, set.Cumulative(interest)), 0)
fmt.Printf("net: \n%v", net[:len(balance)])
fmt.Printf("interest: \n%v", interest[:len(balance)])
fmt.Printf("fracInterest: \n%v", fracInterest[:len(balance)])
fmt.Printf("balance: \n%v", balance)
}
func max(x, y float64) float64 {
if x > y {
return x
}
return y
}
|
package miner
import (
"fmt"
abi "github.com/filecoin-project/go-state-types/abi"
big "github.com/filecoin-project/go-state-types/big"
"github.com/ipfs/go-cid"
mh "github.com/multiformats/go-multihash"
builtin "github.com/filecoin-project/specs-actors/actors/builtin"
. "github.com/filecoin-project/specs-actors/actors/util"
)
// The period over which all a miner's active sectors will be challenged.
var WPoStProvingPeriod = abi.ChainEpoch(builtin.EpochsInDay) // 24 hours
// The duration of a deadline's challenge window, the period before a deadline when the challenge is available.
var WPoStChallengeWindow = abi.ChainEpoch(30 * 60 / builtin.EpochDurationSeconds) // 30 minutes (48 per day)
// The number of non-overlapping PoSt deadlines in each proving period.
const WPoStPeriodDeadlines = uint64(48)
// WPoStMaxChainCommitAge is the maximum distance back that a valid Window PoSt must commit to the current chain.
var WPoStMaxChainCommitAge = WPoStChallengeWindow
func init() {
// Check that the challenge windows divide the proving period evenly.
if WPoStProvingPeriod%WPoStChallengeWindow != 0 {
panic(fmt.Sprintf("incompatible proving period %d and challenge window %d", WPoStProvingPeriod, WPoStChallengeWindow))
}
if abi.ChainEpoch(WPoStPeriodDeadlines)*WPoStChallengeWindow != WPoStProvingPeriod {
panic(fmt.Sprintf("incompatible proving period %d and challenge window %d", WPoStProvingPeriod, WPoStChallengeWindow))
}
}
// The maximum number of sectors that a miner can have simultaneously active.
// This also bounds the number of faults that can be declared, etc.
// TODO raise this number, carefully
// https://github.com/filecoin-project/specs-actors/issues/470
const SectorsMax = 32 << 20 // PARAM_FINISH
// The maximum number of partitions that may be required to be loaded in a single invocation.
// This limits the number of simultaneous fault, recovery, or sector-extension declarations.
// With 48 deadlines (half-hour), 200 partitions per declaration permits loading a full EiB of 32GiB
// sectors with 1 message per epoch within a single half-hour deadline. A miner can of course submit more messages.
const AddressedPartitionsMax = 200
// The maximum number of sector infos that may be required to be loaded in a single invocation.
const AddressedSectorsMax = 10_000
// The maximum number of partitions that may be required to be loaded in a single invocation,
// when all the sector infos for the partitions will be loaded.
func loadPartitionsSectorsMax(partitionSectorCount uint64) uint64 {
return min64(AddressedSectorsMax/partitionSectorCount, AddressedPartitionsMax)
}
// The maximum number of new sectors that may be staged by a miner during a single proving period.
const NewSectorsPerPeriodMax = 128 << 10
// Epochs after which chain state is final.
const ChainFinality = abi.ChainEpoch(900)
var SealedCIDPrefix = cid.Prefix{
Version: 1,
Codec: cid.FilCommitmentSealed,
MhType: mh.POSEIDON_BLS12_381_A1_FC1,
MhLength: 32,
}
// List of proof types which can be used when creating new miner actors
var SupportedProofTypes = map[abi.RegisteredSealProof]struct{}{
abi.RegisteredSealProof_StackedDrg32GiBV1: {},
abi.RegisteredSealProof_StackedDrg64GiBV1: {},
}
// Maximum duration to allow for the sealing process for seal algorithms.
// Dependent on algorithm and sector size
var MaxSealDuration = map[abi.RegisteredSealProof]abi.ChainEpoch{
abi.RegisteredSealProof_StackedDrg32GiBV1: abi.ChainEpoch(10000), // PARAM_FINISH
abi.RegisteredSealProof_StackedDrg2KiBV1: abi.ChainEpoch(10000),
abi.RegisteredSealProof_StackedDrg8MiBV1: abi.ChainEpoch(10000),
abi.RegisteredSealProof_StackedDrg512MiBV1: abi.ChainEpoch(10000),
abi.RegisteredSealProof_StackedDrg64GiBV1: abi.ChainEpoch(10000),
}
// Number of epochs between publishing the precommit and when the challenge for interactive PoRep is drawn
// used to ensure it is not predictable by miner.
var PreCommitChallengeDelay = abi.ChainEpoch(150)
// Lookback from the current epoch for state view for leader elections.
const ElectionLookback = abi.ChainEpoch(1) // PARAM_FINISH
// Lookback from the deadline's challenge window opening from which to sample chain randomness for the challenge seed.
// This lookback exists so that deadline windows can be non-overlapping (which make the programming simpler)
// but without making the miner wait for chain stability before being able to start on PoSt computation.
// The challenge is available this many epochs before the window is actually open to receiving a PoSt.
const WPoStChallengeLookback = abi.ChainEpoch(20)
// Minimum period before a deadline's challenge window opens that a fault must be declared for that deadline.
// This lookback must not be less than WPoStChallengeLookback lest a malicious miner be able to selectively declare
// faults after learning the challenge value.
const FaultDeclarationCutoff = WPoStChallengeLookback + 50
// The maximum age of a fault before the sector is terminated.
var FaultMaxAge = WPoStProvingPeriod * 14
// Staging period for a miner worker key change.
// Finality is a harsh delay for a miner who has lost their worker key, as the miner will miss Window PoSts until
// it can be changed. It's the only safe value, though. We may implement a mitigation mechanism such as a second
// key or allowing the owner account to submit PoSts while a key change is pending.
const WorkerKeyChangeDelay = ChainFinality
// Minimum number of epochs past the current epoch a sector may be set to expire.
const MinSectorExpiration = 90 * builtin.EpochsInDay
// Maximum number of epochs past the current epoch a sector may be set to expire.
// The actual maximum extension will be the minimum of CurrEpoch + MaximumSectorExpirationExtension
// and sector.ActivationEpoch+sealProof.SectorMaximumLifetime()
const MaxSectorExpirationExtension = 270 * builtin.EpochsInDay
// Ratio of sector size to maximum deals per sector.
// The maximum number of deals is the sector size divided by this number (2^27)
// which limits 32GiB sectors to 256 deals and 64GiB sectors to 512
const DealLimitDenominator = 134217728
// DealWeight and VerifiedDealWeight are spacetime occupied by regular deals and verified deals in a sector.
// Sum of DealWeight and VerifiedDealWeight should be less than or equal to total SpaceTime of a sector.
// Sectors full of VerifiedDeals will have a SectorQuality of VerifiedDealWeightMultiplier/QualityBaseMultiplier.
// Sectors full of Deals will have a SectorQuality of DealWeightMultiplier/QualityBaseMultiplier.
// Sectors with neither will have a SectorQuality of QualityBaseMultiplier/QualityBaseMultiplier.
// SectorQuality of a sector is a weighted average of multipliers based on their propotions.
func QualityForWeight(size abi.SectorSize, duration abi.ChainEpoch, dealWeight, verifiedWeight abi.DealWeight) abi.SectorQuality {
sectorSpaceTime := big.Mul(big.NewIntUnsigned(uint64(size)), big.NewInt(int64(duration)))
totalDealSpaceTime := big.Add(dealWeight, verifiedWeight)
Assert(sectorSpaceTime.GreaterThanEqual(totalDealSpaceTime))
weightedBaseSpaceTime := big.Mul(big.Sub(sectorSpaceTime, totalDealSpaceTime), builtin.QualityBaseMultiplier)
weightedDealSpaceTime := big.Mul(dealWeight, builtin.DealWeightMultiplier)
weightedVerifiedSpaceTime := big.Mul(verifiedWeight, builtin.VerifiedDealWeightMultiplier)
weightedSumSpaceTime := big.Sum(weightedBaseSpaceTime, weightedDealSpaceTime, weightedVerifiedSpaceTime)
scaledUpWeightedSumSpaceTime := big.Lsh(weightedSumSpaceTime, builtin.SectorQualityPrecision)
return big.Div(big.Div(scaledUpWeightedSumSpaceTime, sectorSpaceTime), builtin.QualityBaseMultiplier)
}
// Returns the power for a sector size and weight.
func QAPowerForWeight(size abi.SectorSize, duration abi.ChainEpoch, dealWeight, verifiedWeight abi.DealWeight) abi.StoragePower {
quality := QualityForWeight(size, duration, dealWeight, verifiedWeight)
return big.Rsh(big.Mul(big.NewIntUnsigned(uint64(size)), quality), builtin.SectorQualityPrecision)
}
// Returns the quality-adjusted power for a sector.
func QAPowerForSector(size abi.SectorSize, sector *SectorOnChainInfo) abi.StoragePower {
duration := sector.Expiration - sector.Activation
return QAPowerForWeight(size, duration, sector.DealWeight, sector.VerifiedDealWeight)
}
// Determine maximum number of deal miner's sector can hold
func dealPerSectorLimit(size abi.SectorSize) uint64 {
return max64(256, uint64(size/DealLimitDenominator))
}
type BigFrac struct {
numerator big.Int
denominator big.Int
}
var consensusFaultReporterInitialShare = BigFrac{
// PARAM_FINISH
numerator: big.NewInt(1),
denominator: big.NewInt(1000),
}
var consensusFaultReporterShareGrowthRate = BigFrac{
// PARAM_FINISH
numerator: big.NewInt(101251),
denominator: big.NewInt(100000),
}
// Specification for a linear vesting schedule.
type VestSpec struct {
InitialDelay abi.ChainEpoch // Delay before any amount starts vesting.
VestPeriod abi.ChainEpoch // Period over which the total should vest, after the initial delay.
StepDuration abi.ChainEpoch // Duration between successive incremental vests (independent of vesting period).
Quantization abi.ChainEpoch // Maximum precision of vesting table (limits cardinality of table).
}
var RewardVestingSpecV0 = VestSpec{
InitialDelay: abi.ChainEpoch(20 * builtin.EpochsInDay), // PARAM_FINISH
VestPeriod: abi.ChainEpoch(90 * builtin.EpochsInDay), // PARAM_FINISH
StepDuration: abi.ChainEpoch(1 * builtin.EpochsInDay), // PARAM_FINISH
Quantization: 12 * builtin.EpochsInHour, // PARAM_FINISH
}
var RewardVestingSpecV1 = VestSpec{
InitialDelay: abi.ChainEpoch(0), // PARAM_FINISH
VestPeriod: abi.ChainEpoch(90 * builtin.EpochsInDay), // PARAM_FINISH
StepDuration: abi.ChainEpoch(1 * builtin.EpochsInDay), // PARAM_FINISH
Quantization: 12 * builtin.EpochsInHour, // PARAM_FINISH
}
func RewardForConsensusSlashReport(elapsedEpoch abi.ChainEpoch, collateral abi.TokenAmount) abi.TokenAmount {
// PARAM_FINISH
// var growthRate = SLASHER_SHARE_GROWTH_RATE_NUM / SLASHER_SHARE_GROWTH_RATE_DENOM
// var multiplier = growthRate^elapsedEpoch
// var slasherProportion = min(INITIAL_SLASHER_SHARE * multiplier, 1.0)
// return collateral * slasherProportion
// BigInt Operation
// NUM = SLASHER_SHARE_GROWTH_RATE_NUM^elapsedEpoch * INITIAL_SLASHER_SHARE_NUM * collateral
// DENOM = SLASHER_SHARE_GROWTH_RATE_DENOM^elapsedEpoch * INITIAL_SLASHER_SHARE_DENOM
// slasher_amount = min(NUM/DENOM, collateral)
maxReporterShareNum := big.NewInt(1)
maxReporterShareDen := big.NewInt(2)
elapsed := big.NewInt(int64(elapsedEpoch))
slasherShareNumerator := big.Exp(consensusFaultReporterShareGrowthRate.numerator, elapsed)
slasherShareDenominator := big.Exp(consensusFaultReporterShareGrowthRate.denominator, elapsed)
num := big.Mul(big.Mul(slasherShareNumerator, consensusFaultReporterInitialShare.numerator), collateral)
denom := big.Mul(slasherShareDenominator, consensusFaultReporterInitialShare.denominator)
return big.Min(big.Div(num, denom), big.Div(big.Mul(collateral, maxReporterShareNum), maxReporterShareDen))
}
|
package make
import (
"fmt"
)
func test1() {
a := make([]int, 5, 10)
fmt.Printf("a:%v, add: %p, len: %d, cap: %d \n", a, a, len(a), cap(a))
for i := 0; i < 10; i++ {
a = append(a, i)
fmt.Printf("a:%v, add: %p, len: %d, cap: %d \n", a, a, len(a), cap(a))
}
}
func Test() {
test1()
}
|
package main
import (
"context"
"fmt"
)
func main() {
ProcessRequest("Jhone", "a1234")
}
func ProcessRequest(userId, authToken string) {
ctx := context.WithValue(context.Background(), "UserID", userId)
ctx = context.WithValue(ctx, "authToken", authToken)
HandleRequest(ctx)
}
func HandleRequest(ctx context.Context) {
fmt.Println(
ctx.Value("UserID"),
ctx.Value("authToken"),
)
}
|
package service
import (
"github.com/GoGroup/Movie-and-events/model"
"github.com/GoGroup/Movie-and-events/schedule"
)
type ScheduleService struct {
scheduleRepo schedule.ScheduleRepository
}
func NewScheduleService(schRepo schedule.ScheduleRepository) schedule.ScheduleService {
return &ScheduleService{scheduleRepo: schRepo}
}
func (s *ScheduleService) Schedules() ([]model.Schedule, []error) {
schdls, errs := s.scheduleRepo.Schedules()
if len(errs) > 0 {
return nil, errs
}
return schdls, errs
}
func (s *ScheduleService) HallSchedules(id uint, day string) ([]model.Schedule, []error) {
schdls, errs := s.scheduleRepo.HallSchedules(id, day)
if len(errs) > 0 {
return nil, errs
}
return schdls, errs
}
func (s *ScheduleService) StoreSchedule(schedule *model.Schedule) (*model.Schedule, []error) {
schdls, errs := s.scheduleRepo.StoreSchedule(schedule)
if len(errs) > 0 {
return nil, errs
}
return schdls, errs
}
func (ss *ScheduleService) UpdateSchedules(schedule *model.Schedule) (*model.Schedule, []error) {
schdls, errs := ss.scheduleRepo.UpdateSchedules(schedule)
if len(errs) > 0 {
return nil, errs
}
return schdls, errs
}
func (ss *ScheduleService) UpdateSchedulesBooked(schedule *model.Schedule, Amount uint) *model.Schedule {
schdls := ss.scheduleRepo.UpdateSchedulesBooked(schedule, Amount)
return schdls
}
func (ss *ScheduleService) DeleteSchedules(id uint) (*model.Schedule, []error) {
schdls, errs := ss.scheduleRepo.DeleteSchedules(id)
if len(errs) > 0 {
return nil, errs
}
return schdls, errs
}
func (ss *ScheduleService) Schedule(id uint) (*model.Schedule, []error) {
schdls, errs := ss.scheduleRepo.Schedule(id)
if len(errs) > 0 {
return nil, errs
}
return schdls, errs
}
func (ss *ScheduleService) ScheduleHallDay(hallid uint, day string) ([]model.Schedule, []error) {
schdls, errs := ss.scheduleRepo.ScheduleHallDay(hallid, day)
if len(errs) > 0 {
return nil, errs
}
return schdls, errs
}
|
package service
import (
"context"
"fmt"
"sync"
"github.com/go-ocf/cloud/cloud2cloud-connector/events"
"github.com/go-ocf/kit/codec/cbor"
"github.com/go-ocf/kit/codec/json"
coap "github.com/go-ocf/go-coap"
"github.com/go-ocf/sdk/schema/cloud"
"github.com/go-ocf/cqrs/event"
"github.com/go-ocf/cqrs/eventstore"
"github.com/go-ocf/kit/log"
"github.com/go-ocf/kit/net/http"
raCqrs "github.com/go-ocf/cloud/resource-aggregate/cqrs"
raEvents "github.com/go-ocf/cloud/resource-aggregate/cqrs/events"
"github.com/go-ocf/cloud/resource-aggregate/cqrs/notification"
pbRA "github.com/go-ocf/cloud/resource-aggregate/pb"
)
type resourceCtx struct {
lock sync.Mutex
resource *pbRA.Resource
isPublished bool
content *pbRA.ResourceChanged
syncPoolHandler *GoroutinePoolHandler
updateNotificationContainer *notification.UpdateNotificationContainer
}
func newResourceCtx(syncPoolHandler *GoroutinePoolHandler, updateNotificationContainer *notification.UpdateNotificationContainer) func(context.Context) (eventstore.Model, error) {
return func(context.Context) (eventstore.Model, error) {
return &resourceCtx{
syncPoolHandler: syncPoolHandler,
updateNotificationContainer: updateNotificationContainer,
}, nil
}
}
func (m *resourceCtx) cloneLocked() *resourceCtx {
return &resourceCtx{
resource: m.resource,
isPublished: m.isPublished,
content: m.content,
}
}
func (m *resourceCtx) Clone() *resourceCtx {
m.lock.Lock()
defer m.lock.Unlock()
return m.cloneLocked()
}
func (m *resourceCtx) onResourcePublishedLocked(ctx context.Context) error {
err := m.syncPoolHandler.Handle(ctx, Event{
Id: m.resource.GetDeviceId(),
EventType: events.EventType_ResourcesPublished,
DeviceID: m.resource.GetDeviceId(),
Href: m.resource.GetHref(),
Representation: makeLinksRepresentation(events.EventType_ResourcesPublished, []eventstore.Model{m.cloneLocked()}),
})
if err != nil {
err = fmt.Errorf("cannot make action on resource published: %w", err)
}
return err
}
func (m *resourceCtx) onCloudStatusChangedLocked(ctx context.Context) error {
var decoder func(data []byte, v interface{}) error
switch m.content.GetContent().GetContentType() {
case coap.AppCBOR.String(), coap.AppOcfCbor.String():
decoder = cbor.Decode
case coap.AppJSON.String():
decoder = json.Decode
}
if decoder == nil {
return fmt.Errorf("decoder not found")
}
var cloudStatus cloud.Status
err := decoder(m.content.GetContent().GetData(), &cloudStatus)
if err != nil {
return err
}
eventType := events.EventType_DevicesOffline
if cloudStatus.Online {
eventType = events.EventType_DevicesOnline
}
return m.syncPoolHandler.Handle(ctx, Event{
Id: m.resource.GetDeviceId(),
EventType: eventType,
DeviceID: m.resource.GetDeviceId(),
Representation: makeOnlineOfflineRepresentation(m.resource.GetDeviceId()),
})
}
func (m *resourceCtx) onResourceUnpublishedLocked(ctx context.Context) error {
err := m.syncPoolHandler.Handle(ctx, Event{
Id: m.resource.GetDeviceId(),
EventType: events.EventType_ResourcesUnpublished,
DeviceID: m.resource.GetDeviceId(),
Href: m.resource.GetHref(),
Representation: makeLinksRepresentation(events.EventType_ResourcesUnpublished, []eventstore.Model{m.cloneLocked()}),
})
if err != nil {
err = fmt.Errorf("cannot make action on resource unpublished: %w", err)
}
return err
}
func (m *resourceCtx) onResourceChangedLocked(ctx context.Context) error {
var rep interface{}
var err error
eventType := events.EventType_ResourceChanged
if m.content.GetStatus() != pbRA.Status_OK {
eventType = events.EventType_SubscriptionCanceled
} else {
rep, err = unmarshalContent(m.content.GetContent())
if err != nil {
return fmt.Errorf("cannot make action on resource content changed: %w", err)
}
}
err = m.syncPoolHandler.Handle(ctx, Event{
Id: m.resource.GetDeviceId(),
EventType: eventType,
DeviceID: m.resource.GetDeviceId(),
Href: m.resource.GetHref(),
Representation: rep,
})
if err != nil {
err = fmt.Errorf("cannot make action on resource content changed: %w", err)
}
return err
}
func (m *resourceCtx) onProcessedContentUpdatesLocked(updateProcessed []raEvents.ResourceUpdated) {
for _, up := range updateProcessed {
notify := m.updateNotificationContainer.Find(up.AuditContext.CorrelationId)
if notify != nil {
select {
case notify <- up:
default:
log.Debugf("DeviceId: %v, ResourceId: %v: cannot send notification", m.resource.DeviceId, m.resource.Id)
}
}
}
}
func (m *resourceCtx) SnapshotEventType() string {
s := &raEvents.ResourceStateSnapshotTaken{}
return s.SnapshotEventType()
}
func (m *resourceCtx) Handle(ctx context.Context, iter event.Iter) error {
var onResourcePublished, onResourceUnpublished, onResourceChanged bool
processedContentUpdates := make([]raEvents.ResourceUpdated, 0, 128)
m.lock.Lock()
defer m.lock.Unlock()
var anyEventProcessed bool
var deviceID string
var resourceID string
for {
var eu event.EventUnmarshaler
if !iter.Next(ctx, &eu) {
break
}
deviceID = eu.GroupId
resourceID = eu.AggregateId
anyEventProcessed = true
log.Debugf("resourceCtx.Handle: DeviceID: %v, ResourceId: %v, Version: %v, EventType: %v", deviceID, resourceID, eu.Version, eu.EventType)
switch eu.EventType {
case http.ProtobufContentType(&pbRA.ResourceStateSnapshotTaken{}):
var s raEvents.ResourceStateSnapshotTaken
if err := eu.Unmarshal(&s); err != nil {
return err
}
if !m.isPublished {
onResourcePublished = s.IsPublished
onResourceUnpublished = !s.IsPublished
}
if m.content == nil {
onResourceChanged = true
} else {
onResourceChanged = s.GetLatestResourceChange().GetEventMetadata().GetVersion() > m.content.GetEventMetadata().GetVersion()
}
m.content = s.LatestResourceChange
m.resource = s.Resource
m.isPublished = s.IsPublished
case http.ProtobufContentType(&pbRA.ResourcePublished{}):
var s raEvents.ResourcePublished
if err := eu.Unmarshal(&s); err != nil {
return err
}
if !m.isPublished {
onResourcePublished = true
onResourceUnpublished = false
}
m.isPublished = true
m.resource = s.Resource
case http.ProtobufContentType(&pbRA.ResourceUnpublished{}):
if m.isPublished {
onResourcePublished = false
onResourceUnpublished = true
}
m.isPublished = false
case http.ProtobufContentType(&pbRA.ResourceChanged{}):
var s raEvents.ResourceChanged
if err := eu.Unmarshal(&s); err != nil {
return err
}
if m.content == nil {
onResourceChanged = true
} else {
onResourceChanged = s.GetEventMetadata().GetVersion() > m.content.GetEventMetadata().GetVersion()
}
m.content = &s.ResourceChanged
case http.ProtobufContentType(&pbRA.ResourceUpdated{}):
var s raEvents.ResourceUpdated
if err := eu.Unmarshal(&s); err != nil {
return err
}
processedContentUpdates = append(processedContentUpdates, s)
}
}
if !anyEventProcessed {
// if event event not processed, it means that the projection will be reloaded.
return nil
}
if m.resource == nil {
return fmt.Errorf("DeviceID: %v, ResourceId: %v: invalid resource is stored in eventstore: Resource attribute is not set", deviceID, resourceID)
}
if onResourcePublished {
if err := m.onResourcePublishedLocked(ctx); err != nil {
log.Errorf("%v", err)
}
} else if onResourceUnpublished {
if err := m.onResourceUnpublishedLocked(ctx); err != nil {
log.Errorf("%v", err)
}
}
if onResourceChanged && m.isPublished {
if raCqrs.MakeResourceId(m.resource.GetDeviceId(), cloud.StatusHref) == m.resource.Id {
if err := m.onCloudStatusChangedLocked(ctx); err != nil {
log.Errorf("cannot make action on cloud status changed: %v", err)
}
}
if err := m.onResourceChangedLocked(ctx); err != nil {
log.Errorf("%v", err)
}
}
m.onProcessedContentUpdatesLocked(processedContentUpdates)
return nil
}
|
// package main
//
// import (
// "expvar"
// "fmt"
// "net/http"
// )
//
// var visits = expvar.NewInt("visits")
//
// func handler(w http.ResponseWriter, r *http.Request) {
// visits.Add(1)
// fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
// }
//
// func main() {
// http.HandleFunc("/", handler)
// http.ListenAndServe(":8080", nil)
// }
package main
import (
"expvar"
"gin-gonic-demo/expvar/monitor"
"github.com/gin-gonic/gin"
"net/http"
)
var visits = expvar.NewInt("visits")
func Debugvars() gin.HandlerFunc {
return func(c *gin.Context) {
visits.Add(1)
c.Next()
}
}
func main() {
r := gin.Default()
r.Use(Debugvars())
r.GET("/debug/vars", monitor.GetCurrentRunningStats)
r.GET("/someJSON", func(c *gin.Context) {
c.AsciiJSON(http.StatusOK, expvar.KeyValue{})
})
// 监听并在 0.0.0.0:8080 上启动服务
r.Run(":8080")
}
|
package server
import (
"net/http"
"reflect"
"strings"
"time"
"github.com/ItsJimi/casa/logger"
"github.com/ItsJimi/casa/utils"
"github.com/labstack/echo"
"golang.org/x/crypto/bcrypt"
)
var emailRegExp = "(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])"
type signupReq struct {
Email string `json:"email"`
Password string `json:"password"`
PasswordConfirmation string `json:"passwordConfirmation"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Birthdate string `json:"birthdate"`
}
type signinReq struct {
Email string `json:"email"`
Password string `json:"password"`
}
// SignUp route create an user
func SignUp(c echo.Context) error {
req := new(signupReq)
if err := c.Bind(req); err != nil {
logger.WithFields(logger.Fields{"code": "CSASU001"}).Errorf("%s", err.Error())
return c.JSON(http.StatusBadRequest, ErrorResponse{
Code: "CSASU001",
Message: "Wrong parameters",
})
}
if req.Password != req.PasswordConfirmation {
logger.WithFields(logger.Fields{"code": "CSASU002"}).Warnf("Passwords mismatch")
return c.JSON(http.StatusBadRequest, ErrorResponse{
Code: "CSASU002",
Message: "Passwords mismatch",
})
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), 14)
if err != nil {
logger.WithFields(logger.Fields{"code": "CSASU003"}).Errorf("%s", err.Error())
return c.JSON(http.StatusInternalServerError, ErrorResponse{
Code: "CSASU003",
Message: "Password can't be encrypted",
})
}
var birthdate time.Time
if req.Birthdate != "" {
birthdate, err = time.Parse(time.RFC3339, req.Birthdate)
if err != nil {
logger.WithFields(logger.Fields{"code": "CSASU004"}).Errorf("%s", err.Error())
return c.JSON(http.StatusInternalServerError, ErrorResponse{
Code: "CSASU004",
Message: "Birthdate can't be parsed",
})
}
}
firstname := req.Firstname
if firstname == "" {
firstname = strings.Split(req.Email, "@")[0]
}
newUser := User{
Email: req.Email,
Password: string(hashedPassword),
Firstname: firstname,
Lastname: req.Lastname,
Birthdate: birthdate.Format("2006-01-02 00:00:00"),
}
_, err = DB.NamedExec("INSERT INTO users (id, email, password, firstname, lastname, birthdate) VALUES (generate_ulid(), :email, :password, :firstname, :lastname, :birthdate)", newUser)
if err != nil {
logger.WithFields(logger.Fields{"code": "CSASU005"}).Errorf("%s", err.Error())
return c.JSON(http.StatusInternalServerError, ErrorResponse{
Code: "CSASU005",
Message: "Account can't be created",
})
}
return c.JSON(http.StatusCreated, MessageResponse{
Message: "Account created",
})
}
// SignIn route log an user by giving token
func SignIn(c echo.Context) error {
req := new(signinReq)
if err := c.Bind(req); err != nil {
logger.WithFields(logger.Fields{"code": "CSASI001"}).Errorf("%s", err.Error())
return c.JSON(http.StatusBadRequest, ErrorResponse{
Code: "CSASI001",
Message: "Wrong parameters",
})
}
if err := utils.MissingFields(c, reflect.ValueOf(req).Elem(), []string{"Email", "Password"}); err != nil {
logger.WithFields(logger.Fields{"code": "CSASI002"}).Errorf("%s", err.Error())
return c.JSON(http.StatusBadRequest, ErrorResponse{
Code: "CSASI002",
Message: err.Error(),
})
}
var user User
err := DB.Get(&user, "SELECT id, password FROM users WHERE email=$1", req.Email)
if err != nil {
logger.WithFields(logger.Fields{"code": "CSASI003"}).Errorf("%s", err.Error())
return c.JSON(http.StatusBadRequest, ErrorResponse{
Code: "CSASI003",
Message: "Email and password doesn't match",
})
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
logger.WithFields(logger.Fields{"code": "CSASI004"}).Errorf("%s", err.Error())
return c.JSON(http.StatusBadRequest, ErrorResponse{
Code: "CSASI003",
Message: "Email and password doesn't match",
})
}
row, err := DB.Query("INSERT INTO tokens (id, user_id, type, ip, user_agent) VALUES (generate_ulid(), $1, $2, $3, $4) RETURNING id;",
user.ID, "signin", c.RealIP(), c.Request().UserAgent())
if err != nil {
logger.WithFields(logger.Fields{"code": "CSASI005"}).Errorf("%s", err.Error())
return c.JSON(http.StatusBadRequest, ErrorResponse{
Code: "CSASI005",
Message: "Token can't be created",
})
}
var id string
row.Next()
err = row.Scan(&id)
if err != nil {
logger.WithFields(logger.Fields{"code": "CSASI006"}).Errorf("%s", err.Error())
return c.JSON(http.StatusBadRequest, ErrorResponse{
Code: "CSASI006",
Message: "Token can't be created",
})
}
return c.JSON(http.StatusOK, MessageResponse{
Message: id,
})
}
// SignOut route logout user and delete his token
func SignOut(c echo.Context) error {
token := strings.Split(c.Request().Header.Get("Authorization"), " ")[1]
_, err := DB.Exec(`
DELETE FROM tokens
WHERE id=$1
`, token)
if err != nil {
logger.WithFields(logger.Fields{"code": "CSASO001"}).Errorf("%s", err.Error())
return c.JSON(http.StatusInternalServerError, ErrorResponse{
Code: "CSASO001",
Message: "Token can't be delete",
})
}
return c.JSON(http.StatusOK, MessageResponse{
Message: "You've been disconnected and your token has been deleted",
})
}
type tokenUser struct {
Token
User
}
// IsAuthenticated verify validity of token
func IsAuthenticated(key string, c echo.Context) (bool, error) {
var token tokenUser
err := DB.Get(&token, "SELECT users.*, tokens.expire_at FROM tokens JOIN users ON tokens.user_id = users.id WHERE tokens.id=$1", key)
if err != nil {
logger.WithFields(logger.Fields{"code": "CSAIA001"}).Errorf("%s", err.Error())
return false, nil
}
expireAt, err := time.Parse(time.RFC3339, token.Token.ExpireAt)
if err != nil {
logger.WithFields(logger.Fields{"code": "CSAIA002"}).Errorf("%s", err.Error())
return false, nil
}
if expireAt.Sub(time.Now()) <= 0 {
logger.WithFields(logger.Fields{"code": "CSAIA003"}).Warnf("Expired tokens")
return false, nil
}
c.Set("user", token.User)
return true, nil
}
|
package cmds
import (
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"github.com/ayufan/docker-composer/compose"
)
func runEnableCommand(c *cli.Context) error {
app, err := compose.ExistingApplication(c.Args()...)
if err != nil {
logrus.Fatalln("App:", err)
}
err = app.Enable()
if err != nil {
logrus.Fatalln("Enable:", err)
}
err = app.Deploy()
if err != nil {
logrus.Fatalln("Deploy:", err)
}
return nil
}
func runDisableCommand(c *cli.Context) error {
app, err := compose.ExistingApplication(c.Args()...)
if err != nil {
logrus.Fatalln("App:", err)
}
err = app.Disable()
if err != nil {
logrus.Fatalln("Disable:", err)
}
err = app.Compose("down")
if err != nil {
logrus.Fatalln(err)
}
return nil
}
func init() {
registerCommand(cli.Command{
Name: "enable",
Action: runEnableCommand,
Usage: "enable application (previously disabled)",
Category: "manage",
ArgsUsage: "APP",
})
registerCommand(cli.Command{
Name: "disable",
Action: runDisableCommand,
Usage: "disable application (previously enabled)",
Category: "manage",
ArgsUsage: "APP",
})
}
|
// usage: go run predict_client.go --server_addr 127.0.0.1:9000 --model_name dense --model_version 1
package main
import (
"flag"
"fmt"
framework "tensorflow/core/framework"
pb "tensorflow_serving"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
)
var (
serverAddr = flag.String("server_addr", "127.0.0.1:9000", "The server address in the format of host:port")
modelName = flag.String("model_name", "cancer", "TensorFlow model name")
modelVersion = flag.Int64("model_version", 1, "TensorFlow model version")
tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
caFile = flag.String("ca_file", "testdata/ca.pem", "The file containning the CA root cert file")
serverHostOverride = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake")
)
func main() {
flag.Parse()
var opts []grpc.DialOption
if *tls {
var sn string
if *serverHostOverride != "" {
sn = *serverHostOverride
}
var creds credentials.TransportCredentials
if *caFile != "" {
var err error
creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
if err != nil {
grpclog.Fatalf("Failed to create TLS credentials %v", err)
}
} else {
creds = credentials.NewClientTLSFromCert(nil, sn)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithInsecure())
}
conn, err := grpc.Dial(*serverAddr, opts...)
if err != nil {
grpclog.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewPredictionServiceClient(conn)
var pr *pb.PredictRequest
if *modelName == "dense" {
pr = newDensePredictRequest(modelName, modelVersion)
} else {
pr = newSparsePredictRequest(modelName, modelVersion)
}
resp, err := client.Predict(context.Background(), pr)
if err != nil {
fmt.Println(err)
return
}
for k, v := range resp.Outputs {
fmt.Println(k, v)
}
}
func newDensePredictRequest(modelName *string, modelVersion *int64) *pb.PredictRequest {
pr := newPredictRequest(*modelName, *modelVersion)
addInput(pr, "keys", framework.DataType_DT_INT32, []int32{1, 2, 3}, nil, nil)
addInput(pr, "features", framework.DataType_DT_FLOAT, []float32{
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
}, []int64{3, 9}, nil)
return pr
}
// Example data:
// 0 5:1 6:1 17:1 21:1 35:1 40:1 53:1 63:1 71:1 73:1 74:1 76:1 80:1 83:1
// 1 5:1 7:1 17:1 22:1 36:1 40:1 51:1 63:1 67:1 73:1 74:1 76:1 81:1 83:1
func newSparsePredictRequest(modelName *string, modelVersion *int64) *pb.PredictRequest {
pr := newPredictRequest(*modelName, *modelVersion)
addInput(pr, "keys", framework.DataType_DT_INT32, []int32{1, 2}, nil, nil)
addInput(pr, "indexs", framework.DataType_DT_INT64, []int64{
0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5,
0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0, 11,
0, 12, 0, 13, 1, 0, 1, 1, 1, 2, 1, 3,
1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9,
1, 10, 1, 11, 1, 12, 1, 13,
}, []int64{28, 2}, nil)
addInput(pr, "ids", framework.DataType_DT_INT64, []int64{
5, 6, 17, 21, 35, 40, 53, 63, 71, 73, 74, 76, 80, 83,
5, 7, 17, 22, 36, 40, 51, 63, 67, 73, 74, 76, 81, 83,
}, nil, nil)
addInput(pr, "values", framework.DataType_DT_FLOAT, []float32{
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
}, nil, nil)
addInput(pr, "shape", framework.DataType_DT_INT64, []int64{2, 124}, nil, nil)
return pr
}
|
package keeper
import (
// "fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
// sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
abci "github.com/tendermint/tendermint/abci/types"
)
func queryReceiverInfo(
ctx sdk.Context, keeper Keeper, req abci.RequestQuery, receiver string,
) ([]byte, error) {
dayInfos := keeper.GetReceiverDayIdsInfo(ctx, receiver)
return keeper.cdc.MustMarshalJSON(dayInfos), nil
}
|
package main
func main() {
c := CommandInvoker{}
c.addToQueue(&SomeCommand{"Simone"})
c.addToQueue(&SomeCommand{"Gentili"})
c.addToQueue(&SomeSpecialCommand{"sensorario"})
}
|
package gocloud
import (
"github.com/b2wdigital/goignite/pkg/config"
)
// configs ..
const (
Resource = "transport.client.gocloud.resource"
Type = "transport.client.gocloud.type"
Region = "transport.client.gocloud.region"
)
func init() {
config.Add(Type, "memory", "define queue type")
config.Add(Resource, "topicA", "define queue resource")
config.Add(Region, "", "define queue region")
}
|
package main
import (
"fmt"
"os"
_ "github.com/mattn/go-sqlite3"
"github.com/alokmenghrajani/sqlc/sqlc"
)
func main() {
os.Remove("/tmp/example1.db")
db, err := sqlc.Open(sqlc.Sqlite, "/tmp/example1.db")
panicOnError(err)
defer db.Close()
_, err = db.Exec("CREATE TABLE books (id int primary key, title varchar(255), author int)")
panicOnError(err)
// Sample insert
db.InsertInto(BOOKS).Set(BOOKS.TITLE, "Defender Of Greatness").Set(BOOKS.ID, 1).Set(BOOKS.AUTHOR, 1234).Exec()
db.InsertInto(BOOKS).Set(BOOKS.TITLE, "Destiny Of Silver").Set(BOOKS.ID, 3).Set(BOOKS.AUTHOR, 1234).Exec()
// Sample update
db.Update(BOOKS).Set(BOOKS.ID, 3).Where(BOOKS.ID.Eq(2)).Exec()
// Sample query
rows, err := db.Select().From(BOOKS).Query()
panicOnError(err)
defer rows.Close()
for rows.Next() {
var book books
err := rows.StructScan(&book)
panicOnError(err)
fmt.Printf("%d: title: %s, author: %d\n", book.Id, book.Title, book.Author)
}
}
func panicOnError(err error) {
if err != nil {
panic(err)
}
}
|
package explorer
// 资源管理器
type exDataSet struct {
Id string `json:"uuid,omitempty"`
Name string `json:"name"`
UserId string `json:"user_id"`
Type string `json:"type,omitempty"`
Description string `json:"description,omitempty"`
}
type explorer struct {
Path string `json:"path" description:"explorer path"`
DataSets []*exDataSet `json:"newData, omitempty"`
}
|
package core
import (
"log"
"github.com/jonmorehouse/gatekeeper/gatekeeper"
router_plugin "github.com/jonmorehouse/gatekeeper/plugin/router"
)
type RouterClient interface {
RouteRequest(*gatekeeper.Request) (*gatekeeper.Upstream, *gatekeeper.Request, error)
}
type Router interface {
starter
RouterClient
}
func NewLocalRouter(broadcaster Broadcaster, metricWriter MetricWriter) Router {
return &localRouter{
broadcaster: broadcaster,
eventCh: make(EventCh, 10),
upstreams: make(map[gatekeeper.UpstreamID]*gatekeeper.Upstream),
prefixCache: make(map[string]*gatekeeper.Upstream),
hostnameCache: make(map[string]*gatekeeper.Upstream),
Subscriber: NewSubscriber(broadcaster),
}
}
type localRouter struct {
broadcaster Broadcaster
listenerID ListenerID
eventCh EventCh
RWMutex
upstreams map[gatekeeper.UpstreamID]*gatekeeper.Upstream
prefixCache map[string]*gatekeeper.Upstream
hostnameCache map[string]*gatekeeper.Upstream
Subscriber
}
func (l *localRouter) Start() error {
l.Subscriber.AddUpstreamEventHook(gatekeeper.UpstreamAddedEvent, l.addUpstreamHook)
l.Subscriber.AddUpstreamEventHook(gatekeeper.UpstreamRemovedEvent, l.removeUpstreamHook)
return l.Subscriber.Start()
}
func (l *localRouter) RouteRequest(req *gatekeeper.Request) (*gatekeeper.Upstream, *gatekeeper.Request, error) {
l.RLock()
defer l.RUnlock()
upstream, hit := l.prefixCache[req.Prefix]
if hit {
req.Path = req.PrefixlessPath
return upstream, req, nil
}
upstream, hit = l.hostnameCache[req.Host]
if hit {
return upstream, req, nil
}
log.Println(l.upstreams)
// check the upstream store for any and all matches
for _, upstream := range l.upstreams {
log.Println(upstream)
if InStrList(req.Host, upstream.Hostnames) {
l.hostnameCache[req.Host] = upstream
return upstream, req, nil
}
if InStrList(req.Prefix, upstream.Prefixes) {
l.prefixCache[req.Prefix] = upstream
req.Path = req.PrefixlessPath
return upstream, req, nil
}
}
return nil, req, RouteNotFoundError
}
func (l *localRouter) addUpstreamHook(event *UpstreamEvent) {
log.Println("add upstream...", event.Upstream)
l.Lock()
defer l.Unlock()
l.upstreams[event.UpstreamID] = event.Upstream
}
func (l *localRouter) removeUpstreamHook(event *UpstreamEvent) {
log.Println("remove upstream")
l.Lock()
defer l.Unlock()
delete(l.upstreams, event.UpstreamID)
for _, host := range event.Upstream.Hostnames {
delete(l.hostnameCache, host)
}
for _, prefix := range event.Upstream.Prefixes {
delete(l.prefixCache, prefix)
}
}
func NewPluginRouter(broadcaster Broadcaster, pluginManager PluginManager) Router {
return &pluginRouter{
Subscriber: NewSubscriber(broadcaster),
pluginManager: pluginManager,
}
}
type pluginRouter struct {
pluginManager PluginManager
Subscriber
}
func (p *pluginRouter) Start() error {
p.Subscriber.AddUpstreamEventHook(gatekeeper.UpstreamAddedEvent, p.addUpstreamHook)
p.Subscriber.AddUpstreamEventHook(gatekeeper.UpstreamRemovedEvent, p.removeUpstreamHook)
return p.Subscriber.Start()
}
func (p *pluginRouter) RouteRequest(req *gatekeeper.Request) (*gatekeeper.Upstream, *gatekeeper.Request, error) {
var upstream *gatekeeper.Upstream
var err error
callErr := p.pluginManager.Call("RouteRequest", func(plugin Plugin) error {
routerPlugin, ok := plugin.(router_plugin.PluginClient)
if !ok {
gatekeeper.ProgrammingError(InternalPluginError.Error())
return nil
}
upstream, req, err = routerPlugin.RouteRequest(req)
return err
})
if callErr != nil {
return nil, req, callErr
}
return upstream, req, err
}
func (p *pluginRouter) addUpstreamHook(event *UpstreamEvent) {
callErr := p.pluginManager.Call("AddUpstream", func(plugin Plugin) error {
routerPlugin, ok := plugin.(router_plugin.PluginClient)
if !ok {
gatekeeper.ProgrammingError(InternalPluginError.Error())
return nil
}
return routerPlugin.AddUpstream(event.Upstream)
})
if callErr != nil {
log.Println(callErr)
}
}
func (p *pluginRouter) removeUpstreamHook(event *UpstreamEvent) {
callErr := p.pluginManager.Call("RemoveUpstream", func(plugin Plugin) error {
routerPlugin, ok := plugin.(router_plugin.PluginClient)
if !ok {
gatekeeper.ProgrammingError(InternalPluginError.Error())
return nil
}
return routerPlugin.RemoveUpstream(event.UpstreamID)
})
if callErr != nil {
log.Println(callErr)
}
}
|
package main
import (
"bytes"
"github.com/jhyle/imgserver/api"
"image"
"image/jpeg"
"io/ioutil"
"net/http"
"os"
"strconv"
"sync"
"testing"
"time"
)
func TestImgServer(t *testing.T) {
tmpPath, err := ioutil.TempDir("", "imgserver")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpPath)
// start debugging server
go func() {
http.ListenAndServe("localhost:6000", nil)
}()
api := imgserver.NewImgServerApi("localhost", 3030, tmpPath, 1024*2)
go api.Start()
time.Sleep(time.Second * 3)
buffer := new(bytes.Buffer)
baseUrl := "http://localhost:3030/"
filename := "test.jpg"
url := baseUrl + filename
rgba := image.NewRGBA(image.Rect(0, 0, 5000, 5000))
jpeg.Encode(buffer, rgba, &jpeg.Options{90})
resp, err := http.Post(url, "image/jpeg", buffer)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("POST returned " + strconv.Itoa(resp.StatusCode))
}
var wait sync.WaitGroup
wait.Add(100)
for i := 0; i < 100; i++ {
go func() {
defer wait.Done()
for i := 0; i < 100; i++ {
for _, w := range []int{100, 200, 400, 800, 1600} {
resp, err := http.Get(url + "?width=" + strconv.Itoa(w) + "&height=10")
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("GET returned " + strconv.Itoa(resp.StatusCode))
}
ioutil.ReadAll(resp.Body)
resp.Body.Close()
}
}
}()
}
wait.Wait()
req, err := http.NewRequest("PUT", baseUrl, nil)
if err != nil {
t.Fatal(err)
}
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("PUT returned " + strconv.Itoa(resp.StatusCode))
} else {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
} else {
t.Log(string(data[:]))
}
}
filenameCopy := "test2.jpg"
req, err = http.NewRequest("PUT", url+"/"+filenameCopy, nil)
if err != nil {
t.Fatal(err)
}
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("PUT returned " + strconv.Itoa(resp.StatusCode))
}
urlCopy := baseUrl + filenameCopy
resp, err = http.Get(urlCopy)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("GET returned " + strconv.Itoa(resp.StatusCode))
}
req, err = http.NewRequest("DELETE", urlCopy, nil)
if err != nil {
t.Fatal(err)
}
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("DELETE returned " + strconv.Itoa(resp.StatusCode))
}
req, err = http.NewRequest("DELETE", url, nil)
if err != nil {
t.Fatal(err)
}
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("DELETE returned " + strconv.Itoa(resp.StatusCode))
}
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusNotFound {
t.Fatal("image exists after deletion")
}
}
|
package modules
import (
"fmt"
"strings"
)
// Channels ...
func Channels() {
switchingBetweenChannels()
}
type Message struct {
To []string
From string
Content string
}
type FailedMessage struct {
ErrorMessage string
OriginalMessage Message
}
func switchingBetweenChannels() {
msgCh := make(chan Message, 1)
errCh := make(chan FailedMessage, 1)
// msg := Message{
// To: []string{"adnan@adnan.com"},
// From: "manuel@manuel.com",
// Content: "Keep it secret, keep it safe."}
// failedMessage := FailedMessage{
// ErrorMessage: "Message errr",
// OriginalMessage: Message{}}
// msgCh <- msg
// errCh <- failedMessage
// fmt.Println(<-msgCh)
// fmt.Println(<-errCh)
// msgCh <- msg
select {
case receivedMsg := <-msgCh:
fmt.Println(receivedMsg)
case receivedError := <-errCh:
fmt.Println(receivedError)
// defult:
// fmt.Println("no message")
}
}
func rangingOverAChannel() {
phrase := "These are the times that try men's souls.\n"
words := strings.Split(phrase, " ")
ch := make(chan string, len(words))
for _, word := range words {
ch <- word
}
close(ch)
for msg := range ch {
fmt.Print(msg + " ")
}
}
func closingChannels() {
phrase := "These are the times that try men's souls.\n"
words := strings.Split(phrase, " ")
ch := make(chan string, len(words))
for _, word := range words {
ch <- word
}
close(ch)
for i := 0; i < len(words); i++ {
fmt.Print(<-ch + " ")
}
// ch <- "test"
}
func bufferedChannels() {
phrase := "These are the times that try men's souls.\n"
words := strings.Split(phrase, " ")
ch := make(chan string, len(words))
for _, word := range words {
ch <- word
}
for i := 0; i < len(words); i++ {
fmt.Print(<-ch + " ")
}
}
func basicChannels1() {
// deadlock
ch := make(chan string)
// ch := make(chan string, 1)
ch <- "Hello"
fmt.Println(<-ch)
}
|
package handler
import (
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/irham/agung/notes-bot/gdrive"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
)
type (
handler struct {
bot *tgbotapi.BotAPI
log *logrus.Logger
}
)
func New(bot *tgbotapi.BotAPI, log *logrus.Logger) *handler {
return &handler{
bot: bot,
log: log,
}
}
func (h *handler) FindImage() {
}
func (h *handler) MessageStart(update *tgbotapi.Update) {
_, err := h.bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(MessageStartResponse, update.Message.Chat.FirstName)))
if err != nil {
h.log.Errorf("MessageStart error: %v", err)
}
}
func (h *handler) MessageAuth(config *oauth2.Config, update *tgbotapi.Update) {
_, err := gdrive.FindToken(config)
if err != nil {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
msg := tgbotapi.NewMessage(update.Message.Chat.ID, MessageMissingAuthResponse)
msg.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonURL(AuthenticationUrlString, authURL),
),
)
_, err := h.bot.Send(msg)
if err != nil {
h.log.Errorf("MessageAuth error: %v", err)
return
}
}
}
func (h *handler) MessageUnknown(update *tgbotapi.Update) {
_, err := h.bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, MessageUnknownResponse))
if err != nil {
h.log.Errorf("MessageUnknown error: %v", err)
}
}
|
package timeo
import (
"fmt"
"time"
)
// 创建定时任务
var (
globalrounds int32
)
func main() {
// var ch chan int
// ticker := time.NewTicker(time.Second * 2)
// go func(tickers *time.Ticker) {
// for range tickers.C {
// fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
// }
// ch <- 1
// }(ticker)
// <-ch
c := time.Tick(time.Second * 5)
for {
<-c
go func() {
fmt.Println(time.Now().Format("2006-01-02 15:04:05"),globalrounds)
globalrounds += 1
}()
}
}
|
package cmd
import (
"fmt"
"os"
cobra "github.com/spf13/cobra"
)
var cfgFike string
var rootCmd = &cobra.Command{
Use: "reverse <command> [flags]",
Short: "reverse is a go utility to reverse a string",
Long: "reverse can reverse string from various source and write to various sources"}
// Execute add all child commands to the root command and set flags appropriately,
// This is called by main.main. It only needs to happen once to the rootCmd
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init(){
cobra.OnInitialize()
} |
package cmd
import (
"fmt"
"io/ioutil"
"log"
"github.com/lhopki01/dirin/internal/config"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func registerListCmd(rootCmd *cobra.Command) {
listCmd := &cobra.Command{
Use: "list",
Short: "List all collections",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
runListCmd(args)
},
}
rootCmd.AddCommand(listCmd)
err := viper.BindPFlags(listCmd.Flags())
if err != nil {
log.Fatalf("Binding flags failed: %s", err)
}
viper.AutomaticEnv()
}
func runListCmd(args []string) {
for _, c := range getCollections() {
fmt.Println(c)
}
}
func getCollections() []string {
fileNames := []string{}
files, err := ioutil.ReadDir(config.CollectionsDir())
if err != nil {
log.Fatal(err)
}
for _, f := range files {
if !f.IsDir() {
c, err := config.LoadCollectionRead(f.Name())
if err == nil && c != nil {
fileNames = append(fileNames, f.Name())
}
}
}
return fileNames
}
|
// Copyright 2018 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
// ===========================================================================
// HeadS represents a series of Head.
type HeadS []Head
// TailS represents a series of Tail.
type TailS []Tail
// Both implements Pair
// by returning both parts of a,
// a slice of the first item and a slice of the remaining items.
func (a HeadS) Both() (aten, apep interface{}) {
if len(a) > 0 {
return a[:1], a[1:] }
return a[:0], a[0:] }
// Both implements Pair
// by returning both parts of a,
// a slice of the first item and a slice of the remaining items.
func (a TailS) Both() (aten, apep interface{}) {
if len(a) > 0 {
return a[:1], a[1:] }
return a[:0], a[0:] }
// ===========================================================================
// Len reports the length.
func (a HeadS) Len() int { return len(a) }
// Len reports the length.
func (a TailS) Len() int { return len(a) }
// Size implements Pile by returning the length.
func (a HeadS) Size() Cardinality { return Cardinal(len(a)) }
// Size implements Pile by returning the length.
func (a TailS) Size() Cardinality { return Cardinal(len(a)) }
// ===========================================================================
|
package actions
import "github.com/stianeikeland/go-rpio"
//-->System Information
type Sysinfo struct{
Host HostInfo `json:"host"`
Cpu CpuInfo `json:"cpu"`
Mem MemInfo `json:"mem"`
Disk DiskInfo `json:"disk"`
}
type HostInfo struct{
Uptime string `json:"uptime"`
KernelVer string `json:"kernel_version"`
Platform string `json:"platform"`
PlatformVer string `json:"platform_ver"`
Boottime string `json:"boottime"`
Hostname string `json:"hostname"`
HostId string `json:"host_id"`
}
type CpuInfo struct{
CpuStats []CpuStat `json:"cpu_stats"`
}
type CpuStat struct{
CpuNum int `json:"cpu_num"`
Mhz float64 `json:"mhz"`
ModelName string `json:"model_name"`
Cores int32 `json:"cores"`
}
type MemInfo struct{
Total string `json:"total"`
Free string `json:"free"`
}
type DiskInfo struct{
Total uint64 `json:"total"`
Used uint64 `json:"used"`
Free uint64 `json:"free"`
}
//<--System Information
//-->GPIO pin
type GpioStates struct {
Pins []Pin `json:"pins"`
}
type Pin struct{
BcmPin int `json:"bcm_pin"`
State rpio.State `json:"state"`
}
//<--GPIO pin
//-->HDMI display
type Display struct{
HdmiState int `json:"hdmi_state"`
}
//<--HDMI display
//-->APT
type AptLog struct{
Log []string `json:"log"`
}
type AptInstallUpdate struct{
Status string `json:"status"`
}
//<--APT
//-->Power
type Power struct{
Status string `json:"status"`
}
//<--Power
//-->Service
type Service struct{
Status string `json:"status"`
}
//<--Service |
package dto
type FocusingExercise struct {
Exercise
}
|
package route
import (
"fmt"
)
type missingRoutesError struct {
method string
}
func (e *missingRoutesError) Error() string {
return fmt.Sprintf("%s has no routes", e.method)
}
|
package command
import (
"bytes"
"context"
"strings"
"testing"
"mvdan.cc/sh/v3/interp"
"mvdan.cc/sh/v3/syntax"
)
func TestCommand(t *testing.T) {
p := syntax.NewParser()
file, err := p.Parse(strings.NewReader("printf 123 && printf '4'\"'\"'5''6'"), "")
if err != nil {
t.Fatal(err)
}
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
r, err := interp.New(interp.StdIO(nil, stdout, stderr))
if err != nil {
t.Fatal(err)
}
err = r.Run(context.Background(), file)
if err != nil && err != interp.ShellExitStatus(0) {
t.Fatal(err)
}
if stdout.String() != "1234'56" {
t.Fatalf("Expected stdout '1234'56', got stdout '%s' - stderr '%s'", stdout.String(), stderr.String())
}
}
|
package validation
import (
"bytes"
"crypto/ecdsa"
"database/sql"
"encoding/asn1"
"errors"
"flag"
"log"
"math/big"
"os"
"strings"
"time"
"unicode"
"github.com/SIGBlockchain/project_aurum/internal/accountstable"
"github.com/SIGBlockchain/project_aurum/internal/block"
"github.com/SIGBlockchain/project_aurum/internal/config"
"github.com/SIGBlockchain/project_aurum/internal/contracts"
"github.com/SIGBlockchain/project_aurum/internal/hashing"
"github.com/SIGBlockchain/project_aurum/internal/jsonify"
"github.com/SIGBlockchain/project_aurum/internal/publickey"
)
// SetConfigFromFlags loads a configuration file into a Config struct, modifies the struct according to flags,
// and returns the updated struct
func SetConfigFromFlags(configFile *os.File) (config.Config, error) {
cfg := config.Config{}
err := jsonify.LoadJSON(configFile, &cfg)
if err != nil {
return cfg, errors.New("Failed to unmarshall configuration data : " + err.Error())
}
//specify flags
versionU64 := flag.Uint("version", uint(cfg.Version), "enter version number")
flag.Uint64Var(&cfg.InitialAurumSupply, "supply", cfg.InitialAurumSupply, "enter a number for initial aurum supply")
flag.StringVar(&cfg.Port, "port", cfg.Port, "enter port number")
flag.StringVar(&cfg.BlockProductionInterval, "interval", cfg.BlockProductionInterval, "enter a time for block production interval\n(assuming seconds if units are not provided)")
flag.BoolVar(&cfg.Localhost, "localhost", cfg.Localhost, "syntax: -localhost=/boolean here/")
flag.StringVar(&cfg.MintAddr, "mint", cfg.MintAddr, "enter a mint address (64 characters hex string)")
//read flags
flag.Parse()
cfg.Version = uint16(*versionU64)
// get units of interval
intervalSuffix := strings.TrimLeftFunc(cfg.BlockProductionInterval, func(r rune) bool {
return !unicode.IsLetter(r) && unicode.IsDigit(r)
})
// check units are valid
hasSuf := false
for _, s := range [7]string{"ns", "us", "µs", "ms", "s", "m", "h"} {
if intervalSuffix == s {
hasSuf = true
break
}
}
if !hasSuf {
log.Fatalf("Failed to enter a valid interval suffix\nBad input: %v\n"+
"Format should be digits and unit with no space e.g. 1h or 20s",
cfg.BlockProductionInterval)
}
if len(cfg.MintAddr) != 64 && len(cfg.MintAddr) != 0 {
log.Fatalf("Failed to enter a valid 64 character hex string for mint address.\n"+
"Bad input: %v (len: %v)\n"+"The mint address must have 64 characters", cfg.MintAddr, len(cfg.MintAddr))
}
return cfg, nil
}
func ValidateContract(dbConnection *sql.DB, c *contracts.Contract) error {
// check for zero value transaction
if c.Value == 0 {
return errors.New("Invalid contract: zero value transaction")
}
// check for nil sender public key and recip == sha-256 hash of senderPK
encodedCSenderPublicKey, err := publickey.Encode(c.SenderPubKey)
if err != nil {
return err
}
if c.SenderPubKey == nil || bytes.Equal(c.RecipPubKeyHash, hashing.New(encodedCSenderPublicKey)) {
return errors.New("Invalid contract: sender cannot be nil nor same as recipient")
}
// verify the signature in the contract
// Serialize the Contract
copyOfSigLen := c.SigLen
c.SigLen = 0
serializedContract, err := c.Serialize()
if err != nil {
return errors.New(err.Error())
}
hashedContract := hashing.New(serializedContract)
// stores r and s values needed for ecdsa.Verify
var esig struct {
R, S *big.Int
}
if _, err := asn1.Unmarshal(c.Signature, &esig); err != nil {
return errors.New("Failed to unmarshal signature")
}
// if ecdsa.Verify returns false, the signature is invalid
if !ecdsa.Verify(c.SenderPubKey, hashedContract, esig.R, esig.S) {
return errors.New("Invalid contract: signature is invalid")
}
// retrieve sender's balance from account balance table
senderPubKeyHash := hashing.New(encodedCSenderPublicKey)
senderAccountInfo, errAccount := accountstable.GetAccountInfo(dbConnection, senderPubKeyHash)
if errAccount == nil {
// check insufficient funds
if senderAccountInfo.Balance < c.Value {
// invalid contract because the sender's balance is less than the contract amount
return errors.New("Invalid contract: sender's balance is less than the contract amount")
}
if senderAccountInfo.StateNonce+1 != c.StateNonce {
// invalid contract because contract state nonce is not the expected number
return errors.New("Invalid contract: contract state nonce is not the expected number")
}
/* valid contract */
c.SigLen = copyOfSigLen
return nil
}
return errors.New("Failed to validate contract")
}
// ValidatePending validates a contract with the given pending balance and pending state nonce
func ValidatePending(c *contracts.Contract, pBalance *uint64, pNonce *uint64) error {
// check for zero value transaction
if c.Value == 0 {
return errors.New("Invalid contract: zero value transaction")
}
// check for nil sender public key and recip == sha-256 hash of senderPK
recipPKhash := hashing.SHA256Hash{SecureHash: c.RecipPubKeyHash}
encodedCSenderPublicKey, err := publickey.Encode(c.SenderPubKey)
if err != nil {
return err
}
if c.SenderPubKey == nil || recipPKhash.Equals(encodedCSenderPublicKey) {
return errors.New("Invalid contract: sender cannot be nil nor same as recipient")
}
// verify the signature in the contract
// Serialize the Contract
copyOfSigLen := c.SigLen
c.SigLen = 0
serializedContract, err := c.Serialize()
if err != nil {
return errors.New(err.Error())
}
hashedContract := hashing.New(serializedContract)
// stores r and s values needed for ecdsa.Verify
var esig struct {
R, S *big.Int
}
if _, err := asn1.Unmarshal(c.Signature, &esig); err != nil {
return errors.New("Failed to unmarshal signature")
}
// if ecdsa.Verify returns false, the signature is invalid
if !ecdsa.Verify(c.SenderPubKey, hashedContract, esig.R, esig.S) {
return errors.New("Invalid contract: signature is invalid")
}
// if sender's pending balance is less than the contract amount, invalid contract
if *pBalance < c.Value {
return errors.New("Invalid contract: sender's pending balance is less than the contract amount")
}
// if contract state nonce is not one greater than the sender's pending state nonce, invalid contract
if (*pNonce)+1 != c.StateNonce {
return errors.New("Invalid contract: contract state nonce is not the expected number")
}
/* valid contract, return updated pending balance and state nonce */
c.SigLen = copyOfSigLen
*pBalance -= c.Value
(*pNonce)++
return nil
}
// ValidateBlock takes in expected version, height, previousHash, and timeStamp
// and compares them with the block's
func ValidateBlock(b block.Block, version uint16, prevHeight uint64, previousHash []byte, prevTimeStamp int64) bool {
// Check Version
if b.Version != version {
return false
}
// Check Height
if b.Height != prevHeight+1 {
return false
}
// Check Previous Hash
if !(bytes.Equal(b.PreviousHash, previousHash)) {
return false
}
// Check timestamp
if b.Timestamp <= prevTimeStamp || b.Timestamp > time.Now().UnixNano() {
return false
}
// Check MerkleRoot
if !hashing.MerkleRootHashOf(b.MerkleRootHash, b.Data) {
return false
}
return true
}
// ValidateProducerTimestamp checks the parameter timestamp p to see if
// it is greater than the sum of the interval itv and
// the table timestamp t (corresponding to the walletAddr).
// False if p < t + itv
func ValidateProducerTimestamp(db *sql.DB, timestamp int64, walletAddr []byte, interval time.Duration) (bool, error) {
// search for wallet address in table and return timestamp
row, err := db.Query("SELECT timestamp FROM producer WHERE public_key_hash = ?", walletAddr)
if err != nil {
return false, err
}
defer row.Close()
// verify row was found
if !row.Next() {
return false, nil
}
// Scan for timestamp value in database row
var wT time.Duration
row.Scan(&wT)
// check if p < t + itv
if time.Duration(timestamp) < (wT + interval) {
return false, nil
}
return true, nil
}
|
package goevent_test
import (
"testing"
"github.com/indie21/goevent"
)
func TestNewTable(t *testing.T) {
ta := goevent.NewTable()
t.Logf("%#v", ta)
}
func TestTableOnTrigger(t *testing.T) {
ta := goevent.NewTable()
i := 0
err := ta.On("foo", func(j int) { i += j })
if err != nil {
t.Error(err)
}
err = ta.Trigger("foo", 1)
if err != nil {
t.Error(err)
}
if i != 1 {
t.Errorf("i expected 1, but got %d", i)
}
}
func TestTableTriggerFail(t *testing.T) {
ta := goevent.NewTable()
err := ta.Trigger("foo", 1)
if err == nil {
t.Error("should return error when event has not been defined yet. But got nil")
}
}
func TestTableOff(t *testing.T) {
ta := goevent.NewTable()
ta.Off("foo", func() {})
i := 0
f := func() { i++ }
ta.On("foo", f)
ta.Trigger("foo")
err := ta.Off("foo", f)
if err != nil {
t.Error(err)
}
ta.Trigger("foo")
if i != 1 {
t.Errorf("i expected 1, but got %d", i)
}
}
func TestTableDestroy(t *testing.T) {
ta := goevent.NewTable()
i := 0
ta.On("foo", func(j int) { i += j })
ta.Trigger("foo", 1)
err := ta.Destroy("foo")
if err != nil {
t.Error(err)
}
err = ta.Trigger("foo", 1)
if err == nil {
t.Errorf("should destroy event. but not destroy.")
}
if i != 1 {
t.Errorf("i expected 1, but got %d", i)
}
err = ta.Destroy("foo")
if err == nil {
t.Errorf("should return error when event has not been defined yet. but got nil")
}
}
|
// Copyright 2020 Thomas.Hoehenleitner [at] seerose.net
// Use of this source code is governed by a license that can be found in the LICENSE file.
package receiver
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"github.com/rokath/trice/internal/com"
"github.com/rokath/trice/internal/link"
)
var (
// ShowInputBytes displays incoming bytes if set true.
ShowInputBytes bool
// Port is the trice receiver to use.
Port string
// PortArguments are the trice receiver device specific arguments.
PortArguments string
)
// NewReadCloser returns a ReadCloser for the specified port and its args.
// err is nil on successful open.
// When port is "COMn" args can be used to be "TARM" to use a different driver for dynamic testing.
// When port is "BUFFER", args is expected to be a byte sequence in the same format as for example coming from one of the other ports.
// When port is "JLINK" args contains JLinkRTTLogger.exe specific parameters described inside UM08001_JLink.pdf.
// When port is "STLINK" args has the same format as for "JLINK"
func NewReadCloser(port, args string) (r io.ReadCloser, err error) {
switch port {
case "JLINK", "STLINK":
l := link.NewDevice(port, args)
if nil != l.Open() {
err = fmt.Errorf("can not open link device %s with args %s", port, args)
}
r = l
default: // assuming serial port
var c com.COMport // interface type
if "TARM" == args { // for comparing dynamic behaviour
c = com.NewCOMPortTarm(port)
} else {
c = com.NewCOMPortGoBugSt(port)
}
if false == c.Open() {
err = fmt.Errorf("can not open %s", port)
}
r = c
return
case "BUFFER":
r = ioutil.NopCloser(bytes.NewBufferString(args))
}
return
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// dynamic debug helper
//
type bytesViewer struct {
r io.ReadCloser
}
// NewBytesViewer returns a ReadCloser `in` which is internally using reader `from`.
// Calling the `in` Read method leads to internally calling the `from` Read method
// but lets to do some additional action like logging
func NewBytesViewer(from io.ReadCloser) (in io.ReadCloser) {
return &bytesViewer{from}
}
func (p *bytesViewer) Read(buf []byte) (count int, err error) {
count, err = p.r.Read(buf)
if 0 < count || (nil != err && io.EOF != err) {
log.Println("input bytes:", err, count, buf[:count])
}
return
}
// Close is needed to satify the ReadCloser interface.
func (p *bytesViewer) Close() error { return nil }
//
///////////////////////////////////////////////////////////////////////////////////////////////////
|
package pathways
import (
"net/http"
)
type ResponseWriter func(http.ResponseWriter)
type Response struct {
Response http.ResponseWriter
Request *http.Request
writer ResponseWriter
}
func ResponseFromContext(cx *Context, writer ResponseWriter) *Response {
return &Response{
Request: cx.Request,
Response: cx.Response,
writer: writer,
}
}
func (r *Response) ContentType(ct string) *Response {
return r.Header("Content-Type", ct)
}
func (r *Response) Location(url string) *Response {
return r.Header("Location", url)
}
func (r *Response) Header(key, value string) *Response {
r.Response.Header().Add(key, value)
return r
}
func (r *Response) Write() {
r.writer(r.Response)
}
|
package rp
import (
"encoding/json"
"net/http"
"time"
)
// Client is a client for working with the RP Web API.
type Client struct {
baseURL string
authBearer string
http *http.Client
}
// Launch that identifies a test run.
type Launch struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Mode Mode `json:"mode,omitempty"`
StartTime time.Time `json:"start_time"`
Tags []string `json:"tags,omitempty"`
}
// MarshalJSON with custom time format
func (launch *Launch) MarshalJSON() ([]byte, error) {
type Alias Launch
return json.Marshal(&struct {
StartTime string `json:"start_time"`
*Alias
}{
StartTime: launch.StartTime.Format(TimestampLayout),
Alias: (*Alias)(launch),
})
}
// TestItem identifies a test suite, test, test method (step) fot test run.
type TestItem struct {
LaunchID string `json:"launch_id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
StartTime time.Time `json:"start_time"`
Type TestItemType `json:"type"`
Tags []string `json:"tags,omitempty"`
}
// MarshalJSON with custom time format
func (item *TestItem) MarshalJSON() ([]byte, error) {
type Alias TestItem
return json.Marshal(&struct {
*Alias
StartTime string `json:"start_time"`
}{
Alias: (*Alias)(item),
StartTime: item.StartTime.Format(TimestampLayout),
})
}
// ExecutionResult is used to update executed TestItem.
type ExecutionResult struct {
EndTime time.Time `json:"end_time"`
Status ExecutionStatus `json:"status"`
}
// MarshalJSON with custom time format
func (result *ExecutionResult) MarshalJSON() ([]byte, error) {
type Alias ExecutionResult
return json.Marshal(&struct {
*Alias
EndTime string `json:"end_time"`
}{
Alias: (*Alias)(result),
EndTime: result.EndTime.Format(TimestampLayout),
})
}
// ResponceID of created item
type ResponceID struct {
ID string `json:"id"`
}
// LogMessage identifies test log.
type LogMessage struct {
ItemID string `json:"item_id"`
Time time.Time `json:"time"`
Message string `json:"message"`
Level LogLevel `json:"level"`
}
// MarshalJSON with custom time format
func (msg *LogMessage) MarshalJSON() ([]byte, error) {
type Alias LogMessage
return json.Marshal(&struct {
*Alias
Time string `json:"time"`
}{
Alias: (*Alias)(msg),
Time: msg.Time.Format(TimestampLayout),
})
}
|
package apps
import (
"fmt"
"os"
"os/exec"
)
func (app *App) run_post_push_commands() error {
for _, command := range app.PostPushCommands {
err := app.run_post_push_command(command)
if err != nil {
return err
}
}
return nil
}
func (app *App) run_post_push_command(command string) error {
if app.config.DryRun {
fmt.Printf("Run: %s\n - skipped (dry run)\n", command)
return nil
}
cmd := exec.Command("heroku", "run", command)
cmd.Env = append(
os.Environ(),
[]string{
"HEROKU_APP=" + app.AppName,
}...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = "/"
err := cmd.Run()
if err != nil {
fmt.Printf("error=%s", err)
return err
}
return nil
}
|
// Pacakge dump is a NanoMDM service that dumps raw responses
package dump
import (
"os"
"github.com/micromdm/nanomdm/mdm"
"github.com/micromdm/nanomdm/service"
)
// Dumper is a service middleware that dumps MDM requests and responses
// to a file handle.
type Dumper struct {
next service.CheckinAndCommandService
file *os.File
cmd bool
}
// New creates a new dumper service middleware.
func New(next service.CheckinAndCommandService, file *os.File) *Dumper {
return &Dumper{
next: next,
file: file,
cmd: true,
}
}
func (svc *Dumper) Authenticate(r *mdm.Request, m *mdm.Authenticate) error {
svc.file.Write(m.Raw)
return svc.next.Authenticate(r, m)
}
func (svc *Dumper) TokenUpdate(r *mdm.Request, m *mdm.TokenUpdate) error {
svc.file.Write(m.Raw)
return svc.next.TokenUpdate(r, m)
}
func (svc *Dumper) CheckOut(r *mdm.Request, m *mdm.CheckOut) error {
svc.file.Write(m.Raw)
return svc.next.CheckOut(r, m)
}
func (svc *Dumper) CommandAndReportResults(r *mdm.Request, results *mdm.CommandResults) (*mdm.Command, error) {
svc.file.Write(results.Raw)
cmd, err := svc.next.CommandAndReportResults(r, results)
if svc.cmd && err != nil && cmd != nil && cmd.Raw != nil {
svc.file.Write(cmd.Raw)
}
return cmd, err
}
|
package main
import (
"flag"
"lesson/fourth/configs"
"lesson/fourth/internal/di"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-kratos/kratos/pkg/log"
)
func main() {
flag.Parse()
log.Init(nil)
defer log.Close()
configs.Init()
_, closeFunc, err := di.InitApp()
if err != nil {
panic(err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
time.Sleep(time.Second)
closeFunc()
return
default:
return
}
}
}
|
package user
import (
"context"
"github.com/gudongkun/single_ucenter/enlight_ucenter_client"
"github.com/gudongkun/single_ucenter/enlight_ucenter_client/proto/user"
"github.com/micro/go-micro/v2/broker"
)
//GetName 获取用户信息, enlight_ucenter_client是一个整体,子调父的方式也不可避免。
func GetName(ctx context.Context, uid uint64) (*user.UserName, error) {
return enlight_ucenter_client.User.GetName(ctx, &user.UserId{Id: uid})
}
//GetAge 获取用户信息, enlight_ucenter_client是一个整体,子调父的方式也不可避免。
func GetAge(ctx context.Context, uid uint64) (*user.UserAge, error) {
return enlight_ucenter_client.User.GetAge(ctx, &user.UserId{Id: uid})
}
//GetSex 获取用户信息, enlight_ucenter_client是一个整体,子调父的方式也不可避免。
func GetSex(ctx context.Context, uid uint64) (*user.UserSex, error) {
return enlight_ucenter_client.User.GetSex(ctx, &user.UserId{Id: uid})
}
//PubSayHi 原生 broker 方式发送消息
func PubSayHi(ctx context.Context) error {
pubSub := enlight_ucenter_client.UCenterService.Server().Options().Broker
err := pubSub.Connect()
if err != nil {
panic(err)
}
//data,_ := proto.Marshal(student)
data_msg := broker.Message{
Header: map[string]string{
"header-name": "publish",
"header-version": "v1.0.0",
"data_type": "input",
},
Body: []byte("important msg"),
//Body:data,
}
err = pubSub.Publish("sayHello", &data_msg)
return err
}
|
package crd
const (
GroupName = "crd.alpha.io"
Version = "v1"
)
|
package handlers
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
"time"
"github.com/DungBuiTien1999/bookings/internal/driver"
"github.com/DungBuiTien1999/bookings/internal/models"
)
var theTests = []struct {
name string
url string
method string
expectedStatusCode int
}{
{"home", "/", "GET", http.StatusOK},
{"about", "/about", "GET", http.StatusOK},
{"general_quarters", "/generals-quarters", "GET", http.StatusOK},
{"majors_suite", "/majors-suite", "GET", http.StatusOK},
{"search_availability", "/search-availability", "GET", http.StatusOK},
{"contact", "/contact", "GET", http.StatusOK},
{"non-exist", "/haha/hoho", "GET", http.StatusNotFound},
{"login", "/user/login", "GET", http.StatusOK},
{"logout", "/user/logout", "GET", http.StatusOK},
{"admin dashboard", "/admin/dashboard", "GET", http.StatusOK},
{"new reservations", "/admin/reservations-new", "GET", http.StatusOK},
{"all reservations", "/admin/reservations-all", "GET", http.StatusOK},
{"show reservation", "/admin/reservations/new/1/show", "GET", http.StatusOK},
{"show reservation calender", "/admin/reservations-calendar?y=2021&m=10", "GET", http.StatusOK},
{"handle process mark with year", "/admin/process-reservation/new/1/do?y=2021&m=10", "GET", http.StatusOK},
{"handle process mark without year", "/admin/process-reservation/new/1/do", "GET", http.StatusOK},
{"handle delete reservation with year", "/admin/delete-reservation/new/1/do?y=2021&m=10", "GET", http.StatusOK},
{"handle delete reservation", "/admin/delete-reservation/new/1/do", "GET", http.StatusOK},
}
func TestHandlers(t *testing.T) {
routes := getRoutes()
ts := httptest.NewTLSServer(routes)
defer ts.Close()
for _, e := range theTests {
resp, err := ts.Client().Get(ts.URL + e.url)
if err != nil {
t.Log(err)
t.Fatal(err)
}
if resp.StatusCode != e.expectedStatusCode {
t.Errorf("for %s, expected %d but got %d", e.name, e.expectedStatusCode, resp.StatusCode)
}
}
}
func TestNewRepo(t *testing.T) {
var db driver.DB
testRepo := NewRepo(&app, &db)
if reflect.TypeOf(testRepo).String() != "*handlers.Repository" {
t.Errorf("Did not get correct type from NewRepo, got %s, wanted *Repository", reflect.TypeOf(testRepo).String())
}
}
func TestRepository_Reservation(t *testing.T) {
reservation := models.Reservation{
ID: 1,
RoomID: 1,
Room: models.Room{
ID: 1,
RoomName: "General's Quarter",
},
}
req, _ := http.NewRequest("GET", "/make-reservation", nil)
ctx := getCtx(req)
req = req.WithContext(ctx)
rr := httptest.NewRecorder()
session.Put(ctx, "reservation", reservation)
handler := http.HandlerFunc(Repo.Reservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("Reservation handler returned wrong response code: got %d, wanted %d", rr.Code, http.StatusOK)
}
// test case where reservation is not in session (reset initial session)
req, _ = http.NewRequest("GET", "/make-reservation", nil)
ctx = getCtx(req)
req = req.WithContext(ctx)
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("Reservation handler returned wrong response code: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case non-existent room
req, _ = http.NewRequest("GET", "/make-reservation", nil)
ctx = getCtx(req)
req = req.WithContext(ctx)
rr = httptest.NewRecorder()
reservation.RoomID = 3
session.Put(ctx, "reservation", reservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("Reservation handler returned wrong response code: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
}
func TestRepository_PostReservation(t *testing.T) {
layout := "2006-01-02"
startDate, _ := time.Parse(layout, "2050-01-01")
endDate, _ := time.Parse(layout, "2050-01-03")
reservation := models.Reservation{
RoomID: 1,
StartDate: startDate,
EndDate: endDate,
Room: models.Room{
ID: 1,
RoomName: "General's Quarter",
},
}
postData := url.Values{}
postData.Add("first_name", "dung")
postData.Add("last_name", "bui")
postData.Add("email", "dung@gmail.com")
postData.Add("phone", "023186753")
req, _ := http.NewRequest("POST", "/make-reservation", strings.NewReader(postData.Encode()))
ctx := getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
session.Put(ctx, "reservation", reservation)
handler := http.HandlerFunc(Repo.PostReservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostReservation handler returned wrong response code: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case where reservation is not in session (reset initial session)
req, _ = http.NewRequest("POST", "/make-reservation", strings.NewReader(postData.Encode()))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostReservation handler returned wrong response code for missing reservation session: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case missing post body
req, _ = http.NewRequest("POST", "/make-reservation", nil)
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
session.Put(ctx, "reservation", reservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostReservation handler returned wrong response code for missing body: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case invalid form
postData = url.Values{}
postData.Add("first_name", "d")
postData.Add("last_name", "bui")
postData.Add("email", "dung@gmail.com")
postData.Add("phone", "023186753")
req, _ = http.NewRequest("POST", "/make-reservation", strings.NewReader(postData.Encode()))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
session.Put(ctx, "reservation", reservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostReservation handler returned wrong response code for invalid form data: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case insert reservation failure
reservation.RoomID = 2
postData = url.Values{}
postData.Add("first_name", "dung")
postData.Add("last_name", "bui")
postData.Add("email", "dung@gmail.com")
postData.Add("phone", "023186753")
req, _ = http.NewRequest("POST", "/make-reservation", strings.NewReader(postData.Encode()))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
session.Put(ctx, "reservation", reservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostReservation handler returned wrong response code for insert reservation: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case insert restriction room failure
reservation.RoomID = 1000
postData = url.Values{}
postData.Add("first_name", "dung")
postData.Add("last_name", "bui")
postData.Add("email", "dung@gmail.com")
postData.Add("phone", "023186753")
req, _ = http.NewRequest("POST", "/make-reservation", strings.NewReader(postData.Encode()))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
session.Put(ctx, "reservation", reservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostReservation handler returned wrong response code for insert restriction room: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
}
func TestRepository_PostAvailability(t *testing.T) {
reqBody := "start=2050-01-01"
reqBody = fmt.Sprintf("%s&%s", reqBody, "end=2050-01-03")
reqBody = fmt.Sprintf("%s&%s", reqBody, "room_id=1")
req, _ := http.NewRequest("POST", "/search-availability", strings.NewReader(reqBody))
ctx := getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
handler := http.HandlerFunc(Repo.PostAvailability)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("PostAvailability handler returned wrong response code: got %d, wanted %d", rr.Code, http.StatusOK)
}
// test case invalid form
req, _ = http.NewRequest("POST", "/search-availability", nil)
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler = http.HandlerFunc(Repo.PostAvailability)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostAvailability handler returned wrong response code for missing form data: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case failure to parse start date
reqBody = "start=invalid"
reqBody = fmt.Sprintf("%s&%s", reqBody, "end=2050-01-03")
reqBody = fmt.Sprintf("%s&%s", reqBody, "room_id=1")
req, _ = http.NewRequest("POST", "/search-availability", strings.NewReader(reqBody))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler = http.HandlerFunc(Repo.PostAvailability)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostAvailability handler returned wrong response code for invalid start date: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case failure to parse end date
reqBody = "start=2050-01-01"
reqBody = fmt.Sprintf("%s&%s", reqBody, "end=invalid")
reqBody = fmt.Sprintf("%s&%s", reqBody, "room_id=1")
req, _ = http.NewRequest("POST", "/search-availability", strings.NewReader(reqBody))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler = http.HandlerFunc(Repo.PostAvailability)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostAvailability handler returned wrong response code for invalid end date: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case failure to search available rooms
reqBody = "start=2000-01-01"
reqBody = fmt.Sprintf("%s&%s", reqBody, "end=2000-01-03")
reqBody = fmt.Sprintf("%s&%s", reqBody, "room_id=1")
req, _ = http.NewRequest("POST", "/search-availability", strings.NewReader(reqBody))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler = http.HandlerFunc(Repo.PostAvailability)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostAvailability handler returned wrong response code for search available rooms: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case when have non-existently available room
reqBody = "start=2050-10-01"
reqBody = fmt.Sprintf("%s&%s", reqBody, "end=2000-10-03")
reqBody = fmt.Sprintf("%s&%s", reqBody, "room_id=1")
req, _ = http.NewRequest("POST", "/search-availability", strings.NewReader(reqBody))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler = http.HandlerFunc(Repo.PostAvailability)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("PostAvailability handler returned wrong response code for no available room: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
}
func TestRepository_ReservationSummary(t *testing.T) {
reservation := models.Reservation{}
req, _ := http.NewRequest("POST", "/search-availability", nil)
ctx := getCtx(req)
req = req.WithContext(ctx)
session.Put(ctx, "reservation", reservation)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(Repo.ReservationSummary)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("ReservationSummary handler returned wrong response code: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case missing reservation session
req, _ = http.NewRequest("POST", "/search-availability", nil)
ctx = getCtx(req)
req = req.WithContext(ctx)
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("ReservationSummary handler returned wrong response code for missing reservation session: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
}
func TestRepository_PostAvailabilityJSON(t *testing.T) {
// first case - rooms are not available
reqBody := "start_date=2050-01-01"
reqBody = fmt.Sprintf("%s&%s", reqBody, "end_date=2050-01-03")
reqBody = fmt.Sprintf("%s&%s", reqBody, "room_id=3")
// create request
req, _ := http.NewRequest("POST", "/search-availability-json", strings.NewReader(reqBody))
// get context with session
ctx := getCtx(req)
req = req.WithContext(ctx)
// set the request header
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// make handler handleFunc
handler := http.HandlerFunc(Repo.PostAvailabilityJSON)
// get response recorder
rr := httptest.NewRecorder()
// make request to handler
handler.ServeHTTP(rr, req)
var j jsonResponse
err := json.Unmarshal([]byte(rr.Body.Bytes()), &j)
if err != nil {
t.Error("failed to parse json - case have not availible room")
}
if j.OK {
t.Error("expected rooms are not available")
}
// second case - rooms are available
reqBody = "start_date=2050-01-01"
reqBody = fmt.Sprintf("%s&%s", reqBody, "end_date=2050-01-03")
reqBody = fmt.Sprintf("%s&%s", reqBody, "room_id=1")
req, _ = http.NewRequest("POST", "/search-availability-json", strings.NewReader(reqBody))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
err = json.Unmarshal([]byte(rr.Body.Bytes()), &j)
if err != nil {
t.Error("failed to parse json - case have not availible room")
}
if !j.OK {
t.Error("expected rooms are available")
}
// third case - missing form data
req, _ = http.NewRequest("POST", "/search-availability-json", nil)
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
err = json.Unmarshal([]byte(rr.Body.Bytes()), &j)
if err != nil {
t.Error("failed to parse json - case missing form data")
}
if j.OK {
t.Error("expected error because missing form data")
}
// four case - failure to connect to database
reqBody = "start_date=2050-01-01"
reqBody = fmt.Sprintf("%s&%s", reqBody, "end_date=2050-01-03")
reqBody = fmt.Sprintf("%s&%s", reqBody, "room_id=3")
req, _ = http.NewRequest("POST", "/search-availability-json", strings.NewReader(reqBody))
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
err = json.Unmarshal([]byte(rr.Body.Bytes()), &j)
if err != nil {
t.Error("failed to parse json - case failure to connect to database")
}
if j.OK {
t.Error("expected error for failure connect to database")
}
}
func TestRepository_ChooseRoom(t *testing.T) {
reservation := models.Reservation{
RoomID: 1,
Room: models.Room{
ID: 1,
RoomName: "General's Quarters",
},
}
req, _ := http.NewRequest("GET", "/choose-room/1", nil)
req.RequestURI = "/choose/1"
ctx := getCtx(req)
req = req.WithContext(ctx)
session.Put(ctx, "reservation", reservation)
handler := http.HandlerFunc(Repo.ChooseRoom)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("ChooseRoom handler returned wrong response code: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case failure to parse room id
req, _ = http.NewRequest("GET", "/choose-room/invalid", nil)
req.RequestURI = "/choose/invalid"
ctx = getCtx(req)
req = req.WithContext(ctx)
session.Put(ctx, "reservation", reservation)
handler = http.HandlerFunc(Repo.ChooseRoom)
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("ChooseRoom handler returned wrong response code for invalid roomID: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case missing reservation session
req, _ = http.NewRequest("GET", "/choose-room/1", nil)
req.RequestURI = "/choose/1"
ctx = getCtx(req)
req = req.WithContext(ctx)
handler = http.HandlerFunc(Repo.ChooseRoom)
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("ChooseRoom handler returned wrong response code for missing reservation session: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
}
func TestRepository_BookRoom(t *testing.T) {
req, _ := http.NewRequest("GET", "/book-room?id=1&sd=2050-01-01&ed=2050-01-03", nil)
req.RequestURI = "/book-room?id=1&sd=2050-01-01&ed=2050-01-03"
ctx := getCtx(req)
req = req.WithContext(ctx)
handler := http.HandlerFunc(Repo.BookRoom)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("BookRoom handler returned wrong response code: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
// test case failure to connect to database
req, _ = http.NewRequest("GET", "/book-room?id=3&sd=2050-01-01&ed=2050-01-03", nil)
req.RequestURI = "/book-room?id=3&sd=2050-01-01&ed=2050-01-03"
ctx = getCtx(req)
req = req.WithContext(ctx)
handler = http.HandlerFunc(Repo.BookRoom)
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("BookRoom handler returned wrong response code for failure to connect to db: got %d, wanted %d", rr.Code, http.StatusSeeOther)
}
}
var loginTests = []struct {
name string
email string
expectedStatusCode int
expectedHTML string
expectedLocation string
}{
{
"valid-credentials",
"me@hehe.com",
http.StatusSeeOther,
"",
"/",
},
{
"invalid-credentials",
"dung@hehe.com",
http.StatusSeeOther,
"",
"/user/login",
},
{
"invalid-credentials",
"d",
http.StatusOK,
`action="/user/login"`,
"",
},
}
func TestLogin(t *testing.T) {
// range through all tests
for _, e := range loginTests {
postedData := url.Values{}
postedData.Add("email", e.email)
postedData.Add("password", "password")
// create request
req, _ := http.NewRequest("POST", "user/login", strings.NewReader(postedData.Encode()))
ctx := getCtx(req)
req = req.WithContext(ctx)
// set the header
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
// call the handler
handler := http.HandlerFunc(Repo.PostShowLogin)
handler.ServeHTTP(rr, req)
if rr.Code != e.expectedStatusCode {
t.Errorf("failed %s: expected code %d, but got %d", e.name, e.expectedStatusCode, rr.Code)
}
if e.expectedLocation != "" {
// get the URL from the test
actualLoc, _ := rr.Result().Location()
if actualLoc.String() != e.expectedLocation {
t.Errorf("failed %s: expected location %s, but got %s", e.name, e.expectedLocation, actualLoc.String())
}
}
// checking for expected values in HTML
if e.expectedHTML != "" {
// read the response body into a string
html := rr.Body.String()
if !strings.Contains(html, e.expectedHTML) {
t.Errorf("failed %s: expected to find %s but did not", e.name, e.expectedHTML)
}
}
}
}
func TestAdminPostShowReservation(t *testing.T) {
// case valid without redirect to calendar
formData := url.Values{}
formData.Add("year", "")
formData.Add("month", "")
formData.Add("first_name", "dung")
formData.Add("last_name", "bui")
formData.Add("email", "dung@gmail.com")
formData.Add("phone", "320-334-8878")
req, _ := http.NewRequest("POST", "/admin/reservations/new/1", strings.NewReader(formData.Encode()))
req.RequestURI = "/admin/reservations/new/1"
ctx := getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
handler := http.HandlerFunc(Repo.AdminPostShowReservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("failed valid without redirect to calendar: expected code %d, but got %d", http.StatusSeeOther, rr.Code)
}
actualLoc, _ := rr.Result().Location()
if actualLoc.String() != "/admin/reservations-new" {
t.Errorf("failed valid without redirect to calendar: expected location /admin/reservations-new, but got %s", actualLoc.String())
}
// case valid with redirect to calendar
formData = url.Values{}
formData.Add("year", "2021")
formData.Add("month", "10")
formData.Add("first_name", "dung")
formData.Add("last_name", "bui")
formData.Add("email", "dung@gmail.com")
formData.Add("phone", "320-334-8878")
req, _ = http.NewRequest("POST", "/admin/reservations/cal/1", strings.NewReader(formData.Encode()))
req.RequestURI = "/admin/reservations/cal/1"
ctx = getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr = httptest.NewRecorder()
handler = http.HandlerFunc(Repo.AdminPostShowReservation)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("failed valid without redirect to calendar: expected code %d, but got %d", http.StatusSeeOther, rr.Code)
}
actualLoc, _ = rr.Result().Location()
if actualLoc.String() != "/admin/reservations-calendar?y=2021&m=10" {
t.Errorf("failed valid without redirect to calendar: expected location /admin/reservations-calendar?y=2021&m=10, but got %s", actualLoc.String())
}
}
func TestAdminPostCalendarReservations(t *testing.T) {
formData := url.Values{}
formData.Add("y", "2021")
formData.Add("m", "10")
formData.Add("remove_block_1_2021-10-10", "2")
formData.Add("remove_block_2_2021-10-10", "5")
formData.Add("add_block_2_2021-10-12", "3")
blockMap1 := make(map[string]int)
blockMap1["2021-10-10"] = 2
blockMap1["2021-10-12"] = 4
blockMap2 := make(map[string]int)
blockMap2["2021-10-10"] = 5
req, _ := http.NewRequest("POST", "/admin/reservations-calendar", strings.NewReader(formData.Encode()))
ctx := getCtx(req)
req = req.WithContext(ctx)
session.Put(ctx, "block_map_1", blockMap1)
session.Put(ctx, "block_map_2", blockMap2)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
handler := http.HandlerFunc(Repo.AdminPostCalendarReservations)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Errorf("failed case valid date: expected code %d, but got %d", http.StatusSeeOther, rr.Code)
}
actualLoc, _ := rr.Result().Location()
if actualLoc.String() != "/admin/reservations-calendar?y=2021&m=10" {
t.Errorf("failed case valid date: expected location /admin/reservations-calendar?y=2021&m=10, but got %s", actualLoc.String())
}
}
func getCtx(r *http.Request) context.Context {
ctx, err := session.Load(r.Context(), r.Header.Get("X-Session"))
if err != nil {
log.Println()
}
return ctx
}
|
package fbmessenger
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
"golang.org/x/net/context"
)
const apiURL = "https://graph.facebook.com/v3.3"
type httpDoer interface {
Do(req *http.Request) (*http.Response, error)
}
/*
Client is used to send messages and get user profiles. Use the empty value in most cases.
The URL field can be overridden to allow for writing integration tests that use a different
endpoint (not Facebook).
*/
type Client struct {
URL string
httpDoer httpDoer
}
/*
Send POSTs a request to and returns a response from the Send API. A response from
Facebook indicating an error does not return an error. Be sure to check for errors
in sending, and errors in the response from Facebook.
response, err := client.Send(request, "YOUR_PAGE_ACCESS_TOKEN")
if err != nil {
//Got an error. Request never got to Facebook.
} else if response.Error != nil {
//Request got to Facebook. Facebook returned an error.
} else {
//Hooray!
}
*/
func (c *Client) Send(sendRequest *SendRequest, pageAccessToken string) (*SendResponse, error) {
return c.SendWithContext(context.Background(), sendRequest, pageAccessToken)
}
// SendWithContext is like Send but allows you to timeout or cancel the request using context.Context.
func (c *Client) SendWithContext(ctx context.Context, sendRequest *SendRequest, pageAccessToken string) (*SendResponse, error) {
var req *http.Request
var err error
if isDataMessage(sendRequest) {
req, err = c.newFormDataRequest(sendRequest, pageAccessToken)
} else {
req, err = c.newJSONRequest(sendRequest, pageAccessToken)
}
if err != nil {
return nil, err
}
response := &SendResponse{}
err = c.doRequest(ctx, req, response)
if err != nil {
return nil, err
}
return response, nil
}
func isDataMessage(sendRequest *SendRequest) bool {
if sendRequest.Message.Attachment == nil {
return false
}
_, ok := sendRequest.Message.Attachment.Payload.(DataPayload)
return ok
}
func (c *Client) newJSONRequest(sendRequest *SendRequest, pageAccessToken string) (*http.Request, error) {
requestBytes, err := json.Marshal(sendRequest)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.buildURL("/me/messages?access_token="+pageAccessToken), bytes.NewBuffer(requestBytes))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return req, nil
}
func (c *Client) newFormDataRequest(sendRequest *SendRequest, pageAccessToken string) (*http.Request, error) {
payload, _ := sendRequest.Message.Attachment.Payload.(DataPayload)
var reqBuffer bytes.Buffer
w := multipart.NewWriter(&reqBuffer)
err := writeFormField(w, "recipient", sendRequest.Recipient)
if err != nil {
return nil, err
}
err = writeFormField(w, "message", sendRequest.Message)
if err != nil {
return nil, err
}
if sendRequest.NotificationType != "" {
err = w.WriteField("notification_type", sendRequest.NotificationType)
if err != nil {
return nil, err
}
}
header := make(textproto.MIMEHeader)
header.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, "filedata", payload.FileName))
header.Set("Content-Type", payload.ContentType)
fileWriter, err := w.CreatePart(header)
if err != nil {
return nil, err
}
_, err = fileWriter.Write(payload.Data)
if err != nil {
return nil, err
}
w.Close()
req, err := http.NewRequest("POST", c.buildURL("/me/messages?access_token="+pageAccessToken), &reqBuffer)
//req, err := http.NewRequest("POST", "http://httpbin.org/post", &reqBuffer)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", w.FormDataContentType())
return req, nil
}
func writeFormField(w *multipart.Writer, fieldName string, value interface{}) error {
valueBytes, err := json.Marshal(value)
if err != nil {
return fmt.Errorf("error marshaling value for field %v: %v", fieldName, err)
}
return w.WriteField(fieldName, string(valueBytes))
}
// GetUserProfile GETs a profile with more information about the user.
func (c *Client) GetUserProfile(userId, pageAccessToken string) (*UserProfile, error) {
return c.GetUserProfileWithContext(context.Background(), userId, pageAccessToken)
}
// GetUserProfileWithContext is like GetUserProfile but allows you to timeout or cancel the request using context.Context.
func (c *Client) GetUserProfileWithContext(ctx context.Context, userId, pageAccessToken string) (*UserProfile, error) {
url := c.buildURL(fmt.Sprintf("/%v?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=%v", userId, pageAccessToken))
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
userProfile := &UserProfile{}
err = c.doRequest(ctx, req, userProfile)
if err != nil {
return nil, err
}
return userProfile, nil
}
func (c *Client) buildURL(path string) string {
url := c.URL
if url == "" {
url = apiURL
}
return url + path
}
func (c *Client) doRequest(ctx context.Context, req *http.Request, responseStruct interface{}) error {
req.Cancel = ctx.Done()
doer := c.httpDoer
if doer == nil {
doer = &http.Client{}
}
resp, err := doer.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, responseStruct)
if err != nil {
return err
}
return nil
}
|
package message
import (
"errors"
"fmt"
"github.com/streadway/amqp"
"time"
)
type Publisher struct {
getChannel GetChannel
exchange string
routingKey string
timeout time.Duration
}
func NewPublisher(getChannel GetChannel, exchange, routingKey string, timeout time.Duration) *Publisher {
return &Publisher{
getChannel: getChannel,
exchange: exchange,
routingKey: routingKey,
timeout: timeout,
}
}
func (p *Publisher) Publish(body string) error {
channel, err := p.getChannel()
if err != nil {
return fmt.Errorf("cannot get channel: %w", err)
}
defer channel.Close()
err = channel.Confirm(false)
if err != nil {
return fmt.Errorf("cannot set confirm: %w", err)
}
err = channel.Publish(
p.exchange,
p.routingKey,
false,
false,
amqp.Publishing{
Body: []byte(body),
},
)
if err != nil {
return fmt.Errorf("cannot publish: %w", err)
}
select {
case confirmation := <-channel.NotifyPublish(make(chan amqp.Confirmation, 1)):
if !confirmation.Ack {
return errors.New("failed to deliver message to exchange/queue")
}
case <-time.After(p.timeout):
return errors.New("publishing timed out")
}
return nil
}
|
/*
* EVE Swagger Interface
*
* An OpenAPI for EVE Online
*
* OpenAPI spec version: 0.4.1.dev1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package swagger
// alliance object
type GetCorporationsCorporationIdAlliancehistoryAlliance struct {
// alliance_id integer
AllianceId int32 `json:"alliance_id,omitempty"`
// True if the alliance has been deleted
IsDeleted bool `json:"is_deleted,omitempty"`
}
|
// Copyright 2018 The go-bindata Authors. All rights reserved.
// Use of this source code is governed by a CC0 1.0 Universal (CC0 1.0)
// Public Domain Dedication license that can be found in the LICENSE file.
package bindata
import "testing"
// nolint: gochecknoglobals
var sanitizeTests = []struct {
in string
out string
}{
{`hello`, "`hello`"},
{"hello\nworld", "`hello\nworld`"},
{"`ello", "(\"`\" + `ello`)"},
{"`a`e`i`o`u`", "(((\"`\" + `a`) + (\"`\" + (`e` + \"`\"))) + ((`i` + (\"`\" + `o`)) + (\"`\" + (`u` + \"`\"))))"},
{"\xEF\xBB\xBF`s away!", "(\"\\xEF\\xBB\\xBF\" + (\"`\" + `s away!`))"},
}
func TestSanitize(t *testing.T) {
for _, tt := range sanitizeTests {
out := sanitize([]byte(tt.in))
if string(out) != tt.out {
t.Errorf("sanitize(%q):\nhave %q\nwant %q", tt.in, out, tt.out)
}
}
}
|
package api
import (
"encoding/json"
"net/http"
"onikur.com/text-to-img-api/utils"
)
// ListFontsHandler ...
type ListFontsHandler struct{}
func (h *ListFontsHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
var a []string
if status := req.URL.Query().Get("status"); status == "disabled" {
a = utils.Fonts().Disabled
} else {
a = utils.Fonts().Available
}
js, err := json.Marshal(a)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
res.Header().Set("Content-Type", "application/json")
res.Write(js)
}
|
/*
* @lc app=leetcode id=72 lang=golang
*
* [72] Edit Distance
*
* https://leetcode.com/problems/edit-distance/description/
*
* algorithms
* Hard (38.45%)
* Likes: 2252
* Dislikes: 34
* Total Accepted: 183.2K
* Total Submissions: 476.3K
* Testcase Example: '"horse"\n"ros"'
*
* Given two words word1 and word2, find the minimum number of operations
* required to convert word1 to word2.
*
* You have the following 3 operations permitted on a word:
*
*
* Insert a character
* Delete a character
* Replace a character
*
*
* Example 1:
*
*
* Input: word1 = "horse", word2 = "ros"
* Output: 3
* Explanation:
* horse -> rorse (replace 'h' with 'r')
* rorse -> rose (remove 'r')
* rose -> ros (remove 'e')
*
*
* Example 2:
*
*
* Input: word1 = "intention", word2 = "execution"
* Output: 5
* Explanation:
* intention -> inention (remove 't')
* inention -> enention (replace 'i' with 'e')
* enention -> exention (replace 'n' with 'x')
* exention -> exection (replace 'n' with 'c')
* exection -> execution (insert 'u')
*
*
*/
func minDistance(word1 string, word2 string) int {
l1 := len(word1)+1
l2 := len(word2)+1
m := make([][]int, l1)
for i, _:=range(m) {
m[i] = make([]int, l2)
}
for i := 0 ; i < l1 ; i ++ {
m[i][0] = i
}
for j := 0 ; j < l2 ; j ++ {
m[0][j] = j
}
for i := 1; i < l1 ; i ++ {
for j := 1; j < l2; j++ {
if word1[i-1] == word2[j-1] {
m[i][j] = m[i-1][j-1]
} else {
min := m[i-1][j-1]
if min > m[i][j-1]{
min = m[i][j-1]
}
if min > m[i-1][j]{
min = m[i-1][j]
}
m[i][j] = min + 1
}
}
}
return m[l1-1][l2-1]
}
|
package services
import "github.com/cloudfoundry-incubator/notifications/models"
type TemplateUpdaterInterface interface {
Update(models.Template) error
}
type TemplateUpdater struct {
repo models.TemplatesRepoInterface
database models.DatabaseInterface
}
func NewTemplateUpdater(repo models.TemplatesRepoInterface, database models.DatabaseInterface) TemplateUpdater {
return TemplateUpdater{
repo: repo,
database: database,
}
}
func (updater TemplateUpdater) Update(template models.Template) error {
_, err := updater.repo.Upsert(updater.database.Connection(), template)
if err != nil {
return err
}
return nil
}
|
package main
import (
"fmt"
"proxy"
)
func main() {
server := new(proxy.Proxy)
err := server.NewProxy("172.16.64.156", 9876)
if err != nil {
fmt.Println(err)
}
server.Run()
}
|
// Copyright 2018 Diego Bernardes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package repository
import (
"context"
"encoding/json"
"fmt"
"net/url"
"time"
"github.com/pkg/errors"
"github.com/diegobernardes/flare"
)
// Resource implements flare.ResourceRepositorier.
type Resource struct {
err error
findByURIErr error
base flare.ResourceRepositorier
date time.Time
createID string
partitions []string
}
// Find mock flare.ResourceRepositorier.FindAll.
func (r *Resource) Find(ctx context.Context, pag *flare.Pagination) (
[]flare.Resource, *flare.Pagination, error,
) {
if r.err != nil {
return nil, nil, r.err
}
res, resPag, err := r.base.Find(ctx, pag)
if err != nil {
return nil, nil, err
}
for i := range res {
res[i].CreatedAt = r.date
}
return res, resPag, nil
}
// FindByID mock flare.ResourceRepositorier.FindOne.
func (r *Resource) FindByID(ctx context.Context, id string) (*flare.Resource, error) {
if r.err != nil {
return nil, r.err
}
res, err := r.base.FindByID(ctx, id)
if err != nil {
return nil, err
}
res.CreatedAt = r.date
return res, nil
}
// FindByURI mock flare.ResourceRepositorier.FindByURI.
func (r *Resource) FindByURI(ctx context.Context, uri url.URL) (*flare.Resource, error) {
if r.findByURIErr != nil {
return nil, r.findByURIErr
} else if r.err != nil {
return nil, r.err
}
return r.base.FindByURI(ctx, uri)
}
// Create mock flare.ResourceRepositorier.Create.
func (r *Resource) Create(ctx context.Context, resource *flare.Resource) error {
if r.err != nil {
return r.err
}
err := r.base.Create(ctx, resource)
resource.CreatedAt = r.date
resource.ID = r.createID
return err
}
// Delete mock flare.ResourceRepositorier.Delete.
func (r *Resource) Delete(ctx context.Context, id string) error {
if r.err != nil {
return r.err
}
return r.base.Delete(ctx, id)
}
// Partitions return the list of partitions of a resource.
func (r *Resource) Partitions(ctx context.Context, id string) (partitions []string, err error) {
if r.err != nil {
return nil, r.err
}
if len(r.partitions) > 0 {
return r.partitions, nil
}
return r.base.Partitions(ctx, id)
}
func newResource(options ...func(*Resource)) *Resource {
r := &Resource{}
for _, option := range options {
option(r)
}
return r
}
// ResourceRepository set the resource repository.
func ResourceRepository(repository flare.ResourceRepositorier) func(*Resource) {
return func(s *Resource) { s.base = repository }
}
// ResourceCreateID set id used during resource create.
func ResourceCreateID(id string) func(*Resource) {
return func(r *Resource) { r.createID = id }
}
// ResourceError set the error to be returned during calls.
func ResourceError(err error) func(*Resource) {
return func(r *Resource) { r.err = err }
}
// ResourceFindByURIError set the error to be returned during findByURI calls.
func ResourceFindByURIError(err error) func(*Resource) {
return func(r *Resource) { r.findByURIErr = err }
}
// ResourceDate set the date to be used at time fields.
func ResourceDate(date time.Time) func(*Resource) {
return func(r *Resource) { r.date = date }
}
// ResourceLoadSliceByteResource load a list of encoded resources in a []byte json layout into
// repository.
func ResourceLoadSliceByteResource(content []byte) func(*Resource) {
return func(r *Resource) {
resources := make([]struct {
Id string `json:"id"`
Endpoint string `json:"endpoint"`
CreatedAt time.Time `json:"createdAt"`
Path string `json:"path"`
Change struct {
Field string `json:"field"`
Format string `json:"format"`
}
}, 0)
if err := json.Unmarshal(content, &resources); err != nil {
panic(errors.Wrap(err,
fmt.Sprintf("error during unmarshal of '%s' into '%v'", string(content), resources),
))
}
for _, rawResource := range resources {
endpoint, err := url.Parse(rawResource.Endpoint)
if err != nil {
panic(errors.Wrap(err, "error during endpoint parse"))
}
err = r.Create(context.Background(), &flare.Resource{
ID: rawResource.Id,
Endpoint: *endpoint,
CreatedAt: rawResource.CreatedAt,
Change: flare.ResourceChange{
Format: rawResource.Change.Format,
Field: rawResource.Change.Field,
},
})
if err != nil {
panic(errors.Wrap(err, "error during flare.Resource persistence"))
}
}
}
}
// ResourcePartitions set a list of partitions to be returned by partitions search.
func ResourcePartitions(partitions []string) func(*Resource) {
return func(r *Resource) {
r.partitions = partitions
}
}
|
package model
import "time"
type User struct {
ID string `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at" sql:"index"`
Name string `json:"name" gorm:"unique; not null"` //昵称
Email string `json:"email" gorm:"unique; not null"` //邮箱地址
Mobile string `json:"mobile" gorm:"unique; not null"` //手机号
Password string `json:"password,omitempty" gorm:"not null"` //密码
AuthorityID string `json:"authority_id""`
Authority Authority `json:"authority"`
}
// TableName 表名
func (user *User) TableName() string {
return "users"
}
|
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"time"
_ "github.com/mattn/go-sqlite3"
"golang.org/x/crypto/bcrypt"
)
var DB *sql.DB
func SetupDB() {
var err error
DB, err = sql.Open("sqlite3", DB_FILE)
if err != nil {
log.Fatal(err)
}
_, err = DB.Exec(
`CREATE TABLE IF NOT EXISTS files
(id INTEGER NOT NULL PRIMARY KEY, hash BLOB NOT NULL UNIQUE, data BLOB, filename TEXT, user_id INTEGER NOT NULL, created_at INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS users
(id INTEGER NOT NULL PRIMARY KEY, username TEXT NOT NULL UNIQUE, email TEXT NOT NULL, password TEXT NOT NULL, role TEXT NOT NULL, created_at INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS sessions
(id INTEGER NOT NULL PRIMARY KEY, session_hash BLOB NOT NULL UNIQUE, user_id INTEGER NOT NULL, created_at INTEGER NOT NULL)`,
)
if err != nil {
log.Fatal(err)
}
// Create default user admin|admin if not exists
rows_num := 0
err = DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&rows_num)
if err != nil {
log.Fatal(err)
}
if rows_num == 0 {
passwdHash, err := bcrypt.GenerateFromPassword([]byte("admin"), bcrypt.DefaultCost)
if err != nil {
log.Fatal(err)
}
_, err = DB.Exec(
"INSERT INTO users (username, email, password, role, created_at) VALUES (?, ?, ?, ?, ?)",
"admin", "", passwdHash, "admin", time.Now().Unix(),
)
if err != nil {
log.Fatal(err)
}
}
}
func CreateUser(u *User) error {
hashedPass, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
_, err = DB.Exec(
"INSERT INTO users (username, email, password, role, created_at) VALUES (?, ?, ?, ?, ?)",
u.Name, u.Email, hashedPass, "admin", time.Now().Unix(),
)
return err
}
func UpdateUser(u *User) error {
hashedPass, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
_, err = DB.Exec(
"UPDATE users SET username=?, email=?, password=? WHERE id=?",
u.Name, u.Email, hashedPass, u.ID,
)
return err
}
func GetUserByName(username string) (*User, error) {
u := new(User)
err := DB.QueryRow(
"SELECT id, username, email, password, role FROM users WHERE username=?", username,
).Scan(&u.ID, &u.Name, &u.Email, &u.Password, &u.Role)
return u, err
}
func CreateEntry(hash []byte, data []byte, filename string, u *User) error {
_, err := DB.Exec(
"INSERT INTO files (hash, data, filename, user_id, created_at) VALUES (?, ?, ?, ?, ?)",
hash, data, filename, u.ID, time.Now().Unix(),
)
return err
}
func DeleteEntryByID(id uint64) error {
_, err := DB.Exec("DELETE FROM files WHERE id=?", id)
return err
}
func GetSessionUser(sessionHash []byte) (*User, error) {
u := new(User)
err := DB.QueryRow(
"SELECT id, username, email, role FROM users WHERE id=(SELECT user_id FROM SESSIONS WHERE session_hash=?)", sessionHash,
).Scan(&u.ID, &u.Name, &u.Email, &u.Role)
return u, err
}
func GetFile(r *http.Request, hash []byte) (*Entry, error) {
file := new(Entry)
err := DB.QueryRow(
"SELECT id, hash, data, filename FROM files WHERE hash=?", hash,
).Scan(&file.ID, &file.Hash, &file.Data, &file.Filename)
file.URL = fmt.Sprintf("http://%s/%x", r.Host, hash)
return file, err
}
func GetUserFilesList(r *http.Request, u *User) []Entry {
entry := Entry{}
list := []Entry{}
rows, err := DB.Query(
"SELECT id, filename, hash, created_at FROM files WHERE user_id=? ORDER BY id DESC",
u.ID,
)
if err != nil {
log.Println(err)
}
defer rows.Close()
for rows.Next() {
rows.Scan(&entry.ID, &entry.Filename, &entry.Hash, &entry.CreatedAt)
entry.URL = fmt.Sprintf("http://%s/%x", r.Host, entry.Hash)
list = append(list, entry)
}
return list
}
func DeleteSessionFromDB(sessionHash []byte) error {
_, err := DB.Exec("DELETE FROM sessions WHERE session_hash=?", sessionHash)
return err
}
func CreateSessionInDB(sessionHash []byte, user *User) error {
_, err := DB.Exec(
"INSERT INTO sessions (session_hash, user_id, created_at) VALUES (?, ?, ?)",
sessionHash, user.ID, time.Now().Unix(),
)
return err
}
// Sessions clean up goroutine
func SessionCleaner() {
for {
_, err := DB.Exec("DELETE FROM sessions WHERE created_at < ?", time.Now().Unix()-SESSION_MAX_AGE)
if err != nil {
log.Println(err)
}
time.Sleep(time.Second * 300)
}
}
|
package main
import "fmt"
var numbers = []int{1, 2, 4, 8, 16}
/*
This func returns an anonymous func that stores the i variable as a value. By this way
the i variable has a scope that goes over of counter.
*/
func counter() func() int {
var i int
return func() int {
i++
return i
}
}
func useCounter() {
f := counter() // f is func() of type func() int
fmt.Printf("call anonymous func, value is %d\n", f())
fmt.Printf("call anonymous func, value is %d\n", f())
fmt.Printf("call anonymous func, value is %d\n", f())
}
func counterNew() {
var funcs []func() int
for _, i := range numbers {
m := i
funcs = append(funcs, func() int {
m++
return m
})
}
for _, f := range funcs {
fmt.Println(f())
}
}
|
package handler
import (
"time"
"github.com/labstack/echo/v4"
"github.com/milobella/oratio/internal/ability"
"github.com/milobella/oratio/internal/config"
"github.com/milobella/oratio/pkg/anima"
"github.com/milobella/oratio/pkg/cerebro"
"github.com/sirupsen/logrus"
)
// New initiates all the handlers and their dependencies from the config.
// It will return an object containing directly the HandlerFunc to register to the server.
func New(conf *config.Config) *Handler {
// Initialize clients
cerebroClient := cerebro.NewClient(conf.Cerebro.Host, conf.Cerebro.Port, conf.Cerebro.UnderstandEndpoint)
animaClient := anima.NewClient(conf.Anima.Host, conf.Anima.Port, conf.Anima.RestituteEndpoint)
// Build the ability service. It will manage the DB and request the different abilities.
// TODO(Célian): The DAO being not initialized shouldn't be a reason of not being up. We should have a retry mechanism + health endpoint
abilityDAO, err := ability.NewMongoDAO(conf.Abilities.Database, 3*time.Second)
if err != nil {
logrus.WithError(err).Fatalf("Error initializing the Ability DAO.")
}
abilityService := ability.NewService(abilityDAO, conf.Abilities)
// Build the handlers
abilityHandler := NewAbility(abilityService)
textHandler := NewText(cerebroClient, animaClient, abilityService)
return &Handler{
Text: textHandler.Send,
GetAbilities: abilityHandler.Get,
CreateAbility: abilityHandler.Create,
}
}
type Handler struct {
Text echo.HandlerFunc
GetAbilities echo.HandlerFunc
CreateAbility echo.HandlerFunc
}
|
/**
* @Author : henry
* @Data: 2020-08-13 21:15
* @Note:
**/
package models
type Voucher interface {
AddVoucher()
}
|
package main
import "text/template"
var tmpl = template.Must(template.New("default").Parse(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Disk Space Visualizer</title>
<style type="text/css">
html, body { font: 14px/20px "Courier New", Courier, monospace }
ul { list-style: none; padding: 0 0 5px 10px }
li { cursor: pointer }
span { display: block; padding: 3px }
li:hover > span { background:#efefef; }
</style>
</head>
<body>
<h1>Disk Space Analyzer</h1>
<ul id="root">
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script id="data" type="application/json">
{{.}}
</script>
<script>
var i = 0;
function render(data) {
var nodeBuilder = [
'<li class="folder"><span title="',
data.fullPath,
'" data-for="#p', i++, '"> ',
data.subDirs && data.subDirs.length > 0 ? ' <b>+</b>' : ' ',
' ',
data.path, ' (', data.size, ')',
'</span>'];
if(data.subDirs && data.subDirs.length > 0) {
nodeBuilder.push(['<ul id="p', i-1,'" style="display:none">'].join(''));
for(var j = 0; j < data.subDirs.length; j++) {
nodeBuilder.push(render(data.subDirs[j]));
}
nodeBuilder.push('</ul>');
}
nodeBuilder.push('</li>');
return nodeBuilder.join('');
}
$(function() {
data = JSON.parse(document.getElementById('data').innerHTML);
$('#root').append($(render(data)));
$('.folder > span').on('click', function() {
var t = $(this);
var b = t.find('b');
b && b.text(b.text() == '+' ? '-' : '+');
var f = $(t.data('for'));
f && f.slideToggle('fast');
});
})
</script>
</body>
</html>`))
|
package command
import (
"fmt"
"github.com/ajpen/termsnippet/core"
"gopkg.in/urfave/cli.v1"
)
func init() {
InstallCommand(listSnippetCommand())
}
const (
listSnippetTemplate = "%s: %s\n\n"
)
func listSnippetCommand() cli.Command {
cmd := cli.Command{
Name: "list",
Description: "list all saved snippets",
Action: func(c *cli.Context) error {
snippets, err := core.AllSnippets()
if err != nil {
return fmt.Errorf("Error getting saved snippets: %s", err)
}
for _, snippet := range snippets {
fmt.Printf(listSnippetTemplate, snippet.Title, snippet.Description)
}
return nil
},
}
return cmd
}
|
package models
import (
"github.com/astaxie/beego"
"database/sql"
"fmt"
)
type Application struct {
Id int64
Title string
}
func GetFrist10() (result []Application, err error){
var rows *sql.Rows
rows, err = DB.Query("select id, title from Application order by id desc limit 10")
if err != nil {
beego.Critical("Query failed: ", err)
return
}
result = []Application{}
for rows.Next() {
app := Application{}
if err = rows.Scan(&app.Id, &app.Title); err != nil {
beego.Critical("Scanning data error: ", err)
return
}
beego.Info(app)
result = append(result, app)
}
if err = rows.Err(); err != nil {
beego.Error("Reading data error: ", err)
return
}
return
}
func GetOneById(id int) (result Application, err error){
fmt.Println("Scan sql.row by ScanStruct()")
row := DB.QueryRow("select id, title from Application where id=?", id)
ScanStruct(row, &result)
return
} |
package common
import (
"testing"
"github.com/root-gg/utils"
"github.com/stretchr/testify/require"
)
func TestUnmarshalUpload(t *testing.T) {
u := &Upload{}
u.NewFile()
bytes, _ := utils.ToJson(u)
upload := &Upload{}
version, err := UnmarshalUpload(bytes, upload)
require.NoError(t, err, "unmarshal upload error")
require.Equal(t, 0, version, "invalid version")
}
func TestUnmarshalUploadV1(t *testing.T) {
v1 := &UploadV1{}
v1.Files = make(map[string]*File)
v1.Files["1"] = &File{ID: "1"}
bytes, _ := utils.ToJson(v1)
upload := &Upload{}
version, err := UnmarshalUpload(bytes, upload)
require.NoError(t, err, "unmarshal upload error")
require.Equal(t, 1, version, "invalid version")
}
func TestUnmarshalUploadInvalid(t *testing.T) {
upload := &Upload{}
_, err := UnmarshalUpload([]byte("blah"), upload)
require.Error(t, err, "unmarshal upload error expected")
}
func TestMarshalUpload(t *testing.T) {
u := &Upload{}
u.NewFile()
bytes, err := MarshalUpload(u, 0)
require.NoError(t, err, "marshal upload error")
require.NotZero(t, len(bytes), "invalid json length")
}
func TestMarshalUploadV1(t *testing.T) {
u := &Upload{}
u.NewFile()
bytes, err := MarshalUpload(u, 1)
require.NoError(t, err, "marshal upload error")
require.NotZero(t, len(bytes), "invalid json length")
}
|
package AAC
import (
"github.com/panda-media/muxer-fmp4/utils"
"strings"
)
const (
AOT_NULL = iota
// Support? Name
AOT_AAC_MAIN ///< Y Main
AOT_AAC_LC ///< Y Low Complexity
AOT_AAC_SSR ///< N (code in SoC repo) Scalable Sample Rate
AOT_AAC_LTP ///< Y Long Term Prediction
AOT_SBR ///< Y Spectral Band Replication HE-AAC
AOT_AAC_SCALABLE ///< N Scalable
AOT_TWINVQ ///< N Twin Vector Quantizer
AOT_CELP ///< N Code Excited Linear Prediction
AOT_HVXC ///< N Harmonic Vector eXcitation Coding
)
const (
AOT_TTSI = 12 + iota ///< N Text-To-Speech Interface
AOT_MAINSYNTH ///< N Main Synthesis
AOT_WAVESYNTH ///< N Wavetable Synthesis
AOT_MIDI ///< N General MIDI
AOT_SAFX ///< N Algorithmic Synthesis and Audio Effects
AOT_ER_AAC_LC ///< N Error Resilient Low Complexity
)
const (
AOT_ER_AAC_LTP = 19 + iota ///< N Error Resilient Long Term Prediction
AOT_ER_AAC_SCALABLE ///< N Error Resilient Scalable
AOT_ER_TWINVQ ///< N Error Resilient Twin Vector Quantizer
AOT_ER_BSAC ///< N Error Resilient Bit-Sliced Arithmetic Coding
AOT_ER_AAC_LD ///< N Error Resilient Low Delay
AOT_ER_CELP ///< N Error Resilient Code Excited Linear Prediction
AOT_ER_HVXC ///< N Error Resilient Harmonic Vector eXcitation Coding
AOT_ER_HILN ///< N Error Resilient Harmonic and Individual Lines plus Noise
AOT_ER_PARAM ///< N Error Resilient Parametric
AOT_SSC ///< N SinuSoidal Coding
AOT_PS ///< N Parametric Stereo
AOT_SURROUND ///< N MPEG Surround
AOT_ESCAPE ///< Y Escape Value
AOT_L1 ///< Y Layer 1
AOT_L2 ///< Y Layer 2
AOT_L3 ///< Y Layer 3
AOT_DST ///< N Direct Stream Transfer
AOT_ALS ///< Y Audio LosslesS
AOT_SLS ///< N Scalable LosslesS
AOT_SLS_NON_CORE ///< N Scalable LosslesS (non core)
AOT_ER_AAC_ELD ///< N Error Resilient Enhanced Low Delay
AOT_SMR_SIMPLE ///< N Symbolic Music Representation Simple
AOT_SMR_MAIN ///< N Symbolic Music Representation Main
AOT_USAC_NOSBR ///< N Unified Speech and Audio Coding (no SBR)
AOT_SAOC ///< N Spatial Audio Object Coding
AOT_LD_SURROUND ///< N Low Delay MPEG Surround
AOT_USAC ///< N Unified Speech and Audio Coding
)
const (
SAMPLE_SIZE = 1024
)
type AACAudioSpecificConfig struct {
object_type int
sampling_index int
sample_rate int
chan_config int
sbr int
ext_object_type int
ext_sampling_index int
ext_sample_rate int
ext_chan_config int
channels int
ps int
frame_length_short int
}
func parseConfigALS(reader *utils.BitReader, asc *AACAudioSpecificConfig) {
if reader.BitsLeft() < 112 {
return
}
if reader.ReadBits(8) != 'A' || reader.ReadBits(8) != 'L' || reader.ReadBits(8) != 'S' || reader.ReadBits(8) != 0 {
return
}
asc.sample_rate = int(reader.Read32Bits())
reader.Read32Bits()
asc.chan_config = 0
asc.channels = reader.ReadBits(16) + 1
}
func getObjectType(reader *utils.BitReader) int {
objType := reader.ReadBits(5)
if AOT_ESCAPE == objType {
objType = 32 + reader.ReadBits(6)
}
return objType
}
func getSampleRate(reader *utils.BitReader) (sampleRateIdx, sampleRate int) {
sampleRateIdx = reader.ReadBits(4)
if sampleRateIdx == 0xf {
sampleRate = reader.ReadBits(24)
} else {
sampleRate = func(idx int) int {
AACSampleRates := [16]int{96000, 88200, 64000, 48000, 44100, 32000,
24000, 22050, 16000, 12000, 11025, 8000, 7350}
return AACSampleRates[idx]
}(sampleRateIdx)
}
return sampleRateIdx, sampleRate
}
func AACGetConfig(data []byte) (asc *AACAudioSpecificConfig) {
reader := &utils.BitReader{}
reader.Init(data)
asc = &AACAudioSpecificConfig{}
asc.object_type = getObjectType(reader)
asc.sampling_index, asc.sample_rate = getSampleRate(reader)
asc.chan_config = reader.ReadBits(4)
if asc.chan_config < 8 {
asc.channels = func(idx int) int {
arr := []int{0, 1, 2, 3, 4, 5, 6, 8}
return arr[idx]
}(asc.chan_config)
}
asc.sbr = -1
asc.ps = -1
if AOT_SBR == asc.object_type ||
(AOT_PS == asc.object_type && 0 == (reader.CopyBits(3)&0x03) && 0 == (reader.CopyBits(9)&0x3f)) {
if AOT_PS == asc.object_type {
asc.ps = 1
}
asc.ext_object_type = AOT_SBR
asc.sbr = 1
asc.ext_sampling_index, asc.ext_sample_rate = getSampleRate(reader)
asc.object_type = getObjectType(reader)
if asc.object_type == AOT_ER_BSAC {
asc.ext_chan_config = reader.ReadBits(4)
}
} else {
asc.ext_object_type = AOT_NULL
asc.ext_sample_rate = 0
}
if AOT_ALS == asc.object_type {
reader.ReadBits(5)
als := reader.CopyBits(24)
if ((als>>16)&0xff) != 'A' || ((als>>8)&0xff) != 'L' || ((als)&0xff) != 'S' {
reader.ReadBits(24)
}
parseConfigALS(reader, asc)
}
if asc.ext_object_type != AOT_SBR {
for reader.BitsLeft() > 15 {
if 0x2b7 == reader.CopyBits(11) {
reader.ReadBits(11)
asc.ext_object_type = getObjectType(reader)
if asc.ext_object_type == AOT_SBR {
asc.sbr = reader.ReadBit()
if asc.sbr == 1 {
asc.ext_sampling_index, asc.ext_sample_rate = getSampleRate(reader)
if asc.ext_sample_rate == asc.sample_rate {
asc.sbr = -1
}
}
if reader.BitsLeft() > 11 && reader.ReadBits(11) == 0x548 {
asc.ps = reader.ReadBit()
}
break
}
} else {
reader.ReadBit()
}
}
}
if asc.sbr == 0 {
asc.ps = 0
}
if (asc.ps == -1 && asc.object_type == AOT_AAC_LC) || (asc.channels&^0x01) != 0 {
asc.ps = 0
}
return
}
func (this *AACAudioSpecificConfig) ObjectType() int {
return this.object_type
}
func (this *AACAudioSpecificConfig) SampleRate() int {
if this.ext_sample_rate > 0 {
return this.ext_sample_rate
}
return this.sample_rate
}
func (this *AACAudioSpecificConfig) Channel() int {
return this.channels
}
func ASCForMP4(ascData []byte, useragent string) (cfg []byte) {
asc := AACGetConfig(ascData)
if asc.ext_object_type == 0 {
cfg = make([]byte, len(ascData))
copy(cfg, ascData)
return
}
if len(useragent) > 0 {
useragent = strings.ToLower(useragent)
}
switch useragent {
case "firefox":
if asc.sampling_index >= AOT_AAC_SCALABLE {
asc.object_type = AOT_SBR
asc.ext_sampling_index = asc.sampling_index - 3
cfg = make([]byte, 4)
} else {
asc.object_type = AOT_AAC_LC
asc.ext_sampling_index = asc.sampling_index
cfg = make([]byte, 2)
}
case "android":
asc.object_type = AOT_AAC_LC
asc.ext_sampling_index = asc.sampling_index
cfg = make([]byte, 2)
default:
asc.object_type = AOT_SBR
asc.ext_sampling_index = asc.sampling_index
cfg = make([]byte, 4)
if asc.sampling_index >= AOT_AAC_SCALABLE {
asc.ext_sampling_index = asc.sampling_index - 3
} else if asc.chan_config == 1 {
asc.object_type = AOT_AAC_LC
asc.ext_sampling_index = asc.sampling_index
cfg = make([]byte, 2)
}
}
cfg[0] = byte(asc.object_type << 3)
cfg[0] |= byte((asc.sampling_index & 0xf) >> 1)
cfg[1] = byte((asc.sampling_index & 0xf) << 7)
cfg[1] |= byte((asc.chan_config & 0xf) << 3)
if asc.object_type == AOT_SBR {
cfg[1] |= byte((asc.ext_sampling_index & 0xf) >> 1)
cfg[2] = byte((asc.ext_sampling_index & 1) << 7)
cfg[2] |= (2 << 2)
cfg[3] = 0
}
return
}
|
package v1
import (
"github.com/freelifer/gohelper/pkg/e"
"github.com/gin-gonic/gin"
)
// @Summary 密码列表
// @Tags passwd
// @Produce json
// @Success 200 {string} json "{"code":200,"data":{"session_id":"xxxxxxxxxxx"},"msg":"ok"}"
// @Router /v1/passwds [get]
func PasswdList(c *gin.Context) {
e.SuccessJSON(c, gin.H{"PasswdList": "PasswdList"})
}
// @Summary 密码详情
// @Tags passwd
// @Produce json
// @Success 200 {string} json "{"code":200,"data":{"session_id":"xxxxxxxxxxx"},"msg":"ok"}"
// @Router /v1/passwds [get]
func GetPasswd(c *gin.Context) {
e.SuccessJSON(c, gin.H{"GetPasswd": "GetPasswd"})
}
// @Summary 更新密码信息
// @Tags passwd
// @Produce json
// @Success 200 {string} json "{"code":200,"data":{"session_id":"xxxxxxxxxxx"},"msg":"ok"}"
// @Router /v1/passwds [get]
func EditPasswd(c *gin.Context) {
e.SuccessJSON(c, gin.H{"EditPasswd": "EditPasswd"})
}
// @Summary 创建密码
// @Tags passwd
// @Produce json
// @Success 200 {string} json "{"code":200,"data":{"session_id":"xxxxxxxxxxx"},"msg":"ok"}"
// @Router /v1/passwds [get]
func AddPasswd(c *gin.Context) {
e.SuccessJSON(c, gin.H{"AddPasswd": "AddPasswd"})
}
|
package api
import (
"encoding/json"
"github.com/EmpregoLigado/cron-srv/mock"
"github.com/EmpregoLigado/cron-srv/models"
"github.com/nbari/violetear"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)
func TestEventsIndex(t *testing.T) {
schedulerMock := mock.NewScheduler()
repoMock := mock.NewRepo()
h := NewAPIHandler(repoMock, schedulerMock)
res := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/v1/events", nil)
if err != nil {
t.Errorf("Expected initialize request %s", err)
}
r := violetear.New()
r.HandleFunc("/v1/events", h.EventsIndex, "GET")
r.ServeHTTP(res, req)
events := []models.Event{}
if err := json.NewDecoder(res.Body).Decode(&events); err != nil {
t.Errorf("Expected to decode response json %s", err)
}
if len(events) == 0 {
t.Errorf("Expected response to not be empty %s", strconv.Itoa(len(events)))
}
if res.Code != http.StatusOK {
t.Errorf("Expected status %d to be equal %d", res.Code, http.StatusOK)
}
}
func TestEventsIndexByStatus(t *testing.T) {
schedulerMock := mock.NewScheduler()
repoMock := mock.NewRepo()
h := NewAPIHandler(repoMock, schedulerMock)
res := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/v1/events?status=active", nil)
if err != nil {
t.Errorf("Expected initialize request %s", err)
}
r := violetear.New()
r.HandleFunc("/v1/events", h.EventsIndex, "GET")
r.ServeHTTP(res, req)
if !repoMock.ByStatus {
t.Errorf("Expected to search by status")
}
if res.Code != http.StatusOK {
t.Errorf("Expected status %d to be equal %d", res.Code, http.StatusOK)
}
}
func TestEventsIndexByExpression(t *testing.T) {
schedulerMock := mock.NewScheduler()
repoMock := mock.NewRepo()
h := NewAPIHandler(repoMock, schedulerMock)
res := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/v1/events?expression=* * * * *", nil)
if err != nil {
t.Errorf("Expected initialize request %s", err)
}
r := violetear.New()
r.HandleFunc("/v1/events", h.EventsIndex, "GET")
r.ServeHTTP(res, req)
if !repoMock.ByExpression {
t.Errorf("Expected to search by expression")
}
if res.Code != http.StatusOK {
t.Errorf("Expected status %d to be equal %d", res.Code, http.StatusOK)
}
}
func TestEventCreate(t *testing.T) {
schedulerMock := mock.NewScheduler()
repoMock := mock.NewRepo()
h := NewAPIHandler(repoMock, schedulerMock)
res := httptest.NewRecorder()
body := strings.NewReader(`{"url":"http://foo.com"}`)
req, err := http.NewRequest("POST", "/v1/events", body)
if err != nil {
t.Errorf("Expected initialize request %s", err)
}
r := violetear.New()
r.HandleFunc("/v1/events", h.EventsCreate, "POST")
r.ServeHTTP(res, req)
if !repoMock.Created {
t.Error("Expected repo create to be called")
}
if !schedulerMock.Created {
t.Error("Expected scheduler create to be called")
}
if res.Code != http.StatusCreated {
t.Errorf("Expected status %d to be equal %d", res.Code, http.StatusOK)
}
}
func TestEventShow(t *testing.T) {
schedulerMock := mock.NewScheduler()
repoMock := mock.NewRepo()
h := NewAPIHandler(repoMock, schedulerMock)
res := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/v1/events/1", nil)
if err != nil {
t.Errorf("Expected initialize request %s", err)
}
r := violetear.New()
r.AddRegex(":id", `^\d+$`)
r.HandleFunc("/v1/events/:id", h.EventsShow, "GET")
r.ServeHTTP(res, req)
if !repoMock.Found {
t.Error("Expected repo findEventById to be called")
}
if res.Code != http.StatusOK {
t.Errorf("Expected status %d to be equal %d", res.Code, http.StatusOK)
}
}
func TestEventsUpdate(t *testing.T) {
schedulerMock := mock.NewScheduler()
repoMock := mock.NewRepo()
h := NewAPIHandler(repoMock, schedulerMock)
res := httptest.NewRecorder()
body := strings.NewReader(`{"url":"http://foo.com"}`)
req, err := http.NewRequest("PUT", "/v1/events/1", body)
if err != nil {
t.Errorf("Expected initialize request %s", err)
}
r := violetear.New()
r.AddRegex(":id", `^\d+$`)
r.HandleFunc("/v1/events/:id", h.EventsUpdate, "PUT")
r.ServeHTTP(res, req)
if !repoMock.Updated {
t.Error("Expected repo update to be called")
}
if !schedulerMock.Updated {
t.Error("Expected scheduler update to be called")
}
if res.Code != http.StatusOK {
t.Errorf("Expected status %d to be equal %d", res.Code, http.StatusOK)
}
}
|
package controller
import (
"github.com/bearname/videohost/internal/videoserver/domain"
"github.com/bearname/videohost/internal/videoserver/domain/model"
)
type CreatePlayListRequest struct {
Name string `json:"name"`
Privacy model.PrivacyType `json:"privacy"`
VideosId []string `json:"videos"`
}
type PlayListVideoModificationRequest struct {
Action domain.Action `json:"act"`
Videos []string `json:"videos"`
}
|
/*
package core
модуль time_to_ready
содержит объекты, которые змейка может съесть
*/
package game
import (
"github.com/JoelOtter/termloop"
)
//createTimeObj создать отрисовку обратного отсчёта
func createTimeObj(text string) *timeToReady {
timeObj := new(timeToReady)
timeObj.Text = termloop.NewText(7, (high/2)-1,
text,
termloop.ColorWhite,
termloop.ColorDefault)
return timeObj
}
|
package utils
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestValidate64HexHash(t *testing.T) {
valid := "1A2E95A2DCF03143297572EAEC496F6913D5001D2F28A728B35CB274294D5A14"
assert.Equal(t, true, Validate64HexHash(valid))
// invalid, not hex
invalid := "1A2E95A2DCZ03143297572EAEC496F6913D5001D2F28A728B35CB274294D5A14"
assert.Equal(t, false, Validate64HexHash(invalid))
invalid = "1A2E95A2DCF03143297572EAEC496F6913D5001D2F28A728B35CB274294D5A1"
assert.Equal(t, false, Validate64HexHash(invalid))
}
|
package Plugins
import (
"../Misc"
"../Parse"
"fmt"
"golang.org/x/crypto/ssh"
"sync"
"time"
)
const SSHPORT = 22
func SSH(info Misc.HostInfo, ch chan int, wg *sync.WaitGroup) {
var err error
config := &ssh.ClientConfig{
User: info.Username,
Auth: []ssh.AuthMethod{ssh.Password(info.Password)},
Timeout: time.Duration(info.Timeout) * time.Second,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
ip := fmt.Sprintf("%s:%d", info.Host, info.Port)
client, err := ssh.Dial("tcp", ip, config)
if err != nil && info.ErrShow {
Misc.ErrPrinter.Println(err.Error())
} else if err == nil {
success += 1
client.Close()
info.PrintSuccess()
if info.Output != "" {
info.OutputTXT()
}
}
wg.Done()
<-ch
}
func SSHConn(info *Misc.HostInfo, ch chan int) {
var hosts, usernames, passwords []string
var err error
var wg = sync.WaitGroup{}
stime := time.Now()
if info.Ports == "" {
info.Port = SSHPORT
} else {
p, _ := Parse.ParsePort(info.Ports)
info.Port = p[0]
}
hosts, err = Parse.ParseIP(info.Host)
Misc.CheckErr(err)
usernames, err = Parse.ParseUser(info)
Misc.CheckErr(err)
passwords, err = Parse.ParsePass(info)
Misc.CheckErr(err)
wg.Add(len(hosts) * len(usernames) * len(passwords))
Misc.InfoPrinter.Println("Total length", len(hosts)*len(usernames)*len(passwords))
for _, host := range hosts {
for _, user := range usernames {
for _, pass := range passwords {
info.Host = host
info.Username = user
info.Password = pass
go SSH(*info, ch, &wg)
ch <- 1
}
}
}
wg.Wait()
end := time.Since(stime)
Misc.InfoPrinter.Println("All Done")
Misc.InfoPrinter.Println("Number of successes:", success)
Misc.InfoPrinter.Println("Time consumed:", end)
}
|
package humanize
import (
"go/ast"
"strings"
)
// FuncType is the single function
type FuncType struct {
pkg *Package
Parameters []*Variable
Results []*Variable
}
func (f *FuncType) getDefinitionWithName(name string) string {
return "func " + name + f.Sign()
}
// Sign return the function sign
func (f *FuncType) Sign() string {
var args, res []string
for a := range f.Parameters {
args = append(args, f.Parameters[a].Type.String())
}
for a := range f.Results {
res = append(res, f.Results[a].Type.String())
}
result := "(" + strings.Join(args, ",") + ")"
if len(res) > 1 {
result += " (" + strings.Join(res, ",") + ")"
} else {
result += " " + strings.Join(res, ",")
}
return result
}
// String is the string representation of func type
func (f *FuncType) String() string {
return "func " + f.Sign()
}
// Package is the func package
func (f *FuncType) Package() *Package {
return f.pkg
}
// Equal check func type equality
func (f *FuncType) Equal(t Type) bool {
v, ok := t.(*FuncType)
if !ok {
return false
}
if !f.pkg.Equal(v.pkg) {
return false
}
if len(f.Parameters) != len(v.Parameters) {
return false
}
if len(f.Results) != len(v.Results) {
return false
}
for i := range f.Parameters {
if !f.Parameters[i].Type.Equal(v.Parameters[i].Type) {
return false
}
}
for i := range f.Results {
if !f.Results[i].Type.Equal(v.Results[i].Type) {
return false
}
}
return true
}
func (f *FuncType) lateBind() error {
for i := range f.Parameters {
if err := f.Parameters[i].lateBind(); err != nil {
return err
}
}
for i := range f.Results {
if err := f.Results[i].lateBind(); err != nil {
return err
}
}
return nil
}
func getVariableList(p *Package, fl *File, f *ast.FieldList) []*Variable {
var res []*Variable
if f == nil {
return res
}
for i := range f.List {
n := f.List[i]
if n.Names != nil {
for in := range n.Names {
p := variableFromExpr(p, fl, nameFromIdent(n.Names[in]), f.List[i].Type)
res = append(res, p)
}
} else {
// Its probably without name part (ie return variable)
p := variableFromExpr(p, fl, "", f.List[i].Type)
res = append(res, p)
}
}
return res
}
func getFunc(p *Package, f *File, t *ast.FuncType) Type {
return &FuncType{
pkg: p,
Parameters: getVariableList(p, f, t.Params),
Results: getVariableList(p, f, t.Results),
}
}
|
package resin
import "testing"
var testToken string = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Mjc1LCJ1c2VybmFtZSI6InBhYmxvY2FycmFuemEiLCJlbWFpbCI6InNvbWVvbmVAZ21haWwuY29tIiwic29jaWFsX3NlcnZpY2VfYWNjb3VudCI6W10sImhhc19kaXNhYmxlZF9uZXdzbGV0dGVyIjpmYWxzZSwiand0X3NlY3JldCI6InNlY3JldHNlY3JldCIsImhhc1Bhc3N3b3JkU2V0Ijp0cnVlLCJuZWVkc1Bhc3N3b3JkUmVzZXQiOmZhbHNlLCJwdWJsaWNfa2V5IjpmYWxzZSwiZmVhdHVyZXMiOltdLCJpbnRlcmNvbVVzZXJOYW1lIjoiW1NUQUdJTkddIHBhYmxvY2FycmFuemEiLCJpbnRlcmNvbVVzZXJIYXNoIjoic29tZWhhc2giLCJwZXJtaXNzaW9ucyI6W10sImlhdCI6MTQ2NjI3MTc5MywiZXhwIjoxNDY2ODc2NTkzfQ.uXIMNA2OTLPmlkYc_fE6iECAy6dF6c_yYwxs8yvB5eU`
func TestGetUserId(t *testing.T) {
if id, err := GetUserId(testToken); err != nil {
t.Error(err)
} else if id != "275" {
t.Errorf("Got wrong userId: %d", id)
}
}
|
package tests
import (
"testing"
"github.com/WindomZ/quizzee"
"github.com/WindomZ/testify/assert"
)
func TestAnswer_Parse(t *testing.T) {
a := quizzee.NewAnswer("鲁迅:周樟寿")
assert.NoError(t, a.Parse())
assert.Equal(t, []string{"鲁迅", "周樟寿"}, a.Keys)
}
|
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", "postgres://jeoysqgj:Yqpkng49GujaIUn9LrGfzP1bRD3JHFAM@suleiman.db.elephantsql.com:5432/jeoysqgj")
if err != nil {
log.Fatal("Connect to database error", err)
}
defer db.Close()
stmt, err := db.Prepare("UPDATE todos SET status=$2 where id=$1")
if err != nil {
log.Fatal("can't prepare statement update")
}
if _, err := stmt.Exec(1, "inactive"); err != nil {
log.Fatal("error execite update ", err)
}
fmt.Println("update success")
}
|
package wallet
import "testing"
func TestWallet(t *testing.T) {
t.Run("Deposit", func(t *testing.T) {
wallet := Wallet{}
wallet.Deposit(Bitcoin(10))
want := Bitcoin(10)
assertBalance(t, wallet, want)
})
t.Run("Withdraw", func(t *testing.T) {
wallet := Wallet{Bitcoin(10)}
err := wallet.Withdraw(Bitcoin(10))
want := Bitcoin(0)
assertBalance(t, wallet, want)
assertNoError(t, err)
})
t.Run("Withdraw insufficient funds", func(t *testing.T) {
wallet := Wallet{Bitcoin(10)}
err := wallet.Withdraw(Bitcoin(11))
assertBalance(t, wallet, Bitcoin(10))
assertError(t, err, ErrInsufficientFunds)
})
}
func TestBitcoinStringer(t *testing.T) {
btc := Bitcoin(10)
want := "10 BTC"
got := btc.String()
if got != want {
t.Errorf("got %s want %s", got, want)
}
}
func assertBalance(t *testing.T, w Wallet, want Bitcoin) {
t.Helper()
got := w.Balance()
if got != want {
t.Errorf("got %s want %s", got, want)
}
}
func assertError(t *testing.T, err error, want error) {
t.Helper()
if err == nil {
t.Fatal("expected error but didn't got one")
}
if err != want {
t.Errorf("expected error %q got %q", want, err)
}
}
func assertNoError(t *testing.T, err error) {
if err != nil {
t.Errorf("unexpected error: %q", err)
}
}
|
package validator
import (
"strings"
)
type EmailDomainAllowed struct {
Value string
AllowedDomains []string
}
func (v EmailDomainAllowed) Validate() (bool, Message) {
stringParts := strings.Split(v.Value, "@")
if len(stringParts) < 2 {
return false, Message("Email value doesnt contain '@'")
}
domain := stringParts[1]
domain = strings.TrimSpace(domain)
for _, allowedDomain := range v.AllowedDomains {
if domain == allowedDomain {
return true, ""
}
}
return false, "Email domain not allowed"
}
|
package serato_test
import "testing"
func TestReadSession(t *testing.T) {
t.Skip()
}
|
// Package main is the entrypoint for the github.com/wreckerlabs/goliccop utility
// which helps developers honor license demands.
package main
import (
"errors"
"flag"
"fmt"
"go/parser"
"go/token"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"github.com/dustin/go-humanize"
)
var (
verbose = flag.Bool("v", false, "verbose mode")
root = flag.String("p", ".", "the path to scan")
)
var (
gopath string
licenseFile string
countOfObserved int64
countOfInspected int64
countOfNonCompliant int64
uniquePackages = []string{}
report = make(map[string]*ReportEntry)
m = sync.Mutex{}
)
var (
// ErrPackageSourceNotFound represents an error when a imported package's source-code
// could not be found in $GOPATH
ErrPackageSourceNotFound = errors.New("Unable to locate package sourcecode.")
)
// ReportEntry organized package inspection details
type ReportEntry struct {
Package string
Importers []string
Licensed bool
License []byte
Src string
HasLicense bool
SourceFound bool
ExpectedLicense bool
}
// ErrLicenseSearch organizes exception details for license discovery.
type ErrLicenseSearch struct {
Package string
Path string
Exception string
}
// Error complys with the error interface
func (err ErrLicenseSearch) Error() string {
return fmt.Sprintf(err.Exception, err.Package, err.Path)
}
// ErrLicenseNotFound organizes details for packages where licenses could not be found.
type ErrLicenseNotFound struct {
Package string
Path string
Exception string
}
// Error complys with the error interface
func (err ErrLicenseNotFound) Error() string {
return fmt.Sprintf(err.Exception, err.Package, err.Path)
}
// GoLicCop
func main() {
flag.Parse()
gopath = os.Getenv("GOPATH")
if len(gopath) == 0 {
fmt.Printf("\nError: $GOPATH undefined\n")
}
fmt.Printf("\nLicense Cop: Scanning %s\n\n", *root)
err := filepath.Walk(*root, walker)
if err != nil {
fmt.Printf("Error reading directory. Please verify the path provided: %s\n", *root)
os.Exit(1)
}
renderReport("all")
renderSummary()
}
// walker walks a directory scanning for and inspecting any .go files it finds.
func walker(path string, f os.FileInfo, err error) error {
countOfObserved++
if filepath.Ext(f.Name()) == ".go" {
inspect(path)
}
return nil
}
// inspect analyzes go files and processes import statements.
func inspect(path string) {
countOfInspected++
source, err := ioutil.ReadFile(path)
if err != nil {
fmt.Printf("\t\tUnable to read file. Error: %s\n", err)
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, source, 0)
if err != nil {
panic(err)
}
for _, importStmt := range f.Imports {
registerImport(importStmt.Path.Value, path)
}
}
// registerImport registers imported packages and tracks files that import
// each package. As this function learns of new packages it attempts to discover
// the license file.
func registerImport(pkg string, importer string) {
// If we already know about this package simply register the caller
m.Lock()
v, ok := report[pkg]
m.Unlock()
if ok {
v.Importers = append(v.Importers, importer)
return
}
// Register a new package
var license []byte
var sourceFound bool
var licensed bool
expectLicense := strings.Index(pkg, ".") >= 0
if expectLicense {
pkgSrcPath, licensePath, err := discoverLicense(pkg)
switch err.(type) {
case ErrLicenseNotFound:
if *verbose {
fmt.Printf("\t\tWARNING: License file not found for package %s imported by %s. Error: %s\n", pkg, importer, err.Error())
}
case ErrLicenseSearch:
fmt.Printf("\t\tWARNING: The source code for the package %s imported by %s could not be found at %s. Error: %s\n", pkg, importer, pkgSrcPath, err.Error())
case nil:
sourceFound = true
licensed = true
license, err = parseLicense(licensePath, pkg)
if err != nil {
panic(err)
}
}
}
m.Lock()
report[pkg] = &ReportEntry{
Package: pkg,
Importers: []string{importer},
License: license,
HasLicense: licensed,
SourceFound: sourceFound,
ExpectedLicense: expectLicense,
}
m.Unlock()
}
// parseLicense reads a license file and returns the content. This method will
// soon be enhanced to try to determine the type of license.
func parseLicense(licensePath string, pkg string) (license []byte, err error) {
license, err = ioutil.ReadFile(licensePath)
if err != nil {
return []byte{}, &ErrLicenseSearch{Exception: "Package %s license file found at %s but it could not be read", Package: pkg, Path: licensePath}
}
return license, nil
}
// discoverLicense extrapolates a package as imported into go sourcecode and
// searches for a license file within the package's source code.
func discoverLicense(pkg string) (pkgPath string, licensePath string, err error) {
pkgPath = gopath + "/src/" + pkg[1:len(pkg)-1]
files, err := ioutil.ReadDir(pkgPath)
if err != nil {
return pkgPath, licensePath, &ErrLicenseSearch{Exception: "Package %s source-code not found at %s", Package: pkg, Path: pkgPath}
}
for _, f := range files {
licensePath = pkgPath + "/" + f.Name()
if strings.Contains(strings.ToLower(f.Name()), "license") {
return pkgPath, licensePath, nil
}
}
return pkgPath, licensePath, &ErrLicenseNotFound{Exception: "Package %s license not found in root of %s", Package: pkg, Path: pkgPath}
}
// renderReport communicates the results of a GoLicCop scan to stdout.
func renderReport(mode string) {
switch mode {
case "licensed":
fmt.Printf("\n\n============== Packages Licensed ==============\n\n")
for _, v := range report {
if v.HasLicense {
fmt.Printf(" %s\n", v.Package)
}
}
case "not searched":
if *verbose {
fmt.Printf("\n\n============== Packages Not Searched ==============\n\n")
for _, v := range report {
if !v.ExpectedLicense {
fmt.Printf(" %s\n", v.Package)
for _, importer := range v.Importers {
fmt.Printf(" Imported by..........: %s\n", importer)
}
}
}
}
case "missing":
fmt.Printf("\n\n============== Packages Not Licensed ==============\n\n")
for _, v := range report {
if v.ExpectedLicense && !v.HasLicense {
fmt.Printf(" %s\n", v.Package)
if *verbose {
for _, importer := range v.Importers {
fmt.Printf(" Imported by..........: %s\n", importer)
}
}
}
}
case "all":
renderReport("licensed")
renderReport("not searched")
renderReport("missing")
}
}
// renderSummary communicates the summary of a GoLicCop scan to stdout.
func renderSummary() {
fmt.Printf(" \n\nSummary:\n\n")
fmt.Printf(" Total Packages Used....: %s\n", humanize.Comma(int64(len(report))))
fmt.Printf(" Files Observed.........: %s\n", humanize.Comma(countOfObserved))
fmt.Printf(" Files Inspected........: %s\n", humanize.Comma(countOfInspected))
fmt.Printf(" out of compliance....: %s\n", humanize.Comma(countOfNonCompliant))
}
|
package utils
import (
"testing"
"time"
"github.com/jonmorehouse/gatekeeper/gatekeeper/test"
)
type validConfig struct {
Str string `flag:"str" default:"default"`
Dur time.Duration `flag:"duration" default:"1m"`
Bool bool `flag:"bool" default:"false"`
Uint uint `flag:"uint" default:"1000"`
Int int `flag:"int" default:"1000"`
Float64 float64 `flag:"float64" default:"1000.0"`
StrList []string `flag:"str_list" default:"c,d,e"`
}
type invalidConfig struct {
Invalid struct{} `flag:"invalid"`
}
type requiredConfig struct {
Required string `flag:"required" required:"true"`
}
func TestConfig__OK(t *testing.T) {
var cfg validConfig
opts := map[string]interface{}{
"str": "str",
"duration": "1s",
"bool": "true",
"uint": "0",
"int": "10",
"float64": "10.4",
"str_list": "a,b,c",
}
test.AssertNil(t, ParseConfig(opts, &cfg))
test.AssertEqual(t, cfg.Str, "str")
test.AssertEqual(t, cfg.Dur, time.Second)
test.AssertEqual(t, cfg.Bool, true)
test.AssertEqual(t, cfg.Uint, uint(0))
test.AssertEqual(t, cfg.Int, int(10))
test.AssertEqual(t, cfg.Float64, float64(10.4))
test.AssertEqual(t, cfg.StrList, []string{"a", "b", "c"})
}
func TestConfig__DefaultOK(t *testing.T) {
var cfg validConfig
opts := map[string]interface{}{}
test.AssertNil(t, ParseConfig(opts, &cfg))
test.AssertEqual(t, cfg.Str, "default")
test.AssertEqual(t, cfg.Dur, time.Minute)
test.AssertEqual(t, cfg.Bool, false)
test.AssertEqual(t, cfg.Uint, uint(1000))
test.AssertEqual(t, cfg.Int, int(1000))
test.AssertEqual(t, cfg.Float64, float64(1000.0))
test.AssertEqual(t, cfg.StrList, []string{"c", "d", "e"})
}
func TestConfig__InvalidType(t *testing.T) {
opts := map[string]interface{}{
"invalid": "invalid",
}
var invalid invalidConfig
err := ParseConfig(opts, &invalid)
test.AssertNotNil(t, err)
test.AssertEqual(t, InvalidTypeErr, err)
}
func TestConfig__InvalidRawValue(t *testing.T) {
opts := map[string]interface{}{
"str": struct{}{},
}
var cfg validConfig
err := ParseConfig(opts, &cfg)
test.AssertNotNil(t, err)
test.AssertEqual(t, InvalidRawValueErr, err)
}
func TestConfig__BoolParsing(t *testing.T) {
opts := map[string]interface{}{
"bool": true,
}
var cfg validConfig
err := ParseConfig(opts, &cfg)
test.AssertNil(t, err)
test.AssertEqual(t, cfg.Bool, true)
}
func TestConfig__BoolInvalidDest(t *testing.T) {
opts := map[string]interface{}{
"str": true,
}
var cfg validConfig
err := ParseConfig(opts, &cfg)
test.AssertNotNil(t, err)
}
func TestConfig__Required(t *testing.T) {
var cfg requiredConfig
err := ParseConfig(map[string]interface{}{}, &cfg)
test.AssertNotNil(t, err)
_, ok := err.(RequiredError)
test.AssertTrue(t, ok)
}
|
package router
import (
"fmt"
"log"
s "github.com/nedp/command/sequence"
)
type ContParams struct {
ID int
Router *Router
}
func (ContParams) IsParams() {} // Marker
// Need to use a closure to capture the router.
func NewContParams(r *Router) func() Params {
return func() Params {
p := new(ContParams)
p.Router = r
return p
}
}
func NewContSequence(routeParams Params) s.RunAller {
id := routeParams.(*ContParams).ID
r := routeParams.(*ContParams).Router
outCh := make(chan string)
// Get the command, reporting failure if it's not there.
sl := <-r.slots
cmd, err := sl.Command(id)
r.slots <- sl
if err != nil {
msg := fmt.Sprintf("Couldn't find the command in slot %d: %s", id, err.Error())
return s.FirstJust(sendFailure(outCh, msg)).End(outCh)
}
// Send the command's name and slot.
name := cmd.Name()
builder := s.FirstJust(sendIntro(outCh, "Continuing", id, name))
// Continue the command.
// If a failure occurs, report it, close the channel, and end the sequence.
wasAlreadyContinuing, err := cmd.Cont()
if err != nil {
builder = builder.ThenJust(sendFailure(outCh, err.Error()))
log.Printf("failed to continue command `%s` in slot %d", name, id)
return builder.End(outCh)
}
// Report whether the command was already continuing, or if we contued it.
if wasAlreadyContinuing {
builder = builder.ThenJust(sendString(outCh, "Command was already continuing"))
} else {
builder = builder.ThenJust(sendString(outCh, "Command is now continuing"))
}
// Close the channel
builder = builder.ThenJust(closeCh(outCh))
log.Printf("continuing command `%s` in slot %d", name, id)
return builder.End(outCh)
}
|
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
// Data - some data to process
type Data struct {
Before string
After string
}
func main() {
// init our random number generator
rand.Seed(time.Now().Unix())
// blocking channels - no buffer specified
// only a single Data instance can be placed on the channel
// at a time
input := make(chan Data)
output := make(chan Data)
// this runs seprately from the rest of the instructions in main
// it blocks until main() sends it something to do. It is
// started first so that something is listening on the input
// channel
go func(in <-chan Data, out chan<- Data) {
// close the output channel when this
// function exits. Notice that we
// specified that it is read from with "<-chan"
// and that out is written to with "chan<-".
// the arrow always points to the left.
defer close(out)
// iterate over the input channel
// changing the case of the Before field
// and place the modified struct on the output
// channel
for item := range input {
// Note: this loop terminate when the input
// channel is closed
item.After = strings.ToUpper(item.Before)
// place the updated item on the output channel
out <- item
}
}(input, output)
// Now, lets give the first go routine something to process by starting a
// second go routine that generates lowercase letters and places them in our Data
// struct. This tool runs in the background...
go func(in chan<- Data) {
// loop forever
for {
// initialize x as a "Data" type with the "Brefore" field set to a random lowercase letter
x := Data{Before: randChar()}
// place it on the channel
in <- x
}
}(input)
// Process the output channel
for result := range output {
fmt.Printf("Before: %s => After: %s\n", result.Before, result.After)
}
}
// return a random lowercase ascii character
func randChar() string {
// ascii 97-122 lowerdcase a-z
c := rand.Intn(122-97) + 97 + 1
return fmt.Sprintf("%s", string(c))
}
|
package suites
import (
"fmt"
"testing"
"github.com/go-rod/rod"
)
func (rs *RodSession) verifyIsPublic(t *testing.T, page *rod.Page) {
page.MustElementR("body", "headers")
rs.verifyURLIs(t, page, fmt.Sprintf("%s/headers", PublicBaseURL))
}
|
package csms
import (
"context"
"net"
"sync"
"testing"
insecure "gx/ipfs/QmWmeXRTSyWvjPQZgXjXTj2aP74tMSgJwWi1SAvHsvBJVj/go-conn-security/insecure"
sst "gx/ipfs/QmWmeXRTSyWvjPQZgXjXTj2aP74tMSgJwWi1SAvHsvBJVj/go-conn-security/test"
)
func TestCommonProto(t *testing.T) {
var at, bt SSMuxer
atInsecure := insecure.New("peerA")
btInsecure := insecure.New("peerB")
at.AddTransport("/plaintext/1.0.0", atInsecure)
bt.AddTransport("/plaintext/1.1.0", btInsecure)
bt.AddTransport("/plaintext/1.0.0", btInsecure)
sst.SubtestRW(t, &at, &bt, "peerA", "peerB")
}
func TestNoCommonProto(t *testing.T) {
var at, bt SSMuxer
atInsecure := insecure.New("peerA")
btInsecure := insecure.New("peerB")
at.AddTransport("/plaintext/1.0.0", atInsecure)
bt.AddTransport("/plaintext/1.1.0", btInsecure)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
a, b := net.Pipe()
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
defer a.Close()
_, err := at.SecureInbound(ctx, a)
if err == nil {
t.Fatal("conection should have failed")
}
}()
go func() {
defer wg.Done()
defer b.Close()
_, err := bt.SecureOutbound(ctx, b, "peerA")
if err == nil {
t.Fatal("connection should have failed")
}
}()
wg.Wait()
}
|
package api
import (
"context"
internalclient "github.com/chanioxaris/go-datagovgr/internal/client"
"github.com/chanioxaris/go-datagovgr/types"
)
// Health holds required info to consume Health related endpoints.
type Health struct {
client *internalclient.Client
}
// NewHealth creates a new instance.
func NewHealth(client *internalclient.Client) *Health {
return &Health{client: client}
}
// COVID19VaccinationStatistics retrieves general public COVID-19 vaccination statistics by region and day.
func (h *Health) COVID19VaccinationStatistics(ctx context.Context, params ...QueryParameter) ([]*types.COVID19VaccinationStatistics, error) {
queryParams := make(map[string]string)
for _, param := range params {
param(queryParams)
}
response := make([]*types.COVID19VaccinationStatistics, 0)
if err := h.client.MakeRequestGET(ctx, "mdg_emvolio", &response, queryParams); err != nil {
return nil, err
}
return response, nil
}
// InspectionsAndViolations retrieves annual statistics of food companies inspections and violations.
func (h *Health) InspectionsAndViolations(ctx context.Context) ([]*types.InspectionsAndViolations, error) {
response := make([]*types.InspectionsAndViolations, 0)
if err := h.client.MakeRequestGET(ctx, "efet_inspections", &response, nil); err != nil {
return nil, err
}
return response, nil
}
// NumberOfPharmacists retrieves the number of active pharmacists including new entrants and retiring professionals.
func (h *Health) NumberOfPharmacists(ctx context.Context) ([]*types.NumberOfPharmacists, error) {
response := make([]*types.NumberOfPharmacists, 0)
if err := h.client.MakeRequestGET(ctx, "minhealth_pharmacists", &response, nil); err != nil {
return nil, err
}
return response, nil
}
// NumberOfPharmacies retrieves the number of active pharmacies including new entrants and retiring professionals.
func (h *Health) NumberOfPharmacies(ctx context.Context) ([]*types.NumberOfPharmacies, error) {
response := make([]*types.NumberOfPharmacies, 0)
if err := h.client.MakeRequestGET(ctx, "minhealth_pharmacies", &response, nil); err != nil {
return nil, err
}
return response, nil
}
// NumberOfDoctors retrieves the number of active doctors including new entrants and retiring professionals.
func (h *Health) NumberOfDoctors(ctx context.Context) ([]*types.NumberOfDoctors, error) {
response := make([]*types.NumberOfDoctors, 0)
if err := h.client.MakeRequestGET(ctx, "minhealth_doctors", &response, nil); err != nil {
return nil, err
}
return response, nil
}
// NumberOfDentists retrieves the number of active dentists including new entrants and retiring professionals.
func (h *Health) NumberOfDentists(ctx context.Context) ([]*types.NumberOfDentists, error) {
response := make([]*types.NumberOfDentists, 0)
if err := h.client.MakeRequestGET(ctx, "minhealth_dentists", &response, nil); err != nil {
return nil, err
}
return response, nil
}
|
package debug
import (
"fmt"
"github.com/darkliquid/leader1/state"
"html/template"
"log"
"net"
"net/http"
_ "net/http/pprof"
"os"
"runtime"
"sync"
)
var memTemplate string = `<html><head><title>Memstats</title></head><body>
<h1>Memstats</h1>
<h2>General</h2>
<dl>
<dt>Alloc</dt>
<dd>{{.Alloc}}</dd>
<dt>TotalAlloc</dt>
<dd>{{.TotalAlloc}}</dd>
<dt>Sys</dt>
<dd>{{.Sys}}</dd>
<dt>Lookups</dt>
<dd>{{.Lookups}}</dd>
<dt>Mallocs</dt>
<dd>{{.Mallocs}}</dd>
<dt>Frees</dt>
<dd>{{.Frees}}</dd>
</dl>
<h2>Heap</h2>
<dl>
<dt>HeapAlloc</dt>
<dd>{{.HeapAlloc}}</dd>
<dt>HeapSys</dt>
<dd>{{.HeapSys}}</dd>
<dt>HeapIdle</dt>
<dd>{{.HeapIdle}}</dd>
<dt>HeapInuse</dt>
<dd>{{.HeapInuse}}</dd>
<dt>HeapReleased</dt>
<dd>{{.HeapReleased}}</dd>
<dt>HeapObjects</dt>
<dd>{{.HeapObjects}}</dd>
</dl>
<h2>Low-level</h2>
<dl>
<dt>StackInuse</dt>
<dd>{{.StackInuse}}</dd>
<dt>StackSys</dt>
<dd>{{.StackSys}}</dd>
<dt>MSpanInuse</dt>
<dd>{{.MSpanInuse}}</dd>
<dt>MSpanSys</dt>
<dd>{{.MSpanSys}}</dd>
<dt>MCacheInuse</dt>
<dd>{{.MCacheInuse}}</dd>
<dt>MCacheSys</dt>
<dd>{{.MCacheSys}}</dd>
<dt>BuckHashSys</dt>
<dd>{{.BuckHashSys}}</dd>
<dt>GCSys</dt>
<dd>{{.GCSys}}</dd>
<dt>OtherSys</dt>
<dd>{{.OtherSys}}</dd>
</dl>
<h2>GC</h2>
<dl>
<dt>NextGC</dt>
<dd>{{.NextGC}}</dd>
<dt>LastGC</dt>
<dd>{{.LastGC}}</dd>
<dt>PauseTotalNs</dt>
<dd>{{.PauseTotalNs}}</dd>
<dt>NumGC</dt>
<dd>{{.NumGC}}</dd>
<dt>EnableGC</dt>
<dd>{{.EnableGC}}</dd>
<dt>DebugGC</dt>
<dd>{{.DebugGC}}</dd>
</dl>
</body></html>
`
var indexTemplate string = `
<html><head><title>Debug</title></head><body>
<ul>
<li><a href="/debug/states">State tracking</a></li>
<li><a href="/debug/memstats">Memstats</a></li>
<li><a href="/debug/pprof">Profiling</a></li>
<li><a href="/debug/stop">Stop debug server</a></li>
</ul>
</body></html>
`
var stateTemplate string = `
<html><head><title>State Debug</title></head><body>
<h1>Channels</h1>
<dl>
{{range $key, $val := .}}
<dt><h2>{{$key}} Nicks</h2></dt>
{{range $nick, $priv := $val}}
<dd>
<strong>{{$nick}}</strong> - <em>
{{if $priv.Owner}}Owner{{end}}
{{if $priv.Admin}}Admin{{end}}
{{if $priv.Op}}Op{{end}}
{{if $priv.HalfOp}}HalfOp{{end}}
{{if $priv.Voice}}Voice{{end}}</em>
</dd>
{{end}}
{{end}}
</dl>
</body></html>
`
var botState *state.StateTracker
func SetState(s *state.StateTracker) {
botState = s
}
func printRuntimeInfo(w http.ResponseWriter, r *http.Request) {
m := &runtime.MemStats{}
runtime.ReadMemStats(m)
tmpl, _ := template.New("memstats").Parse(memTemplate)
// Error checking elided
tmpl.Execute(w, m)
}
func printState(w http.ResponseWriter, r *http.Request) {
if botState != nil {
stateMapping := make(map[string]map[string]*state.ChannelPrivileges)
for _, channel := range botState.Channels() {
c := botState.GetChannel(channel)
if c != nil {
stateMapping[channel] = c.Nicks
}
}
tmpl, _ := template.New("states").Parse(stateTemplate)
// Error checking elided
tmpl.Execute(w, stateMapping)
} else {
fmt.Fprint(w, "No state available")
}
}
func printDebugIndex(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, indexTemplate)
}
var running bool
var port string
var listen net.Listener
var lock sync.Mutex
var logger *log.Logger
var waiter sync.WaitGroup
var status string
func init() {
logger = log.New(os.Stdout, "[debug] ", log.LstdFlags)
status = "shut down"
}
func PrintStack() {
buf := make([]byte, 10240) // 10kb buffer
runtime.Stack(buf, true)
logger.Printf("\n\n\n\nStacktrace:\n%s\n\n\n\n", buf)
}
type conn struct {
net.Conn
once sync.Once
waitGroup *sync.WaitGroup
}
// Close closes the connection and notifies the listener that accepted it.
func (c *conn) Close() (err error) {
err = c.Conn.Close()
c.once.Do(c.waitGroup.Done)
return
}
type listener struct {
net.Listener
waitGroup *sync.WaitGroup
conns []*conn
}
// Accept waits for, accounts for, and returns the next connection to the
// listener.
func (l *listener) Accept() (c net.Conn, err error) {
c, err = l.Listener.Accept()
if nil != err {
return
}
l.waitGroup.Add(1)
tmp := &conn{
Conn: c,
waitGroup: l.waitGroup,
}
c = tmp
l.conns = append(l.conns, tmp)
return
}
// Close closes the listener. It does not wait for all connections accepted
// through the listener to be closed.
func (l *listener) Close() (err error) {
err = l.Listener.Close()
logger.Printf("%#v", l)
for _, c := range l.conns {
c.Close()
}
return
}
func StartDebugServer() (string, bool) {
lock.Lock()
defer lock.Unlock()
if running {
return port, true
}
status = "starting"
running = true
l, _ := net.Listen("tcp", ":0")
port = l.Addr().String()
logger.Printf("Started debug server on port %s", port)
listen = &listener{
Listener: l,
waitGroup: &waiter,
}
go func() {
http.HandleFunc("/debug/", printDebugIndex)
http.HandleFunc("/debug/memstats/", printRuntimeInfo)
http.HandleFunc("/debug/states/", printState)
http.HandleFunc("/debug/stop/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
StopDebugServer()
}))
http.Serve(listen, nil)
}()
status = "started"
return port, false
}
func DebugServerStatus() string {
if port == "" {
return status
}
return status + " (" + port + ")"
}
func StopDebugServer() {
lock.Lock()
defer lock.Unlock()
if status != "started" {
return
}
logger.Println("Shutting down debug server")
status = "shutting down"
if listen != nil {
listen.Close()
}
waiter.Wait()
logger.Println("Shut down debug server")
status = "shut down"
listen = nil
port = ""
running = false
}
|
package handlers
import (
"fmt"
"htmlparser/analyser"
"htmlparser/httpclient"
"os"
"github.com/gin-gonic/gin"
"github.com/montanaflynn/stats"
"htmlparser/models"
)
func Prometheus(c *gin.Context) {
appSparkMetrics, err := getMetrics()
if err != nil {
c.Error(err)
return
}
var schedulingDelays []float64
var evtsPerBatchs []float64
var processingTimes []float64
for i := 0; i < len(appSparkMetrics.Batches); i++ {
schedulingDelays = append(schedulingDelays, float64(appSparkMetrics.Batches[i].SchedulingDelay))
evtsPerBatchs = append(evtsPerBatchs, float64(appSparkMetrics.Batches[i].InputSize))
processingTimes = append(processingTimes, float64(appSparkMetrics.Batches[i].ProcessingTime))
}
// actual_events_per_second_processed
sumEvts, _ := stats.Sum(evtsPerBatchs)
sumProcessing, _ := stats.Sum(processingTimes)
str := ""
str += fmt.Sprintf("\nactual_events_per_second_processed %v", sumEvts/sumProcessing)
// actual_events_median_processed
medianEvts, _ := stats.Median(evtsPerBatchs)
medianProcessing, _ := stats.Median(processingTimes)
str += fmt.Sprintf("\nactual_events_median_processed %v", medianEvts/medianProcessing)
str += printPercentiles(evtsPerBatchs, "events_per_second", 10)
str += printPercentiles(schedulingDelays, "scheduling_delay", 1)
str += printPercentiles(processingTimes, "processing_time", 1)
str += "\n\t"
c.String(200, str)
}
func Csv(c *gin.Context) {
res, err := getMetrics()
if err != nil {
c.Error(err)
return
}
str := "Batch Time,Input Size,Scheduling Delay,Processing Time,Total Delay"
for i := 0; i < len(res.Batches); i++ {
str += fmt.Sprintf("\n%s,%d,%d,%v,%v",
res.Batches[i].BatchTime,
res.Batches[i].InputSize,
res.Batches[i].SchedulingDelay,
res.Batches[i].ProcessingTime,
res.Batches[i].TotalDelay,
)
}
c.String(200, str)
}
func printPercentiles(datas []float64, label string, coeff int) string {
avg, _ := stats.Mean(datas)
avg = avg / float64(coeff)
str := fmt.Sprintf("\n%s_avg %v", label, avg)
min, _ := stats.Min(datas)
min = min / float64(coeff)
str += fmt.Sprintf("\n%s_min %v", label, min)
str += fmt.Sprintf("\n%s_10_percentile %v", label, getPercentile(datas, 10, coeff))
str += fmt.Sprintf("\n%s_20_percentile %v", label, getPercentile(datas, 20, coeff))
str += fmt.Sprintf("\n%s_25_percentile %v", label, getPercentile(datas, 25, coeff))
str += fmt.Sprintf("\n%s_30_percentile %v", label, getPercentile(datas, 30, coeff))
str += fmt.Sprintf("\n%s_40_percentile %v", label, getPercentile(datas, 40, coeff))
str += fmt.Sprintf("\n%s_50_percentile %v", label, getPercentile(datas, 50, coeff))
str += fmt.Sprintf("\n%s_60_percentile %v", label, getPercentile(datas, 60, coeff))
str += fmt.Sprintf("\n%s_70_percentile %v", label, getPercentile(datas, 70, coeff))
str += fmt.Sprintf("\n%s_80_percentile %v", label, getPercentile(datas, 80, coeff))
str += fmt.Sprintf("\n%s_90_percentile %v", label, getPercentile(datas, 90, coeff))
str += fmt.Sprintf("\n%s_95_percentile %v", label, getPercentile(datas, 95, coeff))
max, _ := stats.Max(datas)
max = max / float64(coeff)
str += fmt.Sprintf("\n%s_max %v", label, max)
return str
}
func getPercentile(array []float64, percent int, coeff int) float64 {
percentile, _ := stats.Percentile(array, float64(percent))
return percentile / float64(coeff)
}
func getMetrics() (*models.Report, error) {
content, err := httpclient.RequestActiveSparkMasterContent()
if err != nil {
return nil, fmt.Errorf("Cannot request spark dashboard. Error detail : %s", err.Error())
}
appName := os.Getenv("SPARK_APP")
url, err := analyser.FindWorkerLinkForApp(appName, *content)
url = url + "/streaming/"
fmt.Println("Link for app name:", url)
if err != nil {
return nil, fmt.Errorf("Cannot find app url in spark main dashboard. %s", err)
}
// Now, request spark worker dashboard
login := os.Getenv("SPARK_LOGIN")
pass := os.Getenv("SPARK_PASSWORD")
content, err = httpclient.RequestPage(url, login, pass)
if err != nil {
return nil, fmt.Errorf("%s. %s", "Cannot request spark dashboard : ", err)
}
res, err := analyser.ParseSparkDashboard(*content)
if err != nil {
return nil, fmt.Errorf("Error while parsing spark worker streaming page. %s", err)
}
return res, nil
}
|
package main
import (
"fmt"
)
func main() {
fmt.Println(addDigits(678))
}
func addDigits(num int) int {
for num >= 10 {
next := 0
for num != 0 {
next = next + num%10
num /= 10
}
num = next
}
return num
}
|
package main
//"reflect"
//"strings"
//"testing"
/*
var xmltest = []struct {
xmltext string
err error
result []TalonInfo
}{
{
`<?xml version="1.0" encoding="WINDOWS-1251"?><?BSERTIF1 version="0.2"?><BIRTH_SERTIF xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<HEADER DATE="000" TO="" KPP="" INN="" FROM=""/>
<BTAL1 PREM="0" MULP="0" QTW2="0" QTW1="0" PHELP="0" CHK="1" DREG="2020.01.01">
<CERTIF DCERTIF="2020.01.01" NCERTIF="111111" SCERTIF="G"/>
<PERSON ADDRESS="" BDATE="1989.01.01" MNAME="O" FNAME="I" LNAME="F" SNILS="000-000-000 11"/>
<PASSPORT ODOC="ФМС" DDOC="2015.01.01" SDOC="1515" NDOC="111111" TDOC="14"/>
<POLICY NPOLICY="1234567" SPOLICY=""/>
<SICKLIST NLEAF="N1" SLEAF="S1"/>
<EXCCARD DCARD="2019.01.01" NCARD="1/1"/>
</BTAL1>
<BTAL1 PREM="0" MULP="0" QTW2="0" QTW1="0" PHELP="0" CHK="1" DREG="2020.02.02">
<CERTIF DCERTIF="2020.02.02" NCERTIF="222222" SCERTIF="Г"/>
<PERSON ADDRESS="" BDATE="1990.01.01" MNAME="O" FNAME="I" LNAME="F" SNILS="000-000-000 22"/>
<PASSPORT ODOC="ФМС" DDOC="2016.01.01" SDOC="1616" NDOC="222222" TDOC="14"/>
<POLICY NPOLICY="1234567" SPOLICY=""/>
<SICKLIST NLEAF="" SLEAF=""/>
<EXCCARD DCARD="2019.02.02" NCARD="2/2"/>
</BTAL1>
</BIRTH_SERTIF>`,
nil,
[]TalonInfo{
TalonInfo{
NTalon: "1",
DReg: "2020.01.01",
SCertif: "",
NCertif: "",
DCertif: "",
Snils: "",
LName: "",
FName: "",
MName: "",
BDate: "",
PassportTDoc: "",
PassportTDocName: "",
PassportNDoc: "",
PassportSDoc: "",
PassportDDoc: "",
PassportODoc: "",
SPolicy: "",
NPolicy: "",
SLeaf: "",
NLeaf: "",
NCard: "",
DCard: "",
},
},
},
}
func TestParse(t *testing.T) {
for _, test := range xmltest {
r := strings.NewReader(test.xmltext)
ti, err := Xml2Struct(r)
if err != test.err {
t.Errorf("Xml2Struct error gives \"%#v\", expected \"%#v\"",
err, test.err)
}
if !reflect.DeepEqual(ti, test.result) {
t.Errorf("Xml2Struct gives \"%#v\", expected \"%#v\"",
ti, test.result)
}
}
}
*/
|
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Println("Printing Fibonacci numbers..")
reader := bufio.NewReader(os.Stdin)
for {
generator := calculateFibonacci()
input, _ := reader.ReadString('\n')
value, err := strconv.Atoi(strings.TrimSpace(input))
if err != nil {
fmt.Println("Error: ", err.Error())
}
var result int
for i := 0; i < value; i++ {
result = generator()
}
fmt.Printf("Fibonacci number %d is: %d\n", value, result)
}
}
func calculateFibonacci() func() int {
f1 := 0
f2 := 1
return func() int {
f2, f1 = (f1 + f2), f2
return f1
}
}
|
package model
// StateOverViewResp 博客统计返回
type StateOverViewResp struct {
ID string `json:"id"`
Title string `json:"title"`
Tags []string `json:"tags"`
Author string `json:"author"`
Pv int64 `json:"pv"`
Uv int64 `json:"uv"`
}
// StatDetailResp 博客趋势详情
type StatDetailResp struct {
Date string `json:"date"`
Pv int64 `json:"pv"`
Uv int64 `json:"uv"`
} |
package main
import "fmt"
func largestPrime(n uint64) uint64 {
var largest uint64 = 2
for n > 1 {
for n%largest == 0 {
n /= largest
}
largest++
}
return largest - 1
}
func main() {
fmt.Println(largestPrime(13195))
fmt.Println(largestPrime(600851475143))
}
// Find the largest prime factor of a number.
// Note:
// Every natural number has a unique prime factorization.
// Starting from low to high, divide the number repeatedly and consume all the factors.
// Starting from 2, which is a prime. Then consider the next integer.
// At some point, one of the next integer is another factor.
// Assume this factor is a composit, then it will have a smaller prime factor,
// which should be consumed in the past, so this leads to contradiction.
// So it must be a prime.
|
package matchers
import (
"bytes"
"fmt"
"reflect"
"gx/ipfs/QmUWtNQd8JdEiYiDqNYTUcaqyteJZ2rTNQLiw3dauLPccy/gomega/format"
)
type EqualMatcher struct {
Expected interface{}
}
func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) {
if actual == nil && matcher.Expected == nil {
return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
}
// Shortcut for byte slices.
// Comparing long byte slices with reflect.DeepEqual is very slow,
// so use bytes.Equal if actual and expected are both byte slices.
if actualByteSlice, ok := actual.([]byte); ok {
if expectedByteSlice, ok := matcher.Expected.([]byte); ok {
return bytes.Equal(actualByteSlice, expectedByteSlice), nil
}
}
return reflect.DeepEqual(actual, matcher.Expected), nil
}
func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) {
actualString, actualOK := actual.(string)
expectedString, expectedOK := matcher.Expected.(string)
if actualOK && expectedOK {
return format.MessageWithDiff(actualString, "to equal", expectedString)
}
return format.Message(actual, "to equal", matcher.Expected)
}
func (matcher *EqualMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return format.Message(actual, "not to equal", matcher.Expected)
}
|
package main
import (
"fmt"
"time"
)
/* channel ประกาศโดยใช้คำว่า chan
ประเภทของสิ่งที่จะส่งเข้าไปยัง channel
สามารถระบุได้ว่า channel นี้จะให้ทำเฉพาะรับหรือส่ง
func pinger(c chan<-string) คือ ทำได้แค่ส่งข้อความไปที่ c เท่านั้น
func pinger(c <-chan string) คือ channel ที่ไม่ได้ระบุทิศทาง
สามารถใช้ได้ทั้ง 2 ทิศทางทั้งรับและส่ง
*/
func pinger(c chan string) {
for i := 0; ; i++ {
// <- หมายถึง ส่งและรับข้อความบน channel
// c <- "ping" คือ ส่ง ping เข้าไปใน channel
c <- "ping"
}
}
func printer(c chan string) {
for {
/* msg := <-c รับข้อความจาก channel และเก็บข้อความไว้ใน msg
*/
msg := <-c
fmt.Println(msg)
time.Sleep(time.Second * 1)
}
}
func ponger(c chan string) {
for i := 0; ; i++ {
c <- "pong"
}
}
func main() {
var c chan string = make(chan string)
go pinger(c)
go printer(c)
go ponger(c)
var input string
fmt.Scanln(&input)
}
|
package gameplay
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestAddReview(t *testing.T) {
var game GamePlay
game.Players = make([]Player, 3)
game.Players[0] = Player{
Name: "Todd",
Uid: 1,
Song: &Song{
Url: "https://mysong.url",
Description: "Goodish song but not my favourite",
},
}
game.Players[0].AddReview("Nancy", "Terrible song 1/10")
game.Players[0].AddReview("Alice", "Stunning uplift! 10/10")
assert.Equal(t, game.Players[0].ReceivedReviews[0].Rating, 1)
assert.Equal(t, game.Players[0].ReceivedReviews[1].Rating, 10)
game.Players[1] = Player{
Name: "Alice",
Uid: 2,
Song: &Song{
Url: "https://www.youtube.com/my-example-song",
Description: "I had to do it.",
},
}
game.Players[1].AddReview("Nancy", "Oh gosh, why on earth what why oh stop it! 1/10")
game.Players[1].AddReview("Todd", "I've seen the limits of torture 2/10")
assert.Equal(t, game.Players[1].ReceivedReviews[0].Rating, 1)
assert.Equal(t, game.Players[1].ReceivedReviews[1].Rating, 2)
game.Players[2] = Player{
Name: "Nancy",
Uid: 3,
Song: &Song{
Url: "https://www.vimeo.com/ambient-madness",
Description: "Calm down and enjoy. Close your eyes and feel the breeze.",
},
}
game.Players[2].AddReview("Todd", "I can smell the summer, it's here! 8/10")
game.Players[2].AddReview("Alice", "Not my piece of cake but I ate it. 7/10")
assert.Equal(t, game.Players[2].ReceivedReviews[0].Rating, 8)
assert.Equal(t, game.Players[2].ReceivedReviews[1].Rating, 7)
game = GamePlay{}
}
|
package resourcetypes
import (
"errors"
)
func Destroy(id string) error {
var exists bool
for index, resourcetype := range mockResourceTypes {
if resourcetype.ID == id {
mockResourceTypes = append(mockResourceTypes[:index], mockResourceTypes[index+1:]...)
exists = true
}
}
if !exists {
return errors.New("unable to delete resourcetype because resourcetype was not found")
}
return nil
}
|
package helpers
import (
"crypto/sha1"
"encoding/hex"
"path"
"github.com/fd/forklift/util/user"
)
func Path(ref string) (string, error) {
sha := sha1.New()
sha.Write([]byte(ref))
home, err := user.Home()
if err != nil {
return "", err
}
return path.Join(home, ".forklift", "deploypacks", hex.EncodeToString(sha.Sum(nil))), nil
}
|
package routes
import (
"github.com/adamveld12/sessionauth"
"github.com/go-martini/martini"
)
func RegisterRoutes(app *martini.ClassicMartini) {
app.Group("/", registerPageRoutes)
app.Group("/api/v1", registerApiRoutes, sessionauth.LoginRequired)
}
|
package cli
import (
"fmt"
"os"
"github.com/irisnet/irishub/app/protocol"
"github.com/irisnet/irishub/app/v1/service"
"github.com/irisnet/irishub/client/context"
"github.com/irisnet/irishub/client/utils"
"github.com/irisnet/irishub/codec"
sdk "github.com/irisnet/irishub/types"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func GetCmdQuerySvcDef(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "definition",
Short: "Query service definition",
Example: "iriscli service definition --def-chain-id=<chain-id> --service-name=<service name>",
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout).
WithAccountDecoder(utils.GetAccountDecoder(cdc))
name := viper.GetString(FlagServiceName)
defChainId := viper.GetString(FlagDefChainID)
params := service.QueryServiceParams{
DefChainID: defChainId,
ServiceName: name,
}
bz, err := cdc.MarshalJSON(params)
if err != nil {
return err
}
route := fmt.Sprintf("custom/%s/%s", protocol.ServiceRoute, service.QueryDefinition)
res, err := cliCtx.QueryWithData(route, bz)
if err != nil {
return err
}
fmt.Println(string(res))
return nil
},
}
cmd.Flags().AddFlagSet(FsServiceDefinition)
cmd.MarkFlagRequired(FlagDefChainID)
cmd.MarkFlagRequired(FlagServiceName)
return cmd
}
func GetCmdQuerySvcBind(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "binding",
Short: "Query service binding",
Example: "iriscli service binding --def-chain-id=<chain-id> --service-name=<service name> --bind-chain-id=<chain-id> --provider=<provider>",
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout).
WithAccountDecoder(utils.GetAccountDecoder(cdc))
name := viper.GetString(FlagServiceName)
defChainId := viper.GetString(FlagDefChainID)
bindChainId := viper.GetString(FlagBindChainID)
providerStr := viper.GetString(FlagProvider)
provider, err := sdk.AccAddressFromBech32(providerStr)
if err != nil {
return err
}
params := service.QueryBindingParams{
DefChainID: defChainId,
ServiceName: name,
BindChainId: bindChainId,
Provider: provider,
}
bz, err := cdc.MarshalJSON(params)
if err != nil {
return err
}
route := fmt.Sprintf("custom/%s/%s", protocol.ServiceRoute, service.QueryBinding)
res, err := cliCtx.QueryWithData(route, bz)
if err != nil {
return err
}
fmt.Println(string(res))
return nil
},
}
cmd.Flags().AddFlagSet(FsServiceDefinition)
cmd.Flags().AddFlagSet(FsServiceBinding)
cmd.MarkFlagRequired(FlagDefChainID)
cmd.MarkFlagRequired(FlagServiceName)
cmd.MarkFlagRequired(FlagBindChainID)
cmd.MarkFlagRequired(FlagProvider)
return cmd
}
func GetCmdQuerySvcBinds(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "bindings",
Short: "Query service bindings",
Example: "iriscli service bindings --def-chain-id=<chain-id> --service-name=<service name>",
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout).
WithAccountDecoder(utils.GetAccountDecoder(cdc))
name := viper.GetString(FlagServiceName)
defChainId := viper.GetString(FlagDefChainID)
params := service.QueryServiceParams{
DefChainID: defChainId,
ServiceName: name,
}
bz, err := cdc.MarshalJSON(params)
if err != nil {
return err
}
route := fmt.Sprintf("custom/%s/%s", protocol.ServiceRoute, service.QueryBindings)
res, err := cliCtx.QueryWithData(route, bz)
if err != nil {
return err
}
fmt.Println(string(res))
return nil
},
}
cmd.Flags().AddFlagSet(FsServiceDefinition)
cmd.MarkFlagRequired(FlagDefChainID)
cmd.MarkFlagRequired(FlagServiceName)
return cmd
}
func GetCmdQuerySvcRequests(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "requests",
Short: "Query service requests",
Example: "iriscli service requests --def-chain-id=<service-def-chain-id> --service-name=test " +
"--bind-chain-id=<bind-chain-id> --provider=<provider>",
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout).
WithAccountDecoder(utils.GetAccountDecoder(cdc))
name := viper.GetString(FlagServiceName)
defChainId := viper.GetString(FlagDefChainID)
bindChainId := viper.GetString(FlagBindChainID)
providerStr := viper.GetString(FlagProvider)
provider, err := sdk.AccAddressFromBech32(providerStr)
if err != nil {
return err
}
params := service.QueryBindingParams{
DefChainID: defChainId,
ServiceName: name,
BindChainId: bindChainId,
Provider: provider,
}
bz, err := cdc.MarshalJSON(params)
if err != nil {
return err
}
route := fmt.Sprintf("custom/%s/%s", protocol.ServiceRoute, service.QueryRequests)
res, err := cliCtx.QueryWithData(route, bz)
if err != nil {
return err
}
fmt.Println(string(res))
return nil
},
}
cmd.Flags().AddFlagSet(FsServiceDefinition)
cmd.Flags().AddFlagSet(FsServiceBinding)
cmd.MarkFlagRequired(FlagDefChainID)
cmd.MarkFlagRequired(FlagServiceName)
cmd.MarkFlagRequired(FlagBindChainID)
cmd.MarkFlagRequired(FlagProvider)
return cmd
}
func GetCmdQuerySvcResponse(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "response",
Short: "Query a service response",
Example: "iriscli service response --request-chain-id=<req-chain-id> --request-id=<request-id>",
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout).
WithAccountDecoder(utils.GetAccountDecoder(cdc))
reqChainId := viper.GetString(FlagReqChainId)
reqId := viper.GetString(FlagReqId)
params := service.QueryResponseParams{
ReqChainId: reqChainId,
RequestId: reqId,
}
bz, err := cdc.MarshalJSON(params)
if err != nil {
return err
}
route := fmt.Sprintf("custom/%s/%s", protocol.ServiceRoute, service.QueryResponse)
res, err := cliCtx.QueryWithData(route, bz)
if err != nil {
return err
}
fmt.Println(string(res))
return nil
},
}
cmd.Flags().String(FlagReqChainId, "", "the ID of the blockchain that the service invocation initiated")
cmd.Flags().String(FlagReqId, "", "the ID of the service invocation")
cmd.MarkFlagRequired(FlagReqChainId)
cmd.MarkFlagRequired(FlagReqId)
return cmd
}
func GetCmdQuerySvcFees(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "fees",
Short: "Query return and incoming fee of a particular address",
Example: "iriscli service fees <account address>",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout).
WithAccountDecoder(utils.GetAccountDecoder(cdc))
addrString := args[0]
addr, err := sdk.AccAddressFromBech32(addrString)
if err != nil {
return err
}
params := service.QueryFeesParams{
Address: addr,
}
bz, err := cdc.MarshalJSON(params)
if err != nil {
return err
}
route := fmt.Sprintf("custom/%s/%s", protocol.ServiceRoute, service.QueryFees)
res, err := cliCtx.QueryWithData(route, bz)
if err != nil {
return err
}
fmt.Println(string(res))
return nil
},
}
return cmd
}
|
package main
import (
"fmt"
e "github.com/mzmico/mz/rpc_service"
_ "github.com/mzmico/user-service/impls"
)
func main() {
s := e.Default()
err := s.Run()
if err != nil {
fmt.Println(err)
}
}
|
/*
The Chi-Squared (χ²) goodness of fit test estimates if an empirical (observed) distribution fits a theoretical (expected) distribution within reasonable margins.
For example, to figure out if a die is loaded you could roll it many times and note the results.
Because of randomness, you can't expect to get the same frequency for all faces, but if one or more faces turn up much more frequently than some others, it is reasonable to assume the die is loaded.
The formula to calculate the Chi-Square parameter is:
Chi-squared
Below is an example of a die rolled 600 times:
Face 1 2 3 4 5 6
Observed frequency 101 116 89 108 97 89
Expected frequency 100 100 100 100 100 100
Difference 1 16 -11 8 -3 -11
In this example, the Chi-Square parameter has a value of:
χ² = ((1)^2 + (16)^2 + (-11)^2 + (8)^2 + (-3)^2 + (-11)^2) / 100 = 5.72
This parameter is then compared to a critical value, calculated taking into account the number of categories and the confidence level. Here, the critical value is 11.0705. Since 5.72 < 11.0705, it is safe to assume the die is unloaded.
Given a list with the six observed frequencies, write a function that returns true if a die is unloaded, or false if it is loaded. Take 11.0705 as the critical value for all cases.
Examples
FairDie([44, 52, 33, 40, 41, 30]) ➞ true
(χ² = 7.75) < 11.0705
FairDie([34, 27, 23, 20, 32, 28]) ➞ true
(χ² = 1.6) < 11.0705
FairDie([10, 20, 11, 5, 19, 16]) ➞ false
(χ² = 12.556) > 11.0705
Notes
N/A
*/
package main
func main() {
assert(loaded([]float64{8, 10, 5, 15, 15, 10}) == true)
assert(loaded([]float64{21, 22, 17, 31, 29, 30}) == true)
assert(loaded([]float64{8, 16, 16, 9, 11, 3}) == false)
assert(loaded([]float64{14, 10, 16, 14, 15, 15}) == true)
assert(loaded([]float64{7, 18, 15, 21, 14, 28}) == false)
assert(loaded([]float64{29, 34, 33, 38, 41, 35}) == true)
assert(loaded([]float64{10, 20, 11, 5, 19, 16}) == false)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func loaded(a []float64) bool {
return chisq(a) < 11.0705
}
func mean(a []float64) float64 {
if len(a) == 0 {
return 0
}
m := 0.0
for _, v := range a {
m += v
}
return m / float64(len(a))
}
func chisq(a []float64) float64 {
r := 0.0
m := mean(a)
for _, v := range a {
r += (v - m) * (v - m)
}
return r / m
}
|
package utils
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
)
// GenerateSha256 generate sha256
func GenerateSha256(key, data string) string {
// Create a new HMAC by defining the hash type and the key (as byte array)
h := hmac.New(sha256.New, []byte(key))
// Write Data to it
h.Write([]byte(data))
// Get result and encode as hexadecimal string
return hex.EncodeToString(h.Sum(nil))
}
|
package ipam
import (
"fmt"
"net"
"reflect"
"testing"
"github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1"
"github.com/giantswarm/micrologger/microloggertest"
)
func mustParseCIDR(val string) net.IPNet {
_, n, err := net.ParseCIDR(val)
if err != nil {
panic(err)
}
return *n
}
func Test_selectRandomAZs_properties(t *testing.T) {
testCases := []struct {
name string
azs []string
n int
errorMatcher func(error) bool
}{
{
name: "case 0: select one AZ out of three",
azs: []string{"eu-west-1a", "eu-west-1b", "eu-west-1c"},
n: 1,
errorMatcher: nil,
},
{
name: "case 1: select three AZs out of three",
azs: []string{"eu-west-1a", "eu-west-1b", "eu-west-1c"},
n: 2,
errorMatcher: nil,
},
{
name: "case 2: select three AZs out of three",
azs: []string{"eu-west-1a", "eu-west-1b", "eu-west-1c"},
n: 3,
errorMatcher: nil,
},
{
name: "case 3: error when requesting more AZs than there are configured",
azs: []string{"eu-west-1a", "eu-west-1b", "eu-west-1c"},
n: 5,
errorMatcher: IsInvalidParameter,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
r := Resource{
logger: microloggertest.New(),
availabilityZones: tc.azs,
}
azs, err := r.selectRandomAZs(tc.n)
switch {
case err == nil && tc.errorMatcher == nil:
// correct; carry on
case err != nil && tc.errorMatcher == nil:
t.Fatalf("error == %#v, want nil", err)
case err == nil && tc.errorMatcher != nil:
t.Fatalf("error == nil, want non-nil")
case !tc.errorMatcher(err):
t.Fatalf("error == %#v, want matching", err)
}
if tc.errorMatcher != nil {
return
}
if tc.n != len(azs) {
t.Fatalf("got %d AZs in the first round, expected %d", len(azs), tc.n)
}
})
}
}
func Test_selectRandomAZs_random(t *testing.T) {
originalAZs := []string{"eu-west-1a", "eu-west-1b", "eu-west-1c"}
r := Resource{
logger: microloggertest.New(),
availabilityZones: originalAZs,
}
nTestRounds := 25
numAZs := len(originalAZs) - 1
selectedAZs := make([][]string, 0)
for i := 0; i < nTestRounds; i++ {
azs, err := r.selectRandomAZs(numAZs)
if err != nil {
t.Fatalf("unexpected error: %#v", err)
}
differsFromOriginal := false
differsFromEarlier := false
for _, selectedAZs := range selectedAZs {
for j, az := range originalAZs[:numAZs] {
if azs[j] != az {
differsFromOriginal = true
}
}
for j, az := range selectedAZs {
if azs[j] != az {
differsFromEarlier = true
}
}
if differsFromOriginal && differsFromEarlier {
return
}
}
selectedAZs = append(selectedAZs, azs)
}
t.Fatalf("after %d test rounds there was no difference in generated AZs over time and order of original AZs", nTestRounds)
}
func Test_splitSubnetToStatusAZs(t *testing.T) {
testCases := []struct {
name string
subnet net.IPNet
azs []string
expectedAZs []v1alpha1.AWSConfigStatusAWSAvailabilityZone
errorMatcher func(error) bool
}{
{
name: "case 0: split 10.100.4.0/22 for [eu-west-1b]",
subnet: mustParseCIDR("10.100.4.0/22"),
azs: []string{"eu-west-1b"},
expectedAZs: []v1alpha1.AWSConfigStatusAWSAvailabilityZone{
v1alpha1.AWSConfigStatusAWSAvailabilityZone{
Name: "eu-west-1b",
Subnet: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnet{
Private: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPrivate{
CIDR: "10.100.4.0/23",
},
Public: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPublic{
CIDR: "10.100.6.0/23",
},
},
},
},
errorMatcher: nil,
},
{
name: "case 1: split 10.100.4.0/22 for [eu-west-1c, eu-west-1a]",
subnet: mustParseCIDR("10.100.4.0/22"),
azs: []string{"eu-west-1c", "eu-west-1a"},
expectedAZs: []v1alpha1.AWSConfigStatusAWSAvailabilityZone{
v1alpha1.AWSConfigStatusAWSAvailabilityZone{
Name: "eu-west-1c",
Subnet: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnet{
Private: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPrivate{
CIDR: "10.100.4.0/24",
},
Public: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPublic{
CIDR: "10.100.5.0/24",
},
},
},
v1alpha1.AWSConfigStatusAWSAvailabilityZone{
Name: "eu-west-1a",
Subnet: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnet{
Private: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPrivate{
CIDR: "10.100.6.0/24",
},
Public: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPublic{
CIDR: "10.100.7.0/24",
},
},
},
},
errorMatcher: nil,
},
{
name: "case 2: split 10.100.4.0/22 for three [eu-west-1a, eu-west-1b, eu-west-1c]",
subnet: mustParseCIDR("10.100.4.0/22"),
azs: []string{"eu-west-1a", "eu-west-1b", "eu-west-1c"},
expectedAZs: []v1alpha1.AWSConfigStatusAWSAvailabilityZone{
v1alpha1.AWSConfigStatusAWSAvailabilityZone{
Name: "eu-west-1a",
Subnet: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnet{
Private: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPrivate{
CIDR: "10.100.4.0/25",
},
Public: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPublic{
CIDR: "10.100.4.128/25",
},
},
},
v1alpha1.AWSConfigStatusAWSAvailabilityZone{
Name: "eu-west-1b",
Subnet: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnet{
Private: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPrivate{
CIDR: "10.100.5.0/25",
},
Public: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPublic{
CIDR: "10.100.5.128/25",
},
},
},
v1alpha1.AWSConfigStatusAWSAvailabilityZone{
Name: "eu-west-1c",
Subnet: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnet{
Private: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPrivate{
CIDR: "10.100.6.0/25",
},
Public: v1alpha1.AWSConfigStatusAWSAvailabilityZoneSubnetPublic{
CIDR: "10.100.6.128/25",
},
},
},
},
errorMatcher: nil,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
azs, err := splitSubnetToStatusAZs(tc.subnet, tc.azs)
switch {
case err == nil && tc.errorMatcher == nil:
// correct; carry on
case err != nil && tc.errorMatcher == nil:
t.Fatalf("error == %#v, want nil", err)
case err == nil && tc.errorMatcher != nil:
t.Fatalf("error == nil, want non-nil")
case !tc.errorMatcher(err):
t.Fatalf("error == %#v, want matching", err)
}
if !reflect.DeepEqual(azs, tc.expectedAZs) {
t.Fatalf("got %q, expected %q", azs, tc.expectedAZs)
}
})
}
}
func Test_calculateSubnetMask(t *testing.T) {
testCases := []struct {
name string
mask net.IPMask
n uint
expectedMask net.IPMask
errorMatcher func(error) bool
}{
{
name: "case 0: split /24 into one network",
mask: net.CIDRMask(24, 32),
n: 1,
expectedMask: net.CIDRMask(24, 32),
errorMatcher: nil,
},
{
name: "case 1: split /24 into two networks",
mask: net.CIDRMask(24, 32),
n: 2,
expectedMask: net.CIDRMask(25, 32),
errorMatcher: nil,
},
{
name: "case 2: split /24 into three networks",
mask: net.CIDRMask(24, 32),
n: 3,
expectedMask: net.CIDRMask(26, 32),
errorMatcher: nil,
},
{
name: "case 3: split /24 into four networks",
mask: net.CIDRMask(24, 32),
n: 4,
expectedMask: net.CIDRMask(26, 32),
errorMatcher: nil,
},
{
name: "case 4: split /24 into five networks",
mask: net.CIDRMask(24, 32),
n: 5,
expectedMask: net.CIDRMask(27, 32),
errorMatcher: nil,
},
{
name: "case 5: split /22 into 7 networks",
mask: net.CIDRMask(22, 32),
n: 7,
expectedMask: net.CIDRMask(25, 32),
errorMatcher: nil,
},
{
name: "case 6: split /31 into 8 networks (no room)",
mask: net.CIDRMask(31, 32),
n: 7,
expectedMask: nil,
errorMatcher: IsInvalidParameter,
},
{
name: "case 7: IPv6 masks (split /31 for seven networks)",
mask: net.CIDRMask(31, 128),
n: 7,
expectedMask: net.CIDRMask(34, 128),
errorMatcher: nil,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
mask, err := calculateSubnetMask(tc.mask, tc.n)
switch {
case err == nil && tc.errorMatcher == nil:
// correct; carry on
case err != nil && tc.errorMatcher == nil:
t.Fatalf("error == %#v, want nil", err)
case err == nil && tc.errorMatcher != nil:
t.Fatalf("error == nil, want non-nil")
case !tc.errorMatcher(err):
t.Fatalf("error == %#v, want matching", err)
}
if !reflect.DeepEqual(mask, tc.expectedMask) {
t.Fatalf("Mask == %q, want %q", mask, tc.expectedMask)
}
})
}
}
func Test_splitNetwork(t *testing.T) {
testCases := []struct {
name string
network net.IPNet
n uint
expectedSubnets []net.IPNet
errorMatcher func(error) bool
}{
{
name: "case 0: split /24 into four networks",
network: mustParseCIDR("192.168.8.0/24"),
n: 4,
expectedSubnets: []net.IPNet{
mustParseCIDR("192.168.8.0/26"),
mustParseCIDR("192.168.8.64/26"),
mustParseCIDR("192.168.8.128/26"),
mustParseCIDR("192.168.8.192/26"),
},
errorMatcher: nil,
},
{
name: "case 1: split /22 into 7 networks",
network: mustParseCIDR("10.100.0.0/22"),
n: 7,
expectedSubnets: []net.IPNet{
mustParseCIDR("10.100.0.0/25"),
mustParseCIDR("10.100.0.128/25"),
mustParseCIDR("10.100.1.0/25"),
mustParseCIDR("10.100.1.128/25"),
mustParseCIDR("10.100.2.0/25"),
mustParseCIDR("10.100.2.128/25"),
mustParseCIDR("10.100.3.0/25"),
},
errorMatcher: nil,
},
{
name: "case 2: split /31 into 8 networks (no room)",
network: mustParseCIDR("192.168.8.128/31"),
n: 7,
expectedSubnets: nil,
errorMatcher: IsInvalidParameter,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
subnets, err := splitNetwork(tc.network, tc.n)
switch {
case err == nil && tc.errorMatcher == nil:
// correct; carry on
case err != nil && tc.errorMatcher == nil:
t.Fatalf("error == %#v, want nil", err)
case err == nil && tc.errorMatcher != nil:
t.Fatalf("error == nil, want non-nil")
case !tc.errorMatcher(err):
t.Fatalf("error == %#v, want matching", err)
}
if !reflect.DeepEqual(subnets, tc.expectedSubnets) {
msg := "expected: {\n"
for _, n := range tc.expectedSubnets {
msg += fmt.Sprintf("\t%s,\n", n.String())
}
msg += "}\n\ngot: {\n"
for _, n := range subnets {
msg += fmt.Sprintf("\t%s,\n", n.String())
}
msg += "}"
t.Fatal(msg)
}
})
}
}
|
package bob
import (
"strings"
)
// Hey triggers a response from Bob
func Hey(s string) (response string) {
s = strings.TrimSpace(s)
isQuestion := strings.HasSuffix(s, "?")
if len(s) == 0 {
return "Fine. Be that way!"
} else if isYelling(s) && isQuestion {
return "Calm down, I know what I'm doing!"
} else if isYelling(s) {
return "Whoa, chill out!"
} else if isQuestion {
return "Sure."
}
return "Whatever."
}
func isYelling(s string) bool {
return s == strings.ToUpper(s) && s != strings.ToLower(s)
}
|
package msg_queue
import (
"github.com/nsqio/go-nsq"
"time"
"strings"
"git.zhuzi.me/zzjz/zhuzi-bootstrap/lib/log"
"os"
"os/signal"
"syscall"
"sync"
)
var producer *nsq.Producer
var addrNsqLookups []string
var logLevel nsq.LogLevel
// 在调用Publish和Listen之前需要Init
// addrNsqp: 单个nsq地址, addrNsqLookupp:lookup地址 可以有多个,用逗号隔开
// todo 改成结构体, 有很多个参数, 如重试时间, 重试次数, 重连时间
func Init(addrNsq, addrNsqLookup string, debug bool) {
addrNsqLookups = strings.Split(addrNsqLookup, ",")
p, err := nsq.NewProducer(addrNsq, nsq.NewConfig())
if err != nil {
panic(err)
}
logLevel = nsq.LogLevelWarning
if debug {
logLevel = nsq.LogLevelInfo
}
p.SetLogger(log.NsqLogger(), logLevel)
producer = p
go func() {
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
GracefulStop()
}()
}
func Publish(topic string, body []byte, delay ...time.Duration) (err error) {
if len(delay) == 0 {
err = producer.Publish(topic, body)
} else {
err = producer.DeferredPublish(topic, delay[0], body)
}
return
}
var consumers []*nsq.Consumer
// 一个程序里会listen多个topic, 所以不阻塞
func Listen(topic string, channel string, handler nsq.Handler) (err error) {
c, err := nsq.NewConsumer(topic, channel, nsq.NewConfig())
if err != nil {
return
}
c.AddHandler(handler)
c.SetLogger(log.NsqLogger(), logLevel)
err = c.ConnectToNSQLookupds(addrNsqLookups)
if err != nil {
panic(err)
}
consumers = append(consumers, c)
return
}
func GracefulStop() {
producer.Stop()
var wg sync.WaitGroup
for _, c := range consumers {
wg.Add(1)
go func() {
c.Stop()
wg.Done()
}()
}
wg.Wait()
}
|
package seekbuf
// TODO: test
|
package main
import (
"fmt"
"reflect"
)
/*
class Account<T>{
private T id;
private int sum;
Account(T id, int sum){
this.id = id;
this.sum = sum;
}
public T getId() { return id; }
public int getSum() { return sum; }
public void setSum(int sum) { this.sum = sum; }
}
*/
type types interface{}
type Account struct {
id types
sum int
}
func NewAccount(id types, sum int) Account {
a := Account{}
a.id = id
a.sum = sum
return a
}
func (a Account) GetId() types {
return a.id
}
func (a Account) GetSum() types {
return a.sum
}
func (a Account) SetSum(sum int) {
a.sum = sum
}
func main() {
var s = types("hello world")
var s1 = types(25)
res := NewAccount(s, 12)
res1 := NewAccount(s1, 12)
r := res.GetId()
r1 := res1.GetId()
fmt.Println(r)
fmt.Println(r1)
fmt.Println(reflect.TypeOf(r))
fmt.Println(reflect.TypeOf(r1))
}
|
package main
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
)
var (
targzAbsPath string
)
func main() {
rootCmd := &cobra.Command{
Use: "app",
}
//tar subcommand
var (
tarSource string
tarTarget string
)
tarCmd := &cobra.Command{
Use: "tar",
Short: "tar file",
Long: "tar file",
Run: func(cmd *cobra.Command, args []string) {
if f, err := os.Open(tarSource); err != nil {
log.Fatalf("failed to open tar source %v, error:%v", tarSource, err)
} else {
if err = Compress(f, tarTarget); err != nil {
log.Fatalf("failed to tar file %v to $%v, error:%v", tarSource, tarTarget, err)
}
}
log.Printf("tar file %v to %v OK", tarSource, tarTarget)
},
}
tarCmd.Flags().StringVarP(&tarSource, "source", "s", ".", "source file or dir")
tarCmd.Flags().StringVarP(&tarTarget, "target", "t", "", "target file")
//untar subcommand
var (
untarSource string
untarTarget string
)
untarCmd := &cobra.Command{
Use: "untar",
Short: "untar file",
Long: "untar file",
Run: func(cmd *cobra.Command, args []string) {
if err := DeCompress(untarSource, untarTarget); err != nil {
log.Fatalf("failed to untar file %v from $%v, error:%v", untarTarget, untarSource, err)
}
log.Printf("untar file %v from %v OK", untarTarget, untarSource)
},
}
untarCmd.Flags().StringVarP(&untarSource, "source", "s", "", "source file")
untarCmd.Flags().StringVarP(&untarTarget, "target", "t", ".", "target dir")
//add subcommand
rootCmd.AddCommand(tarCmd)
rootCmd.AddCommand(untarCmd)
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
os.Exit(1)
}
}
//压缩 使用gzip压缩成tar.gz
func Compress(file *os.File, dest string) error {
d, _ := os.Create(dest)
defer d.Close()
targzAbsPath, _ = filepath.Abs(dest)
log.Printf("abs path of dest(%v): %v", dest, targzAbsPath)
gw := gzip.NewWriter(d)
defer gw.Close()
tw := tar.NewWriter(gw)
defer tw.Close()
err := compress(file, "", tw)
if err != nil {
return err
}
return nil
}
func compress(file *os.File, prefix string, tw *tar.Writer) error {
info, err := file.Stat()
if err != nil {
return err
}
if info.IsDir() {
prefix = prefix + "/" + info.Name()
fileInfos, err := file.Readdir(-1)
if err != nil {
return err
}
for _, fi := range fileInfos {
absPath, _ := filepath.Abs(fmt.Sprintf("%v/%v", file.Name(), fi.Name()))
if absPath == targzAbsPath {
log.Printf("current file is dest: %v, skip", absPath)
continue
}
f, err := os.Open(file.Name() + "/" + fi.Name())
if err != nil {
return err
}
err = compress(f, prefix, tw)
if err != nil {
return err
}
}
} else {
header, err := tar.FileInfoHeader(info, "")
header.Name = prefix + "/" + header.Name
if err != nil {
return err
}
err = tw.WriteHeader(header)
if err != nil {
return err
}
_, err = io.Copy(tw, file)
file.Close()
if err != nil {
return err
}
}
return nil
}
//解压 tar.gz
func DeCompress(tarFile, dest string) error {
srcFile, err := os.Open(tarFile)
if err != nil {
return err
}
defer srcFile.Close()
gr, err := gzip.NewReader(srcFile)
if err != nil {
return err
}
defer gr.Close()
tr := tar.NewReader(gr)
for {
hdr, err := tr.Next()
if err != nil {
if err == io.EOF {
break
} else {
return err
}
}
filename := dest + hdr.Name
file, err := createFile(filename)
if err != nil {
return err
}
io.Copy(file, tr)
}
return nil
}
func createFile(name string) (*os.File, error) {
err := os.MkdirAll(string([]rune(name)[0:strings.LastIndex(name, "/")]), 0755)
if err != nil {
return nil, err
}
return os.Create(name)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.