<commit_before>package template

import (
	"errors"
	"io/ioutil"
	"text/template"
)

const defaultTemplate = `{{ range . }}
{{ . }}
{{ end }}
`

// -------------------------------------------------------
// Parser.
// -------------------------------------------------------

// Parse a template (and select the appropriate engine based on the file's extension).
func Parse(templateFilename string) (*template.Template, error) {

	// If not available, use the default template.
	if templateFilename == "" {
		return useDefaultTemplate(), nil
	}

	content, err := ioutil.ReadFile(templateFilename)
	if err != nil {
		return nil, errors.New("cannot read the template")
	}

	return useTextTemplate(string(content))
}

func useTextTemplate(content string) (*template.Template, error) {
	t, err := template.New("").Parse(content)
	if err != nil {
		return nil, errors.New("invalid Text/Markdown template file")
	}

	return t, nil
}

func useDefaultTemplate() *template.Template {
	return template.Must(
		template.New("").Parse(defaultTemplate),
	)
}
<commit_msg>Use normal string to encapsulate the default tpl<commit_after>package template

import (
	"errors"
	"io/ioutil"
	"text/template"
)

const defaultTemplate = "{{ range . }}{{ . }}\n\n{{ end }}"

// -------------------------------------------------------
// Parser.
// -------------------------------------------------------

// Parse a template (and select the appropriate engine based on the file's extension).
func Parse(templateFilename string) (*template.Template, error) {

	// If not available, use the default template.
	if templateFilename == "" {
		return useDefaultTemplate(), nil
	}

	content, err := ioutil.ReadFile(templateFilename)
	if err != nil {
		return nil, errors.New("cannot read the template")
	}

	return useTextTemplate(string(content))
}

func useTextTemplate(content string) (*template.Template, error) {
	t, err := template.New("").Parse(content)
	if err != nil {
		return nil, errors.New("invalid Text/Markdown template file")
	}

	return t, nil
}

func useDefaultTemplate() *template.Template {
	return template.Must(
		template.New("").Parse(defaultTemplate),
	)
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Jetstack cert-manager contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package dns

import (
	"errors"
	"testing"

	"github.com/jetstack/cert-manager/test/util/generate"

	"github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha1"
	"github.com/jetstack/cert-manager/pkg/controller/test"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/azuredns"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/clouddns"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/cloudflare"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/route53"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/acmedns"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/util"
)

const (
	defaultTestIssuerName      = "test-issuer"
	defaultTestIssuerKind      = v1alpha1.IssuerKind
	defaultTestNamespace       = "default"
	defaultTestCertificateName = "test-cert"
)

type solverFixture struct {
	// The Solver under test
	Solver *Solver
	*test.Builder

	// Issuer to be passed to functions on the Solver (a default will be used if nil)
	Issuer v1alpha1.GenericIssuer
	// Certificate resource to use during tests
	Certificate *v1alpha1.Certificate
	// Challenge resource to use during tests
	Challenge v1alpha1.ACMEOrderChallenge

	dnsProviders *fakeDNSProviders

	// PreFn will run before the test is run, but after the fixture has been initialised.
	// This is useful if you want to load the clientset with some resources *after* the
	// fixture has been created.
	PreFn func(*testing.T, *solverFixture)
	// CheckFn should performs checks to ensure the output of the test is as expected.
	// Optional additional values may be provided, which represent the output of the
	// function under test.
	CheckFn func(*testing.T, *solverFixture, ...interface{})
	// Err should be true if an error is expected from the function under test
	Err bool

	// testResources is used to store references to resources used or created during
	// the test.
	testResources map[string]interface{}
}

func (s *solverFixture) Setup(t *testing.T) {
	if s.Issuer == nil {
		s.Issuer = generate.Issuer(generate.IssuerConfig{
			Name:      defaultTestIssuerName,
			Namespace: defaultTestNamespace,
		})
	}
	if s.testResources == nil {
		s.testResources = map[string]interface{}{}
	}
	if s.Builder == nil {
		s.Builder = &test.Builder{}
	}
	if s.dnsProviders == nil {
		s.dnsProviders = newFakeDNSProviders()
	}
	s.Solver = buildFakeSolver(s.Builder, s.dnsProviders.constructors)
	if s.PreFn != nil {
		s.PreFn(t, s)
		s.Builder.Sync()
	}
}

func (s *solverFixture) Finish(t *testing.T, args ...interface{}) {
	defer s.Builder.Stop()
	// resync listers before running checks
	s.Builder.Sync()
	// run custom checks
	if s.CheckFn != nil {
		s.CheckFn(t, s, args...)
	}
}

func buildFakeSolver(b *test.Builder, dnsProviders dnsProviderConstructors) *Solver {
	b.Start()
	s := &Solver{
		Context:                 b.Context,
		secretLister:            b.Context.KubeSharedInformerFactory.Core().V1().Secrets().Lister(),
		dnsProviderConstructors: dnsProviders,
	}
	b.Sync()
	return s
}

func strPtr(s string) *string {
	return &s
}

type fakeDNSProviderCall struct {
	name string
	args []interface{}
}

type fakeDNSProviders struct {
	constructors dnsProviderConstructors
	calls        []fakeDNSProviderCall
}

func (f *fakeDNSProviders) call(name string, args ...interface{}) {
	f.calls = append(f.calls, fakeDNSProviderCall{name: name, args: args})
}

func newFakeDNSProviders() *fakeDNSProviders {
	f := &fakeDNSProviders{
		calls: []fakeDNSProviderCall{},
	}
	f.constructors = dnsProviderConstructors{
		cloudDNS: func(project string, serviceAccount []byte, dns01Nameservers []string) (*clouddns.DNSProvider, error) {
			f.call("clouddns", project, serviceAccount, util.RecursiveNameservers)
			return nil, nil
		},
		cloudFlare: func(email, apikey string, dns01Nameservers []string) (*cloudflare.DNSProvider, error) {
			f.call("cloudflare", email, apikey, util.RecursiveNameservers)
			if email == "" || apikey == "" {
				return nil, errors.New("invalid email or apikey")
			}
			return nil, nil
		},
		route53: func(accessKey, secretKey, hostedZoneID, region string, ambient bool, dns01Nameservers []string) (*route53.DNSProvider, error) {
			f.call("route53", accessKey, secretKey, hostedZoneID, region, ambient, util.RecursiveNameservers)
			return nil, nil
		},
		azureDNS: func(clientID, clientSecret, subscriptionID, tenentID, resourceGroupName, hostedZoneName string, dns01Nameservers []string) (*azuredns.DNSProvider, error) {
			f.call("azuredns", clientID, clientSecret, subscriptionID, tenentID, resourceGroupName, hostedZoneName, util.RecursiveNameservers)
			return nil, nil
		},
		acmeDNS: func(host string, accountJson []byte) (*acmedns.DNSProvider, error) {
			f.call("acmedns", host, accountJson)
			return nil, nil
		},
	}
	return f
}
<commit_msg>Fix go fmt failing<commit_after>/*
Copyright 2018 The Jetstack cert-manager contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package dns

import (
	"errors"
	"testing"

	"github.com/jetstack/cert-manager/test/util/generate"

	"github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha1"
	"github.com/jetstack/cert-manager/pkg/controller/test"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/acmedns"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/azuredns"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/clouddns"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/cloudflare"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/route53"
	"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/util"
)

const (
	defaultTestIssuerName      = "test-issuer"
	defaultTestIssuerKind      = v1alpha1.IssuerKind
	defaultTestNamespace       = "default"
	defaultTestCertificateName = "test-cert"
)

type solverFixture struct {
	// The Solver under test
	Solver *Solver
	*test.Builder

	// Issuer to be passed to functions on the Solver (a default will be used if nil)
	Issuer v1alpha1.GenericIssuer
	// Certificate resource to use during tests
	Certificate *v1alpha1.Certificate
	// Challenge resource to use during tests
	Challenge v1alpha1.ACMEOrderChallenge

	dnsProviders *fakeDNSProviders

	// PreFn will run before the test is run, but after the fixture has been initialised.
	// This is useful if you want to load the clientset with some resources *after* the
	// fixture has been created.
	PreFn func(*testing.T, *solverFixture)
	// CheckFn should performs checks to ensure the output of the test is as expected.
	// Optional additional values may be provided, which represent the output of the
	// function under test.
	CheckFn func(*testing.T, *solverFixture, ...interface{})
	// Err should be true if an error is expected from the function under test
	Err bool

	// testResources is used to store references to resources used or created during
	// the test.
	testResources map[string]interface{}
}

func (s *solverFixture) Setup(t *testing.T) {
	if s.Issuer == nil {
		s.Issuer = generate.Issuer(generate.IssuerConfig{
			Name:      defaultTestIssuerName,
			Namespace: defaultTestNamespace,
		})
	}
	if s.testResources == nil {
		s.testResources = map[string]interface{}{}
	}
	if s.Builder == nil {
		s.Builder = &test.Builder{}
	}
	if s.dnsProviders == nil {
		s.dnsProviders = newFakeDNSProviders()
	}
	s.Solver = buildFakeSolver(s.Builder, s.dnsProviders.constructors)
	if s.PreFn != nil {
		s.PreFn(t, s)
		s.Builder.Sync()
	}
}

func (s *solverFixture) Finish(t *testing.T, args ...interface{}) {
	defer s.Builder.Stop()
	// resync listers before running checks
	s.Builder.Sync()
	// run custom checks
	if s.CheckFn != nil {
		s.CheckFn(t, s, args...)
	}
}

func buildFakeSolver(b *test.Builder, dnsProviders dnsProviderConstructors) *Solver {
	b.Start()
	s := &Solver{
		Context:                 b.Context,
		secretLister:            b.Context.KubeSharedInformerFactory.Core().V1().Secrets().Lister(),
		dnsProviderConstructors: dnsProviders,
	}
	b.Sync()
	return s
}

func strPtr(s string) *string {
	return &s
}

type fakeDNSProviderCall struct {
	name string
	args []interface{}
}

type fakeDNSProviders struct {
	constructors dnsProviderConstructors
	calls        []fakeDNSProviderCall
}

func (f *fakeDNSProviders) call(name string, args ...interface{}) {
	f.calls = append(f.calls, fakeDNSProviderCall{name: name, args: args})
}

func newFakeDNSProviders() *fakeDNSProviders {
	f := &fakeDNSProviders{
		calls: []fakeDNSProviderCall{},
	}
	f.constructors = dnsProviderConstructors{
		cloudDNS: func(project string, serviceAccount []byte, dns01Nameservers []string) (*clouddns.DNSProvider, error) {
			f.call("clouddns", project, serviceAccount, util.RecursiveNameservers)
			return nil, nil
		},
		cloudFlare: func(email, apikey string, dns01Nameservers []string) (*cloudflare.DNSProvider, error) {
			f.call("cloudflare", email, apikey, util.RecursiveNameservers)
			if email == "" || apikey == "" {
				return nil, errors.New("invalid email or apikey")
			}
			return nil, nil
		},
		route53: func(accessKey, secretKey, hostedZoneID, region string, ambient bool, dns01Nameservers []string) (*route53.DNSProvider, error) {
			f.call("route53", accessKey, secretKey, hostedZoneID, region, ambient, util.RecursiveNameservers)
			return nil, nil
		},
		azureDNS: func(clientID, clientSecret, subscriptionID, tenentID, resourceGroupName, hostedZoneName string, dns01Nameservers []string) (*azuredns.DNSProvider, error) {
			f.call("azuredns", clientID, clientSecret, subscriptionID, tenentID, resourceGroupName, hostedZoneName, util.RecursiveNameservers)
			return nil, nil
		},
		acmeDNS: func(host string, accountJson []byte) (*acmedns.DNSProvider, error) {
			f.call("acmedns", host, accountJson)
			return nil, nil
		},
	}
	return f
}
<|endoftext|>


<commit_before>package status

import (
	"fmt"

	"github.com/bitfinexcom/bitfinex-api-go/pkg/convert"
)

type DerivativesSnapshot struct {
	Snapshot []*Derivative
}

type Derivative struct {
	Symbol               string
	MTS                  int64
	Price                float64
	SpotPrice            float64
	InsuranceFundBalance float64
	FundingEventMTS      int64
	FundingAccrued       float64
	FundingStep          float64
	CurrentFunding       float64
	MarkPrice            float64
	OpenInterest         float64
	ClampMIN             float64
	ClampMAX             float64
}

func DerivFromRaw(symbol string, raw []interface{}) (*Derivative, error) {
	if len(raw) < 22 {
		return nil, fmt.Errorf("data slice too short for derivative status: %#v", raw)
	}

	return &Derivative{
		Symbol:               symbol,
		MTS:                  convert.I64ValOrZero(raw[0]),
		Price:                convert.F64ValOrZero(raw[2]),
		SpotPrice:            convert.F64ValOrZero(raw[3]),
		InsuranceFundBalance: convert.F64ValOrZero(raw[5]),
		FundingEventMTS:      convert.I64ValOrZero(raw[7]),
		FundingAccrued:       convert.F64ValOrZero(raw[8]),
		FundingStep:          convert.F64ValOrZero(raw[9]),
		CurrentFunding:       convert.F64ValOrZero(raw[11]),
		MarkPrice:            convert.F64ValOrZero(raw[14]),
		OpenInterest:         convert.F64ValOrZero(raw[17]),
		ClampMIN:             convert.F64ValOrZero(raw[21]),
		ClampMAX:             convert.F64ValOrZero(raw[22]),
	}, nil
}

func DerivSnapshotFromRaw(symbol string, raw [][]interface{}) (*DerivativesSnapshot, error) {
	snapshot := make([]*Derivative, len(raw))
	for i, r := range raw {
		d, err := DerivFromRaw(symbol, r)
		if err != nil {
			return nil, err
		}
		snapshot[i] = d
	}
	return &DerivativesSnapshot{Snapshot: snapshot}, nil
}

func DerivFromRestRaw(raw []interface{}) (t *Derivative, err error) {
	if len(raw) == 0 {
		return t, fmt.Errorf("data slice too short for derivatives: %#v", raw)
	}

	return DerivFromRaw(raw[0].(string), raw[1:])
}
<commit_msg>more secure check for payload validity in DerivFromRestRaw<commit_after>package status

import (
	"fmt"

	"github.com/bitfinexcom/bitfinex-api-go/pkg/convert"
)

type DerivativesSnapshot struct {
	Snapshot []*Derivative
}

type Derivative struct {
	Symbol               string
	MTS                  int64
	Price                float64
	SpotPrice            float64
	InsuranceFundBalance float64
	FundingEventMTS      int64
	FundingAccrued       float64
	FundingStep          float64
	CurrentFunding       float64
	MarkPrice            float64
	OpenInterest         float64
	ClampMIN             float64
	ClampMAX             float64
}

func DerivFromRaw(symbol string, raw []interface{}) (*Derivative, error) {
	if len(raw) < 22 {
		return nil, fmt.Errorf("data slice too short for derivative status: %#v", raw)
	}

	return &Derivative{
		Symbol:               symbol,
		MTS:                  convert.I64ValOrZero(raw[0]),
		Price:                convert.F64ValOrZero(raw[2]),
		SpotPrice:            convert.F64ValOrZero(raw[3]),
		InsuranceFundBalance: convert.F64ValOrZero(raw[5]),
		FundingEventMTS:      convert.I64ValOrZero(raw[7]),
		FundingAccrued:       convert.F64ValOrZero(raw[8]),
		FundingStep:          convert.F64ValOrZero(raw[9]),
		CurrentFunding:       convert.F64ValOrZero(raw[11]),
		MarkPrice:            convert.F64ValOrZero(raw[14]),
		OpenInterest:         convert.F64ValOrZero(raw[17]),
		ClampMIN:             convert.F64ValOrZero(raw[21]),
		ClampMAX:             convert.F64ValOrZero(raw[22]),
	}, nil
}

func DerivSnapshotFromRaw(symbol string, raw [][]interface{}) (*DerivativesSnapshot, error) {
	snapshot := make([]*Derivative, len(raw))
	for i, r := range raw {
		d, err := DerivFromRaw(symbol, r)
		if err != nil {
			return nil, err
		}
		snapshot[i] = d
	}
	return &DerivativesSnapshot{Snapshot: snapshot}, nil
}

func DerivFromRestRaw(raw []interface{}) (t *Derivative, err error) {
	if len(raw) < 2 {
		return t, fmt.Errorf("data slice too short for derivatives: %#v", raw)
	}

	return DerivFromRaw(raw[0].(string), raw[1:])
}
<|endoftext|>


<commit_before>package imgur

import (
	"errors"
	"strings"
)

// GenericInfo is returned from functions for which the final result type is not known beforehand.
// Only one pointer is != nil
type GenericInfo struct {
	Image  *ImageInfo
	Album  *AlbumInfo
	GImage *GalleryImageInfo
	GAlbum *GalleryAlbumInfo
	Limit  *RateLimit
}

// GetInfoFromURL tries to query imgur based on information identified in the URL.
// returns image/album info, status code of the request, error
func (client *Client) GetInfoFromURL(url string) (*GenericInfo, int, error) {
	url = strings.TrimSpace(url)
	var ret GenericInfo

	// https://i.imgur.com/<id>.jpg -> image
	if strings.Contains(url, "://i.imgur.com/") {
		start := strings.LastIndex(url, "/") + 1
		end := strings.LastIndex(url, ".") - 1
		if start == -1 || end == -1 || start == end {
			return nil, -1, errors.New("Could not find ID in URL " + url + ". I was going down i.imgur.com path.")
		}
		id := url[start:end]
		client.Log.Debugf("Detected imgur image ID %v. Was going down the i.imgur.com/ path.", id)
		ii, status, err := client.GetGalleryImageInfo(id)
		ret.GImage = ii
		return &ret, status, err
	}

	// https://imgur.com/a/<id> -> album
	if strings.Contains(url, "://imgur.com/a/") {
		start := strings.LastIndex(url, "/") + 1
		if start == -1 {
			return nil, -1, errors.New("Could not find ID in URL " + url + ". I was going down imgur.com/a/ path.")
		}
		id := url[start:]
		client.Log.Debugf("Detected imgur album ID %v. Was going down the imgur.com/a/ path.", id)
		ai, status, err := client.GetAlbumInfo(id)
		ret.Album = ai
		return &ret, status, err
	}

	// https://imgur.com/gallery/<id> len(id) == 5 -> gallery album
	// https://imgur.com/gallery/<id> len(id) == 7 -> gallery image
	if strings.Contains(url, "://imgur.com/gallery/") {
		start := strings.LastIndex(url, "/") + 1
		if start == -1 {
			return nil, -1, errors.New("Could not find ID in URL " + url + ". I was going down imgur.com/gallery/ path.")
		}
		id := url[start:]
		client.Log.Debugf("Detected imgur gallery ID %v. Was going down the imgur.com/gallery/ path.", id)
		if len(id) == 5 {
			client.Log.Debugf("Detected imgur gallery album.")
			ai, status, err := client.GetGalleryAlbumInfo(id)
			ret.GAlbum = ai
			return &ret, status, err
		}

		ii, status, err := client.GetGalleryImageInfo(id)
		ret.GImage = ii
		return &ret, status, err
	}

	// https://imgur.com/<id> -> image
	if strings.Contains(url, "://imgur.com/") {
		start := strings.LastIndex(url, "/") + 1
		if start == -1 {
			return nil, -1, errors.New("Could not find ID in URL " + url + ". I was going down imgur.com/ path.")
		}
		id := url[start:]
		client.Log.Debugf("Detected imgur image ID %v. Was going down the imgur.com/ path.", id)
		ii, status, err := client.GetGalleryImageInfo(id)
		ret.GImage = ii
		return &ret, status, err
	}

	return nil, -1, errors.New("URL pattern matching for URL " + url + " failed.")
}
<commit_msg>Small fix for links directly to images.<commit_after>package imgur

import (
	"errors"
	"strings"
)

// GenericInfo is returned from functions for which the final result type is not known beforehand.
// Only one pointer is != nil
type GenericInfo struct {
	Image  *ImageInfo
	Album  *AlbumInfo
	GImage *GalleryImageInfo
	GAlbum *GalleryAlbumInfo
	Limit  *RateLimit
}

// GetInfoFromURL tries to query imgur based on information identified in the URL.
// returns image/album info, status code of the request, error
func (client *Client) GetInfoFromURL(url string) (*GenericInfo, int, error) {
	url = strings.TrimSpace(url)
	var ret GenericInfo

	// https://i.imgur.com/<id>.jpg -> image
	if strings.Contains(url, "://i.imgur.com/") {
		start := strings.LastIndex(url, "/") + 1
		end := strings.LastIndex(url, ".")
		if start == -1 || end == -1 || start == end {
			return nil, -1, errors.New("Could not find ID in URL " + url + ". I was going down i.imgur.com path.")
		}
		id := url[start:end]
		client.Log.Debugf("Detected imgur image ID %v. Was going down the i.imgur.com/ path.", id)
		ii, status, err := client.GetGalleryImageInfo(id)
		ret.GImage = ii
		return &ret, status, err
	}

	// https://imgur.com/a/<id> -> album
	if strings.Contains(url, "://imgur.com/a/") {
		start := strings.LastIndex(url, "/") + 1
		if start == -1 {
			return nil, -1, errors.New("Could not find ID in URL " + url + ". I was going down imgur.com/a/ path.")
		}
		id := url[start:]
		client.Log.Debugf("Detected imgur album ID %v. Was going down the imgur.com/a/ path.", id)
		ai, status, err := client.GetAlbumInfo(id)
		ret.Album = ai
		return &ret, status, err
	}

	// https://imgur.com/gallery/<id> len(id) == 5 -> gallery album
	// https://imgur.com/gallery/<id> len(id) == 7 -> gallery image
	if strings.Contains(url, "://imgur.com/gallery/") {
		start := strings.LastIndex(url, "/") + 1
		if start == -1 {
			return nil, -1, errors.New("Could not find ID in URL " + url + ". I was going down imgur.com/gallery/ path.")
		}
		id := url[start:]
		client.Log.Debugf("Detected imgur gallery ID %v. Was going down the imgur.com/gallery/ path.", id)
		if len(id) == 5 {
			client.Log.Debugf("Detected imgur gallery album.")
			ai, status, err := client.GetGalleryAlbumInfo(id)
			ret.GAlbum = ai
			return &ret, status, err
		}

		ii, status, err := client.GetGalleryImageInfo(id)
		ret.GImage = ii
		return &ret, status, err
	}

	// https://imgur.com/<id> -> image
	if strings.Contains(url, "://imgur.com/") {
		start := strings.LastIndex(url, "/") + 1
		if start == -1 {
			return nil, -1, errors.New("Could not find ID in URL " + url + ". I was going down imgur.com/ path.")
		}
		id := url[start:]
		client.Log.Debugf("Detected imgur image ID %v. Was going down the imgur.com/ path.", id)
		ii, status, err := client.GetGalleryImageInfo(id)
		ret.GImage = ii
		return &ret, status, err
	}

	return nil, -1, errors.New("URL pattern matching for URL " + url + " failed.")
}
<|endoftext|>


<commit_before>package beater

import (
	"sync"
	"time"

	"github.com/e-travel/cloudwatchlogsbeat/config"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go/service/cloudwatchlogs/cloudwatchlogsiface"
	"github.com/elastic/beats/libbeat/logp"
)

type Group struct {
	Name       string
	Prospector *config.Prospector
	Client     cloudwatchlogsiface.CloudWatchLogsAPI
	Beat       *Cloudwatchlogsbeat
	Streams    map[string]*Stream
	// we'll use this mutex to synchronize access to the Streams map
	mutex *sync.RWMutex
}

func NewGroup(name string, prospector *config.Prospector, beat *Cloudwatchlogsbeat) *Group {
	return &Group{
		Name:       name,
		Prospector: prospector,
		Client:     beat.AWSClient,
		Beat:       beat,
		Streams:    make(map[string]*Stream),
		mutex:      &sync.RWMutex{},
	}
}

func (group *Group) RefreshStreams() {
	params := &cloudwatchlogs.DescribeLogStreamsInput{
		LogGroupName: aws.String(group.Name),
		Descending:   aws.Bool(true),
		OrderBy:      aws.String("LastEventTime"),
	}

	timeHorizon := time.Now().UTC().Add(-group.Prospector.StreamLastEventHorizon)

	isStreamExpired := func(lastEventTimestamp *int64) bool {
		return ToTime(*lastEventTimestamp).Before(timeHorizon)
	}

	err := group.Client.DescribeLogStreamsPages(
		params,
		func(page *cloudwatchlogs.DescribeLogStreamsOutput, lastPage bool) bool {
			for _, logStream := range page.LogStreams {
				name := aws.StringValue(logStream.LogStreamName)
				if logStream.LastEventTimestamp == nil {
					logp.Critical("We have a nil stream timestamp (%s/%s)", group.Name, name)
					continue
				}
				// is the stream too old?
				expired := isStreamExpired(logStream.LastEventTimestamp)
				// are we monitoring the stream already?
				group.mutex.RLock()
				stream, ok := group.Streams[name]
				group.mutex.RUnlock()
				// is this a stream that we're monitoring and it has expired?
				if ok && expired {
					stream.expired <- true
				}
				// is this a stream that we're not monitoring and it is not expired?
				if !ok && !expired {
					group.addNewStream(name)
				}
			}
			return true
		})
	if err != nil {
		logp.Err("Failed to fetch streams for group %s", group.Name)
	}
}

func (group *Group) removeStream(stream *Stream) {
	logp.Info("Stop monitoring stream %s for group %s", stream.Name, group.Name)
	group.mutex.Lock()
	delete(group.Streams, stream.Name)
	group.mutex.Unlock()
}

func (group *Group) addNewStream(name string) {
	finished := make(chan bool)
	expired := make(chan bool)
	stream := NewStream(name, group, group.Client, group.Beat.Registry, finished, expired)
	logp.Info("Start monitoring stream %s for group %s", stream.Name, group.Name)
	group.mutex.Lock()
	group.Streams[name] = stream
	group.mutex.Unlock()
	go stream.Monitor()
	go func() {
		<-finished
		group.removeStream(stream)
	}()
}

func (group *Group) Monitor() {
	logp.Info("Monitoring group %s", group.Name)
	for {
		group.RefreshStreams()
		time.Sleep(group.Beat.Config.StreamRefreshPeriod)
	}
}
<commit_msg>Improves logging in case of a nil stream timestamp<commit_after>package beater

import (
	"sync"
	"time"

	"github.com/e-travel/cloudwatchlogsbeat/config"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go/service/cloudwatchlogs/cloudwatchlogsiface"
	"github.com/elastic/beats/libbeat/logp"
)

type Group struct {
	Name       string
	Prospector *config.Prospector
	Client     cloudwatchlogsiface.CloudWatchLogsAPI
	Beat       *Cloudwatchlogsbeat
	Streams    map[string]*Stream
	// we'll use this mutex to synchronize access to the Streams map
	mutex *sync.RWMutex
}

func NewGroup(name string, prospector *config.Prospector, beat *Cloudwatchlogsbeat) *Group {
	return &Group{
		Name:       name,
		Prospector: prospector,
		Client:     beat.AWSClient,
		Beat:       beat,
		Streams:    make(map[string]*Stream),
		mutex:      &sync.RWMutex{},
	}
}

func (group *Group) RefreshStreams() {
	params := &cloudwatchlogs.DescribeLogStreamsInput{
		LogGroupName: aws.String(group.Name),
		Descending:   aws.Bool(true),
		OrderBy:      aws.String("LastEventTime"),
	}

	timeHorizon := time.Now().UTC().Add(-group.Prospector.StreamLastEventHorizon)

	isStreamExpired := func(lastEventTimestamp *int64) bool {
		return ToTime(*lastEventTimestamp).Before(timeHorizon)
	}

	err := group.Client.DescribeLogStreamsPages(
		params,
		func(page *cloudwatchlogs.DescribeLogStreamsOutput, lastPage bool) bool {
			for _, logStream := range page.LogStreams {
				name := aws.StringValue(logStream.LogStreamName)
				if logStream.LastEventTimestamp == nil {
					logp.Warn("We have a nil stream timestamp (%s/%s) %v", group.Name, name, *logStream)
					continue
				}
				// is the stream too old?
				expired := isStreamExpired(logStream.LastEventTimestamp)
				// are we monitoring the stream already?
				group.mutex.RLock()
				stream, ok := group.Streams[name]
				group.mutex.RUnlock()
				// is this a stream that we're monitoring and it has expired?
				if ok && expired {
					stream.expired <- true
				}
				// is this a stream that we're not monitoring and it is not expired?
				if !ok && !expired {
					group.addNewStream(name)
				}
			}
			return true
		})
	if err != nil {
		logp.Err("Failed to fetch streams for group %s", group.Name)
	}
}

func (group *Group) removeStream(stream *Stream) {
	logp.Info("Stop monitoring stream %s for group %s", stream.Name, group.Name)
	group.mutex.Lock()
	delete(group.Streams, stream.Name)
	group.mutex.Unlock()
}

func (group *Group) addNewStream(name string) {
	finished := make(chan bool)
	expired := make(chan bool)
	stream := NewStream(name, group, group.Client, group.Beat.Registry, finished, expired)
	logp.Info("Start monitoring stream %s for group %s", stream.Name, group.Name)
	group.mutex.Lock()
	group.Streams[name] = stream
	group.mutex.Unlock()
	go stream.Monitor()
	go func() {
		<-finished
		group.removeStream(stream)
	}()
}

func (group *Group) Monitor() {
	logp.Info("Monitoring group %s", group.Name)
	for {
		group.RefreshStreams()
		time.Sleep(group.Beat.Config.StreamRefreshPeriod)
	}
}
<|endoftext|>


<commit_before>// +build ignore

package main

import (
	"fmt"
	"os"
	"sort"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type Event struct {
	Name string
	Link string
	Desc string
	Spec string
}

func main() {
	nameMap := map[string]string{
		"afterprint":               "AfterPrint",
		"animationend":             "AnimationEnd",
		"animationiteration":       "AnimationIteration",
		"animationstart":           "AnimationStart",
		"audioprocess":             "AudioProcess",
		"audioend":                 "AudioEnd",
		"audiostart":               "AudioStart",
		"beforeprint":              "BeforePrint",
		"beforeunload":             "BeforeUnload",
		"canplay":                  "CanPlay",
		"canplaythrough":           "CanPlayThrough",
		"chargingchange":           "ChargingChange",
		"chargingtimechange":       "ChargingTimeChange",
		"compassneedscalibration":  "CompassNeedsCalibration",
		"compositionend":           "CompositionEnd",
		"compositionstart":         "CompositionStart",
		"compositionupdate":        "CompositionUpdate",
		"contextmenu":              "ContextMenu",
		"dblclick":                 "DoubleClick",
		"devicelight":              "DeviceLight",
		"devicemotion":             "DeviceMotion",
		"deviceorientation":        "DeviceOrientation",
		"deviceproximity":          "DeviceProximity",
		"dischargingtimechange":    "DischargingTimeChange",
		"dragend":                  "DragEnd",
		"dragenter":                "DragEnter",
		"dragleave":                "DragLeave",
		"dragover":                 "DragOver",
		"dragstart":                "DragStart",
		"durationchange":           "DurationChange",
		"focusin":                  "FocusIn",
		"focusout":                 "FocusOut",
		"fullscreenchange":         "FullScreenChange",
		"fullscreenerror":          "FullScreenError",
		"gamepadconnected":         "GamepadConnected",
		"gamepaddisconnected":      "GamepadDisconnected",
		"gotpointercapture":        "GotPointerCapture",
		"hashchange":               "HashChange",
		"keydown":                  "KeyDown",
		"keypress":                 "KeyPress",
		"keyup":                    "KeyUp",
		"languagechange":           "LanguageChange",
		"levelchange":              "LevelChange",
		"loadeddata":               "LoadedData",
		"loadedmetadata":           "LoadedMetadata",
		"loadend":                  "LoadEnd",
		"loadstart":                "LoadStart",
		"lostpointercapture":       "LostPointerCapture",
		"mousedown":                "MouseDown",
		"mouseenter":               "MouseEnter",
		"mouseleave":               "MouseLeave",
		"mousemove":                "MouseMove",
		"mouseout":                 "MouseOut",
		"mouseover":                "MouseOver",
		"mouseup":                  "MouseUp",
		"noupdate":                 "NoUpdate",
		"nomatch":                  "NoMatch",
		"notificationclick":        "NotificationClick",
		"orientationchange":        "OrientationChange",
		"pagehide":                 "PageHide",
		"pageshow":                 "PageShow",
		"pointercancel":            "PointerCancel",
		"pointerdown":              "PointerDown",
		"pointerenter":             "PointerEnter",
		"pointerleave":             "PointerLeave",
		"pointerlockchange":        "PointerLockChange",
		"pointerlockerror":         "PointerLockError",
		"pointermove":              "PointerMove",
		"pointerout":               "PointerOut",
		"pointerover":              "PointerOver",
		"pointerup":                "PointerUp",
		"popstate":                 "PopState",
		"pushsubscriptionchange":   "PushSubscriptionChange",
		"ratechange":               "RateChange",
		"readystatechange":         "ReadyStateChange",
		"resourcetimingbufferfull": "ResourceTimingBufferFull",
		"selectstart":              "SelectStart",
		"selectionchange":          "SelectionChange",
		"soundend":                 "SoundEnd",
		"soundstart":               "SoundStart",
		"speechend":                "SpeechEnd",
		"speechstart":              "SpeechStart",
		"timeupdate":               "TimeUpdate",
		"touchcancel":              "TouchCancel",
		"touchend":                 "TouchEnd",
		"touchenter":               "TouchEnter",
		"touchleave":               "TouchLeave",
		"touchmove":                "TouchMove",
		"touchstart":               "TouchStart",
		"transitionend":            "TransitionEnd",
		"updateready":              "UpdateReady",
		"upgradeneeded":            "UpgradeNeeded",
		"userproximity":            "UserProximity",
		"versionchange":            "VersionChange",
		"visibilitychange":         "VisibilityChange",
		"voiceschanged":            "VoicesChanged",
		"volumechange":             "VolumeChange",
		"vrdisplayconnected":       "VRDisplayConnected",
		"vrdisplaydisconnected":    "VRDisplayDisconnected",
		"vrdisplaypresentchange":   "VRDisplayPresentChange",
	}

	doc, err := goquery.NewDocument("https://developer.mozilla.org/en-US/docs/Web/Events")
	if err != nil {
		panic(err)
	}

	events := make(map[string]*Event)

	doc.Find(".standard-table").Eq(0).Find("tr").Each(func(i int, s *goquery.Selection) {
		cols := s.Find("td")
		if cols.Length() == 0 || cols.Find(".icon-thumbs-down-alt").Length() != 0 {
			return
		}
		link := cols.Eq(0).Find("a").Eq(0)
		var e Event
		e.Name = link.Text()
		e.Link, _ = link.Attr("href")
		e.Desc = strings.TrimSpace(cols.Eq(3).Text())
		if e.Desc == "" {
			e.Desc = "(no documentation)"
		}
		e.Spec = strings.TrimSpace(cols.Eq(2).Text())

		funName := nameMap[e.Name]
		if funName == "" {
			funName = capitalize(e.Name)
		}

		events[funName] = &e
	})

	var names []string
	for name := range events {
		names = append(names, name)
	}
	sort.Strings(names)

	file, err := os.Create("event.gen.go")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	fmt.Fprint(file, `//go:generate go run generate.go

// Package event defines markup to bind DOM events.
//
// Generated from "Event reference" by Mozilla Contributors,
// https://developer.mozilla.org/en-US/docs/Web/Events, licensed under
// CC-BY-SA 2.5.
package event

import "github.com/gopherjs/vecty"
`)

	for _, name := range names {
		e := events[name]
		if e.Spec == "WebVR API" {
			continue // not stabilized
		}
		fmt.Fprintf(file, `%s
//
// https://developer.mozilla.org%s
func %s(listener func(*vecty.Event)) *vecty.EventListener {
	return &vecty.EventListener{Name: "%s", Listener: listener}
}
`, descToComments(e.Desc), e.Link[6:], name, e.Name)
	}
}

func capitalize(s string) string {
	return strings.ToUpper(s[:1]) + s[1:]
}

func descToComments(desc string) string {
	c := ""
	length := 80
	for _, word := range strings.Split(desc, " ") {
		if length+len(word)+1 > 80 {
			length = 3
			c += "\n//"
		}
		c += " " + word
		length += len(word) + 1
	}
	return c
}
<commit_msg>event: start all func docstrings with the func name<commit_after>// +build ignore

package main

import (
	"fmt"
	"os"
	"sort"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type Event struct {
	Name string
	Link string
	Desc string
	Spec string
}

func main() {
	nameMap := map[string]string{
		"afterprint":               "AfterPrint",
		"animationend":             "AnimationEnd",
		"animationiteration":       "AnimationIteration",
		"animationstart":           "AnimationStart",
		"audioprocess":             "AudioProcess",
		"audioend":                 "AudioEnd",
		"audiostart":               "AudioStart",
		"beforeprint":              "BeforePrint",
		"beforeunload":             "BeforeUnload",
		"canplay":                  "CanPlay",
		"canplaythrough":           "CanPlayThrough",
		"chargingchange":           "ChargingChange",
		"chargingtimechange":       "ChargingTimeChange",
		"compassneedscalibration":  "CompassNeedsCalibration",
		"compositionend":           "CompositionEnd",
		"compositionstart":         "CompositionStart",
		"compositionupdate":        "CompositionUpdate",
		"contextmenu":              "ContextMenu",
		"dblclick":                 "DoubleClick",
		"devicelight":              "DeviceLight",
		"devicemotion":             "DeviceMotion",
		"deviceorientation":        "DeviceOrientation",
		"deviceproximity":          "DeviceProximity",
		"dischargingtimechange":    "DischargingTimeChange",
		"dragend":                  "DragEnd",
		"dragenter":                "DragEnter",
		"dragleave":                "DragLeave",
		"dragover":                 "DragOver",
		"dragstart":                "DragStart",
		"durationchange":           "DurationChange",
		"focusin":                  "FocusIn",
		"focusout":                 "FocusOut",
		"fullscreenchange":         "FullScreenChange",
		"fullscreenerror":          "FullScreenError",
		"gamepadconnected":         "GamepadConnected",
		"gamepaddisconnected":      "GamepadDisconnected",
		"gotpointercapture":        "GotPointerCapture",
		"hashchange":               "HashChange",
		"keydown":                  "KeyDown",
		"keypress":                 "KeyPress",
		"keyup":                    "KeyUp",
		"languagechange":           "LanguageChange",
		"levelchange":              "LevelChange",
		"loadeddata":               "LoadedData",
		"loadedmetadata":           "LoadedMetadata",
		"loadend":                  "LoadEnd",
		"loadstart":                "LoadStart",
		"lostpointercapture":       "LostPointerCapture",
		"mousedown":                "MouseDown",
		"mouseenter":               "MouseEnter",
		"mouseleave":               "MouseLeave",
		"mousemove":                "MouseMove",
		"mouseout":                 "MouseOut",
		"mouseover":                "MouseOver",
		"mouseup":                  "MouseUp",
		"noupdate":                 "NoUpdate",
		"nomatch":                  "NoMatch",
		"notificationclick":        "NotificationClick",
		"orientationchange":        "OrientationChange",
		"pagehide":                 "PageHide",
		"pageshow":                 "PageShow",
		"pointercancel":            "PointerCancel",
		"pointerdown":              "PointerDown",
		"pointerenter":             "PointerEnter",
		"pointerleave":             "PointerLeave",
		"pointerlockchange":        "PointerLockChange",
		"pointerlockerror":         "PointerLockError",
		"pointermove":              "PointerMove",
		"pointerout":               "PointerOut",
		"pointerover":              "PointerOver",
		"pointerup":                "PointerUp",
		"popstate":                 "PopState",
		"pushsubscriptionchange":   "PushSubscriptionChange",
		"ratechange":               "RateChange",
		"readystatechange":         "ReadyStateChange",
		"resourcetimingbufferfull": "ResourceTimingBufferFull",
		"selectstart":              "SelectStart",
		"selectionchange":          "SelectionChange",
		"soundend":                 "SoundEnd",
		"soundstart":               "SoundStart",
		"speechend":                "SpeechEnd",
		"speechstart":              "SpeechStart",
		"timeupdate":               "TimeUpdate",
		"touchcancel":              "TouchCancel",
		"touchend":                 "TouchEnd",
		"touchenter":               "TouchEnter",
		"touchleave":               "TouchLeave",
		"touchmove":                "TouchMove",
		"touchstart":               "TouchStart",
		"transitionend":            "TransitionEnd",
		"updateready":              "UpdateReady",
		"upgradeneeded":            "UpgradeNeeded",
		"userproximity":            "UserProximity",
		"versionchange":            "VersionChange",
		"visibilitychange":         "VisibilityChange",
		"voiceschanged":            "VoicesChanged",
		"volumechange":             "VolumeChange",
		"vrdisplayconnected":       "VRDisplayConnected",
		"vrdisplaydisconnected":    "VRDisplayDisconnected",
		"vrdisplaypresentchange":   "VRDisplayPresentChange",
	}

	doc, err := goquery.NewDocument("https://developer.mozilla.org/en-US/docs/Web/Events")
	if err != nil {
		panic(err)
	}

	events := make(map[string]*Event)

	doc.Find(".standard-table").Eq(0).Find("tr").Each(func(i int, s *goquery.Selection) {
		cols := s.Find("td")
		if cols.Length() == 0 || cols.Find(".icon-thumbs-down-alt").Length() != 0 {
			return
		}
		link := cols.Eq(0).Find("a").Eq(0)
		var e Event
		e.Name = link.Text()
		e.Link, _ = link.Attr("href")
		e.Desc = strings.TrimSpace(cols.Eq(3).Text())
		e.Spec = strings.TrimSpace(cols.Eq(2).Text())

		funName := nameMap[e.Name]
		if funName == "" {
			funName = capitalize(e.Name)
		}

		if e.Desc != "" {
			// Lowercase the first letter of the description.
			lowercaseDesc := strings.ToLower(string(e.Desc[0])) + e.Desc[1:]
			e.Desc = fmt.Sprintf("%s is an event fired when %s", funName, lowercaseDesc)
		} else {
			e.Desc = "(no documentation)"
		}
		events[funName] = &e
	})

	var names []string
	for name := range events {
		names = append(names, name)
	}
	sort.Strings(names)

	file, err := os.Create("event.gen.go")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	fmt.Fprint(file, `//go:generate go run generate.go

// Package event defines markup to bind DOM events.
//
// Generated from "Event reference" by Mozilla Contributors,
// https://developer.mozilla.org/en-US/docs/Web/Events, licensed under
// CC-BY-SA 2.5.
package event

import "github.com/gopherjs/vecty"
`)

	for _, name := range names {
		e := events[name]
		if e.Spec == "WebVR API" {
			continue // not stabilized
		}
		fmt.Fprintf(file, `%s
//
// https://developer.mozilla.org%s
func %s(listener func(*vecty.Event)) *vecty.EventListener {
	return &vecty.EventListener{Name: "%s", Listener: listener}
}
`, descToComments(e.Desc), e.Link[6:], name, e.Name)
	}
}

func capitalize(s string) string {
	return strings.ToUpper(s[:1]) + s[1:]
}

func descToComments(desc string) string {
	c := ""
	length := 80
	for _, word := range strings.Split(desc, " ") {
		if length+len(word)+1 > 80 {
			length = 3
			c += "\n//"
		}
		c += " " + word
		length += len(word) + 1
	}
	return c
}
<|endoftext|>


<commit_before>package router

import (
	"net"
	"strconv"
	"sync"
	"testing"
	"time"

	"github.com/wandoulabs/codis/pkg/proxy/redis"
	"github.com/wandoulabs/codis/pkg/utils/assert"
)

func TestBackend(t *testing.T) {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	assert.MustNoError(err)
	defer l.Close()

	addr := l.Addr().String()
	reqc := make(chan *Request, 16384)
	go func() {
		bc := NewBackendConn(addr)
		defer bc.Close()
		defer close(reqc)
		var resp = redis.NewBulkBytes(make([]byte, 4096))
		for i := 0; i < cap(reqc); i++ {
			r := &Request{
				Resp: resp,
				slot: &Slot{},
				wait: &sync.WaitGroup{},
			}
			r.slot.jobs.Add(1)
			r.wait.Add(1)
			bc.PushBack(r)
			reqc <- r
		}
	}()

	go func() {
		c, err := l.Accept()
		assert.MustNoError(err)
		defer c.Close()
		conn := redis.NewConn(c)
		time.Sleep(time.Millisecond * 300)
		for i := 0; i < cap(reqc); i++ {
			_, err := conn.Reader.Decode()
			assert.MustNoError(err)
			resp := redis.NewString([]byte(strconv.Itoa(i)))
			assert.MustNoError(conn.Writer.Encode(resp, true))
		}
	}()

	var n int
	for r := range reqc {
		r.Wait()
		assert.Must(string(r.Response.Resp.Value) == strconv.Itoa(n))
		n++
	}
	assert.Must(n == cap(reqc))
}
<commit_msg>fix bug in backend conn tests<commit_after>package router

import (
	"net"
	"strconv"
	"sync"
	"testing"
	"time"

	"github.com/wandoulabs/codis/pkg/proxy/redis"
	"github.com/wandoulabs/codis/pkg/utils/assert"
)

func TestBackend(t *testing.T) {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	assert.MustNoError(err)
	defer l.Close()

	addr := l.Addr().String()
	reqc := make(chan *Request, 16384)
	go func() {
		bc := NewBackendConn(addr)
		defer bc.Close()
		defer close(reqc)
		var resp = redis.NewBulkBytes(make([]byte, 4096))
		for i := 0; i < cap(reqc); i++ {
			r := &Request{
				Resp: resp,
				slot: &Slot{},
				wait: &sync.WaitGroup{},
			}
			r.slot.jobs.Add(1)
			r.wait.Add(1)
			bc.PushBack(r)
			reqc <- r
		}
	}()

	go func() {
		c, err := l.Accept()
		assert.MustNoError(err)
		defer c.Close()
		conn := redis.NewConn(c)
		time.Sleep(time.Millisecond * 300)
		for i := 0; i < cap(reqc); i++ {
			_, err := conn.Reader.Decode()
			assert.MustNoError(err)
			resp := redis.NewString([]byte(strconv.Itoa(i)))
			assert.MustNoError(conn.Writer.Encode(resp, true))
		}
	}()

	var n int
	for r := range reqc {
		r.wait.Wait()
		assert.Must(string(r.Response.Resp.Value) == strconv.Itoa(n))
		n++
	}
	assert.Must(n == cap(reqc))
}
<|endoftext|>


<commit_before>/*
Copyright 2020 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package systemstatsmonitor

// deviceNameLabel labels the monitored disk device, e.g.: "sda", "sda1".
const deviceNameLabel = "device_name"

// directionLabel labels the direction of the disk operations, e.g.: "read", "write".
const directionLabel = "direction"

// stateLabel labels the state of disk/memory/cpu usage, e.g.: "free", "used".
const stateLabel = "state"

// fsTypeLabel labels the fst type of the disk, e.g.: "ext4", "ext2", "vfat"
const fsTypeLabel = "fstype"

// mountPointLabel labels the mountpoint of the monitored disk device
const mountOptionLabel = "mountoption"
<commit_msg>changing the label names as per the standards<commit_after>/*
Copyright 2020 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package systemstatsmonitor

// deviceNameLabel labels the monitored disk device, e.g.: "sda", "sda1".
const deviceNameLabel = "device_name"

// directionLabel labels the direction of the disk operations, e.g.: "read", "write".
const directionLabel = "direction"

// stateLabel labels the state of disk/memory/cpu usage, e.g.: "free", "used".
const stateLabel = "state"

// fsTypeLabel labels the fs type of the disk, e.g.: "ext4", "ext2", "vfat"
const fsTypeLabel = "fs_type"

// mountOptionLabel labels the mount_options of the monitored disk device
const mountOptionLabel = "mount_option"
<|endoftext|>


<commit_before>package command

import (
	"io/ioutil"
	"os"
	"strings"
	"testing"

	"github.com/mitchellh/cli"
)

func TestPlanCommand_Implements(t *testing.T) {
	var _ cli.Command = &RunCommand{}
}

func TestPlanCommand_Fails(t *testing.T) {
	ui := new(cli.MockUi)
	cmd := &PlanCommand{Meta: Meta{Ui: ui}}

	// Fails on misuse
	if code := cmd.Run([]string{"some", "bad", "args"}); code != 255 {
		t.Fatalf("expected exit code 1, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, cmd.Help()) {
		t.Fatalf("expected help output, got: %s", out)
	}
	ui.ErrorWriter.Reset()

	// Fails when specified file does not exist
	if code := cmd.Run([]string{"/unicorns/leprechauns"}); code != 255 {
		t.Fatalf("expect exit 1, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error getting job struct") {
		t.Fatalf("expect getting job struct error, got: %s", out)
	}
	ui.ErrorWriter.Reset()

	// Fails on invalid HCL
	fh1, err := ioutil.TempFile("", "nomad")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(fh1.Name())
	if _, err := fh1.WriteString("nope"); err != nil {
		t.Fatalf("err: %s", err)
	}
	if code := cmd.Run([]string{fh1.Name()}); code != 255 {
		t.Fatalf("expect exit 1, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error getting job struct") {
		t.Fatalf("expect parsing error, got: %s", out)
	}
	ui.ErrorWriter.Reset()

	// Fails on invalid job spec
	fh2, err := ioutil.TempFile("", "nomad")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(fh2.Name())
	if _, err := fh2.WriteString(`job "job1" {}`); err != nil {
		t.Fatalf("err: %s", err)
	}
	if code := cmd.Run([]string{fh2.Name()}); code != 255 {
		t.Fatalf("expect exit 1, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error validating") {
		t.Fatalf("expect validation error, got: %s", out)
	}
	ui.ErrorWriter.Reset()

	// Fails on connection failure (requires a valid job)
	fh3, err := ioutil.TempFile("", "nomad")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(fh3.Name())
	_, err = fh3.WriteString(`
job "job1" {
	type = "service"
	datacenters = [ "dc1" ]
	group "group1" {
		count = 1
		task "task1" {
			driver = "exec"
			resources = {
				cpu = 1000
				disk = 150
				memory = 512
			}
		}
	}
}`)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if code := cmd.Run([]string{"-address=nope", fh3.Name()}); code != 255 {
		t.Fatalf("expected exit code 1, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error during plan") {
		t.Fatalf("expected failed query error, got: %s", out)
	}
}

func TestPlanCommand_From_STDIN(t *testing.T) {
	stdinR, stdinW, err := os.Pipe()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	ui := new(cli.MockUi)
	cmd := &PlanCommand{
		Meta:      Meta{Ui: ui},
		JobGetter: JobGetter{testStdin: stdinR},
	}

	go func() {
		stdinW.WriteString(`
job "job1" {
  type = "service"
  datacenters = [ "dc1" ]
  group "group1" {
                count = 1
                task "task1" {
                        driver = "exec"
                        resources = {
                                cpu = 1000
                                disk = 150
                                memory = 512
                        }
                }
        }
}`)
		stdinW.Close()
	}()

	args := []string{"-"}
	if code := cmd.Run(args); code != 255 {
		t.Fatalf("expected exit code 255, got %d: %q", code, ui.ErrorWriter.String())
	}

	if out := ui.ErrorWriter.String(); !strings.Contains(out, "connection refused") {
		t.Fatalf("expected connection refused error, got: %s", out)
	}
	ui.ErrorWriter.Reset()
}

func TestPlanCommand_From_URL(t *testing.T) {
	ui := new(cli.MockUi)
	cmd := &RunCommand{
		Meta: Meta{Ui: ui},
	}

	args := []string{"https://example.com/foo/bar"}
	if code := cmd.Run(args); code != 1 {
		t.Fatalf("expected exit code 1, got %d: %q", code, ui.ErrorWriter.String())
	}

	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error getting jobfile") {
		t.Fatalf("expected error getting jobfile, got: %s", out)
	}
}
<commit_msg>command.plan: tiny: Fix expect error code message from 1 to 255<commit_after>package command

import (
	"io/ioutil"
	"os"
	"strings"
	"testing"

	"github.com/mitchellh/cli"
)

func TestPlanCommand_Implements(t *testing.T) {
	var _ cli.Command = &RunCommand{}
}

func TestPlanCommand_Fails(t *testing.T) {
	ui := new(cli.MockUi)
	cmd := &PlanCommand{Meta: Meta{Ui: ui}}

	// Fails on misuse
	if code := cmd.Run([]string{"some", "bad", "args"}); code != 255 {
		t.Fatalf("expected exit code 1, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, cmd.Help()) {
		t.Fatalf("expected help output, got: %s", out)
	}
	ui.ErrorWriter.Reset()

	// Fails when specified file does not exist
	if code := cmd.Run([]string{"/unicorns/leprechauns"}); code != 255 {
		t.Fatalf("expect exit 255, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error getting job struct") {
		t.Fatalf("expect getting job struct error, got: %s", out)
	}
	ui.ErrorWriter.Reset()

	// Fails on invalid HCL
	fh1, err := ioutil.TempFile("", "nomad")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(fh1.Name())
	if _, err := fh1.WriteString("nope"); err != nil {
		t.Fatalf("err: %s", err)
	}
	if code := cmd.Run([]string{fh1.Name()}); code != 255 {
		t.Fatalf("expect exit 255, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error getting job struct") {
		t.Fatalf("expect parsing error, got: %s", out)
	}
	ui.ErrorWriter.Reset()

	// Fails on invalid job spec
	fh2, err := ioutil.TempFile("", "nomad")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(fh2.Name())
	if _, err := fh2.WriteString(`job "job1" {}`); err != nil {
		t.Fatalf("err: %s", err)
	}
	if code := cmd.Run([]string{fh2.Name()}); code != 255 {
		t.Fatalf("expect exit 255, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error validating") {
		t.Fatalf("expect validation error, got: %s", out)
	}
	ui.ErrorWriter.Reset()

	// Fails on connection failure (requires a valid job)
	fh3, err := ioutil.TempFile("", "nomad")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(fh3.Name())
	_, err = fh3.WriteString(`
job "job1" {
	type = "service"
	datacenters = [ "dc1" ]
	group "group1" {
		count = 1
		task "task1" {
			driver = "exec"
			resources = {
				cpu = 1000
				disk = 150
				memory = 512
			}
		}
	}
}`)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if code := cmd.Run([]string{"-address=nope", fh3.Name()}); code != 255 {
		t.Fatalf("expected exit code 255, got: %d", code)
	}
	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error during plan") {
		t.Fatalf("expected failed query error, got: %s", out)
	}
}

func TestPlanCommand_From_STDIN(t *testing.T) {
	stdinR, stdinW, err := os.Pipe()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	ui := new(cli.MockUi)
	cmd := &PlanCommand{
		Meta:      Meta{Ui: ui},
		JobGetter: JobGetter{testStdin: stdinR},
	}

	go func() {
		stdinW.WriteString(`
job "job1" {
  type = "service"
  datacenters = [ "dc1" ]
  group "group1" {
                count = 1
                task "task1" {
                        driver = "exec"
                        resources = {
                                cpu = 1000
                                disk = 150
                                memory = 512
                        }
                }
        }
}`)
		stdinW.Close()
	}()

	args := []string{"-"}
	if code := cmd.Run(args); code != 255 {
		t.Fatalf("expected exit code 255, got %d: %q", code, ui.ErrorWriter.String())
	}

	if out := ui.ErrorWriter.String(); !strings.Contains(out, "connection refused") {
		t.Fatalf("expected connection refused error, got: %s", out)
	}
	ui.ErrorWriter.Reset()
}

func TestPlanCommand_From_URL(t *testing.T) {
	ui := new(cli.MockUi)
	cmd := &PlanCommand{
		Meta: Meta{Ui: ui},
	}

	args := []string{"https://example.com/foo/bar"}
	if code := cmd.Run(args); code != 255 {
		t.Fatalf("expected exit code 255, got %d: %q", code, ui.ErrorWriter.String())
	}

	if out := ui.ErrorWriter.String(); !strings.Contains(out, "Error getting jobfile") {
		t.Fatalf("expected error getting jobfile, got: %s", out)
	}
}
<|endoftext|>


<commit_before>package commands

import (
	"flag"
	"fmt"
	"strings"
)

var (
	NameRe          = "[\\w.][\\w.-]*"
	OwnerRe         = "[a-zA-Z0-9][a-zA-Z0-9-]*"
	NameWithOwnerRe = fmt.Sprintf("^(?:%s|%s\\/%s)$", NameRe, OwnerRe, NameRe)
)

type Command struct {
	Run  func(cmd *Command, args *Args)
	Flag flag.FlagSet

	Usage        string
	Short        string
	Long         string
	GitExtension bool
}

func (c *Command) PrintUsage() {
	if c.Runnable() {
		fmt.Printf("Usage: git %s\n\n", c.Usage)
	}

	fmt.Println(strings.Trim(c.Long, "\n"))
}

func (c *Command) Name() string {
	name := c.Usage
	i := strings.Index(name, " ")
	if i >= 0 {
		name = name[:i]
	}
	return name
}

func (c *Command) Runnable() bool {
	return c.Run != nil
}

func (c *Command) List() bool {
	return c.Short != ""
}

var Basic = []*Command{
	cmdInit,
}

var Branching = []*Command{
	cmdCheckout,
	cmdMerge,
	cmdApply,
	cmdCherryPick,
}

var Remote = []*Command{
	cmdClone,
	cmdFetch,
	cmdPush,
	cmdRemote,
	cmdSubmodule,
}

var GitHub = []*Command{
	cmdPullRequest,
	cmdFork,
	cmdCreate,
	cmdCiStatus,
	cmdBrowse,
	cmdCompare,
	cmdRelease,
	cmdIssues,
}

func All() []*Command {
	all := make([]*Command, 0)
	all = append(all, Basic...)
	all = append(all, Branching...)
	all = append(all, Remote...)
	all = append(all, GitHub...)
	all = append(all, cmdAlias)
	all = append(all, cmdVersion)
	all = append(all, cmdHelp)

	return all
}
<commit_msg>Fix typo<commit_after>package commands

import (
	"flag"
	"fmt"
	"strings"
)

var (
	NameRe          = "[\\w.][\\w.-]*"
	OwnerRe         = "[a-zA-Z0-9][a-zA-Z0-9-]*"
	NameWithOwnerRe = fmt.Sprintf("^(?:%s|%s\\/%s)$", NameRe, OwnerRe, NameRe)
)

type Command struct {
	Run  func(cmd *Command, args *Args)
	Flag flag.FlagSet

	Usage        string
	Short        string
	Long         string
	GitExtension bool
}

func (c *Command) PrintUsage() {
	if c.Runnable() {
		fmt.Printf("Usage: git %s\n\n", c.Usage)
	}

	fmt.Println(strings.Trim(c.Long, "\n"))
}

func (c *Command) Name() string {
	name := c.Usage
	i := strings.Index(name, " ")
	if i >= 0 {
		name = name[:i]
	}
	return name
}

func (c *Command) Runnable() bool {
	return c.Run != nil
}

func (c *Command) List() bool {
	return c.Short != ""
}

var Basic = []*Command{
	cmdInit,
}

var Branching = []*Command{
	cmdCheckout,
	cmdMerge,
	cmdApply,
	cmdCherryPick,
}

var Remote = []*Command{
	cmdClone,
	cmdFetch,
	cmdPush,
	cmdRemote,
	cmdSubmodule,
}

var GitHub = []*Command{
	cmdPullRequest,
	cmdFork,
	cmdCreate,
	cmdCiStatus,
	cmdBrowse,
	cmdCompare,
	cmdRelease,
	cmdIssue,
}

func All() []*Command {
	all := make([]*Command, 0)
	all = append(all, Basic...)
	all = append(all, Branching...)
	all = append(all, Remote...)
	all = append(all, GitHub...)
	all = append(all, cmdAlias)
	all = append(all, cmdVersion)
	all = append(all, cmdHelp)

	return all
}
<|endoftext|>


<commit_before>package terraform

import (
	"fmt"

	"github.com/hashicorp/go-version"
)

// The main version number that is being run at the moment.
const Version = "0.8.4"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
const VersionPrerelease = ""

// SemVersion is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVersion = version.Must(version.NewVersion(Version))

// VersionHeader is the header name used to send the current terraform version
// in http requests.
const VersionHeader = "Terraform-Version"

func VersionString() string {
	if VersionPrerelease != "" {
		return fmt.Sprintf("%s-%s", Version, VersionPrerelease)
	}
	return Version
}
<commit_msg>release: clean up after v0.8.4<commit_after>package terraform

import (
	"fmt"

	"github.com/hashicorp/go-version"
)

// The main version number that is being run at the moment.
const Version = "0.8.5"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
const VersionPrerelease = "dev"

// SemVersion is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVersion = version.Must(version.NewVersion(Version))

// VersionHeader is the header name used to send the current terraform version
// in http requests.
const VersionHeader = "Terraform-Version"

func VersionString() string {
	if VersionPrerelease != "" {
		return fmt.Sprintf("%s-%s", Version, VersionPrerelease)
	}
	return Version
}
<|endoftext|>


<commit_before>package compiler

import (
  "github.com/lestrrat/go-xslate/parser"
  "github.com/lestrrat/go-xslate/vm"
)

type Compiler interface {
  Compile(* parser.AST) (*vm.ByteCode, error)
}

type CompilerCtx struct {
  ByteCode *vm.ByteCode
}

func (ctx *CompilerCtx) AppendOp(o vm.OpType, args ...interface {}) *vm.Op {
  return ctx.ByteCode.AppendOp(o, args...)
}

type BasicCompiler struct {}

func New() *BasicCompiler {
  return &BasicCompiler {}
}

func (c *BasicCompiler) Compile(ast *parser.AST) (*vm.ByteCode, error) {
  ctx := &CompilerCtx {
    ByteCode: &vm.ByteCode {},
  }
  for _, n := range ast.Root.Nodes {
    c.compile(ctx, n)
  }

  // When we're done compiling, always append an END op
  ctx.ByteCode.AppendOp(vm.TXOP_end)

  return ctx.ByteCode, nil
}

func (c *BasicCompiler) compile(ctx *CompilerCtx, n parser.Node) {
  switch n.Type() {
  case parser.NodeText:
    // XXX probably not true all the time
    ctx.AppendOp(vm.TXOP_literal, n.(*parser.TextNode).Text)
  case parser.NodeFetchSymbol:
    ctx.AppendOp(vm.TXOP_fetch_s, n.(*parser.TextNode).Text)
  case parser.NodeLocalVar:
    l := n.(*parser.LocalVarNode)
    ctx.AppendOp(vm.TXOP_load_lvar, l.Offset)
  case parser.NodeAssignment:
    c.compile(ctx, n.(*parser.AssignmentNode).Expression)
    ctx.AppendOp(vm.TXOP_save_to_lvar, 0) // XXX this 0 must be pre-computed
  case parser.NodePrint:
    c.compile(ctx, n.(*parser.ListNode).Nodes[0])
    ctx.AppendOp(vm.TXOP_print)
  case parser.NodePrintRaw:
    c.compile(ctx, n.(*parser.ListNode).Nodes[0])
    ctx.AppendOp(vm.TXOP_print_raw)
  case parser.NodeForeach:
    c.compile(ctx, n.(*parser.ForeachNode).List)
    ctx.AppendOp(vm.TXOP_for_start, 0)
    ctx.AppendOp(vm.TXOP_literal, 0)
    iter := ctx.AppendOp(vm.TXOP_for_iter, 0)
    pos  := ctx.ByteCode.Len()
    ctx.AppendOp(vm.TXOP_load_lvar, 0)

    children := n.(*parser.ForeachNode).Nodes
    for _, v := range children {
      c.compile(ctx, v)
    }

    ctx.AppendOp(vm.TXOP_goto, -1 * (ctx.ByteCode.Len() - pos + 2))
    iter.SetArg(ctx.ByteCode.Len() - pos + 1)
  }
}<commit_msg>remove stray load_lvar<commit_after>package compiler

import (
  "github.com/lestrrat/go-xslate/parser"
  "github.com/lestrrat/go-xslate/vm"
)

type Compiler interface {
  Compile(* parser.AST) (*vm.ByteCode, error)
}

type CompilerCtx struct {
  ByteCode *vm.ByteCode
}

func (ctx *CompilerCtx) AppendOp(o vm.OpType, args ...interface {}) *vm.Op {
  return ctx.ByteCode.AppendOp(o, args...)
}

type BasicCompiler struct {}

func New() *BasicCompiler {
  return &BasicCompiler {}
}

func (c *BasicCompiler) Compile(ast *parser.AST) (*vm.ByteCode, error) {
  ctx := &CompilerCtx {
    ByteCode: &vm.ByteCode {},
  }
  for _, n := range ast.Root.Nodes {
    c.compile(ctx, n)
  }

  // When we're done compiling, always append an END op
  ctx.ByteCode.AppendOp(vm.TXOP_end)

  return ctx.ByteCode, nil
}

func (c *BasicCompiler) compile(ctx *CompilerCtx, n parser.Node) {
  switch n.Type() {
  case parser.NodeText:
    // XXX probably not true all the time
    ctx.AppendOp(vm.TXOP_literal, n.(*parser.TextNode).Text)
  case parser.NodeFetchSymbol:
    ctx.AppendOp(vm.TXOP_fetch_s, n.(*parser.TextNode).Text)
  case parser.NodeLocalVar:
    l := n.(*parser.LocalVarNode)
    ctx.AppendOp(vm.TXOP_load_lvar, l.Offset)
  case parser.NodeAssignment:
    c.compile(ctx, n.(*parser.AssignmentNode).Expression)
    ctx.AppendOp(vm.TXOP_save_to_lvar, 0) // XXX this 0 must be pre-computed
  case parser.NodePrint:
    c.compile(ctx, n.(*parser.ListNode).Nodes[0])
    ctx.AppendOp(vm.TXOP_print)
  case parser.NodePrintRaw:
    c.compile(ctx, n.(*parser.ListNode).Nodes[0])
    ctx.AppendOp(vm.TXOP_print_raw)
  case parser.NodeForeach:
    c.compile(ctx, n.(*parser.ForeachNode).List)
    ctx.AppendOp(vm.TXOP_for_start, 0)
    ctx.AppendOp(vm.TXOP_literal, 0)
    iter := ctx.AppendOp(vm.TXOP_for_iter, 0)
    pos  := ctx.ByteCode.Len()

    children := n.(*parser.ForeachNode).Nodes
    for _, v := range children {
      c.compile(ctx, v)
    }

    ctx.AppendOp(vm.TXOP_goto, -1 * (ctx.ByteCode.Len() - pos + 2))
    iter.SetArg(ctx.ByteCode.Len() - pos + 1)
  }
}<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"log"
	"os"
)

func check(e error) {
	if e != nil {
		panic(e)
	}
}

type counter map[[2]int]int

func main() {
	f, err := os.Open("input.txt")
	check(err)
	defer f.Close()
	scanner := bufio.NewScanner(f)
	scanner.Scan()
	input := scanner.Text()
	currentPosition := [...]int{0, 0}
	houseVisitFrequencyMap := make(counter)
	houseVisitFrequencyMap[currentPosition]++
	for _, c := range input {
		if c == '^' {
			currentPosition[1]++
		} else if c == 'v' {
			currentPosition[1]--
		} else if c == '>' {
			currentPosition[0]++
		} else if c == '<' {
			currentPosition[0]--
		} else {
			log.Fatal("Unrecognized character: " + string(c))
		}
		houseVisitFrequencyMap[currentPosition]++
	}
	log.Printf("Answer #1=%d\n", len(houseVisitFrequencyMap))
}
<commit_msg>Day03 part 2 done.<commit_after>package main

import (
	"bufio"
	"log"
	"os"
)

func check(e error) {
	if e != nil {
		panic(e)
	}
}

type counter map[[2]int]int

func move(c rune, currentPosition *[2]int, houseVisitFrequencyMap counter) {
	if c == '^' {
		currentPosition[1]++
	} else if c == 'v' {
		currentPosition[1]--
	} else if c == '>' {
		currentPosition[0]++
	} else if c == '<' {
		currentPosition[0]--
	} else {
		log.Fatal("Unrecognized character: " + string(c))
	}
	houseVisitFrequencyMap[*currentPosition]++
}

func part1(input string) {
	currentPosition := [...]int{0, 0}
	houseVisitFrequencyMap := make(counter)
	houseVisitFrequencyMap[currentPosition]++
	for _, c := range input {
		move(c, &currentPosition, houseVisitFrequencyMap)
	}
	log.Printf("Answer #1=%d\n", len(houseVisitFrequencyMap))
}

func part2(input string) {
	santa := [...]int{0, 0}
	robot := [...]int{0, 0}
	houseVisitFrequencyMap := make(counter)
	houseVisitFrequencyMap[santa]++
	for i, c := range input {
		if (i % 2) == 0 {
			move(c, &santa, houseVisitFrequencyMap)
		} else {
			move(c, &robot, houseVisitFrequencyMap)
		}
	}
	log.Printf("Answer #2=%d\n", len(houseVisitFrequencyMap))
}

func main() {
	f, err := os.Open("input.txt")
	check(err)
	defer f.Close()
	scanner := bufio.NewScanner(f)
	scanner.Scan()
	input := scanner.Text()
	part1(input)
	part2(input)
}
<|endoftext|>


<commit_before>package api

import (
	"cf"
	"cf/configuration"
	"fmt"
	"github.com/stretchr/testify/assert"
	"net/http"
	"net/http/httptest"
	"testing"
)

var multipleOrgEndpoint = func(writer http.ResponseWriter, request *http.Request) {
	acceptHeaderMatches := request.Header.Get("accept") == "application/json"
	methodMatches := request.Method == "GET"
	pathMatches := request.URL.Path == "/v2/organizations"
	authMatches := request.Header.Get("authorization") == "BEARER my_access_token"

	if !(acceptHeaderMatches && methodMatches && pathMatches && authMatches) {
		writer.WriteHeader(http.StatusInternalServerError)
		return
	}

	jsonResponse := `
{
  "total_results": 2,
  "total_pages": 1,
  "prev_url": null,
  "next_url": null,
  "resources": [
    {
      "metadata": {
        "guid": "org1-guid"
      },
      "entity": {
        "name": "Org1"
      }
    },
    {
      "metadata": {
        "guid": "org2-guid"
      },
      "entity": {
        "name": "Org2"
      }
    }
  ]
}`
	fmt.Fprintln(writer, jsonResponse)
}

func TestOrganizationsFindAll(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(multipleOrgEndpoint))
	defer ts.Close()

	repo := CloudControllerOrganizationRepository{}

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: ts.URL}
	organizations, err := repo.FindAll(config)
	assert.NoError(t, err)
	assert.Equal(t, 2, len(organizations))

	firstOrg := organizations[0]
	assert.Equal(t, firstOrg.Name, "Org1")
	assert.Equal(t, firstOrg.Guid, "org1-guid")
	secondOrg := organizations[1]
	assert.Equal(t, secondOrg.Name, "Org2")
	assert.Equal(t, secondOrg.Guid, "org2-guid")
}

func TestOrganizationsFindAllWithIncorrectToken(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(multipleOrgEndpoint))
	defer ts.Close()

	repo := CloudControllerOrganizationRepository{}

	config := &configuration.Configuration{AccessToken: "BEARER incorrect_access_token", Target: ts.URL}
	organizations, err := repo.FindAll(config)

	assert.Error(t, err)
	assert.Equal(t, 0, len(organizations))
}

func TestOrganizationsFindByName(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(multipleOrgEndpoint))
	defer ts.Close()

	repo := CloudControllerOrganizationRepository{}
	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: ts.URL}
	existingOrg := cf.Organization{Guid: "org1-guid", Name: "Org1"}

	org, err := repo.FindByName(config, "Org1")
	assert.NoError(t, err)
	assert.Equal(t, org, existingOrg)

	org, err = repo.FindByName(config, "org1")
	assert.NoError(t, err)
	assert.Equal(t, org, existingOrg)

	org, err = repo.FindByName(config, "org that does not exist")
	assert.Error(t, err)
}
<commit_msg>Change organizations to use test endpoint generator<commit_after>package api_test

import (
	"cf"
	. "cf/api"
	"cf/configuration"
	"github.com/stretchr/testify/assert"
	"net/http"
	"net/http/httptest"
	"testhelpers"
	"testing"
)

var multipleOrgResponse = testhelpers.TestResponse{Status: http.StatusOK, Body: `
{
  "total_results": 2,
  "total_pages": 1,
  "prev_url": null,
  "next_url": null,
  "resources": [
    {
      "metadata": {
        "guid": "org1-guid"
      },
      "entity": {
        "name": "Org1"
      }
    },
    {
      "metadata": {
        "guid": "org2-guid"
      },
      "entity": {
        "name": "Org2"
      }
    }
  ]
}`}

var multipleOrgEndpoint = testhelpers.CreateEndpoint(
	"GET",
	"/v2/organizations",
	nil,
	multipleOrgResponse,
)

func TestOrganizationsFindAll(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(multipleOrgEndpoint))
	defer ts.Close()

	repo := CloudControllerOrganizationRepository{}

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: ts.URL}
	organizations, err := repo.FindAll(config)
	assert.NoError(t, err)
	assert.Equal(t, 2, len(organizations))

	firstOrg := organizations[0]
	assert.Equal(t, firstOrg.Name, "Org1")
	assert.Equal(t, firstOrg.Guid, "org1-guid")
	secondOrg := organizations[1]
	assert.Equal(t, secondOrg.Name, "Org2")
	assert.Equal(t, secondOrg.Guid, "org2-guid")
}

func TestOrganizationsFindAllWithIncorrectToken(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(multipleOrgEndpoint))
	defer ts.Close()

	repo := CloudControllerOrganizationRepository{}

	config := &configuration.Configuration{AccessToken: "BEARER incorrect_access_token", Target: ts.URL}
	organizations, err := repo.FindAll(config)

	assert.Error(t, err)
	assert.Equal(t, 0, len(organizations))
}

func TestOrganizationsFindByName(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(multipleOrgEndpoint))
	defer ts.Close()

	repo := CloudControllerOrganizationRepository{}
	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: ts.URL}
	existingOrg := cf.Organization{Guid: "org1-guid", Name: "Org1"}

	org, err := repo.FindByName(config, "Org1")
	assert.NoError(t, err)
	assert.Equal(t, org, existingOrg)

	org, err = repo.FindByName(config, "org1")
	assert.NoError(t, err)
	assert.Equal(t, org, existingOrg)

	org, err = repo.FindByName(config, "org that does not exist")
	assert.Error(t, err)
}
<|endoftext|>


<commit_before>package builder

import (
	"errors"
	"html/template"
	"reflect"
	"strings"

	"github.com/microcosm-cc/bluemonday"
	"github.com/russross/blackfriday"

	"github.com/aymerick/kowa/models"
)

func generateHTML(inputFormat string, input string) template.HTML {
	var result template.HTML

	if inputFormat == models.FORMAT_MARKDOWN {
		html := blackfriday.MarkdownCommon([]byte(input))

		result = template.HTML(bluemonday.UGCPolicy().SanitizeBytes(html))
	} else {
		sanitizePolicy := bluemonday.UGCPolicy()
		sanitizePolicy.AllowAttrs("style").OnElements("p", "span", "div") // I know this is bad

		result = template.HTML(sanitizePolicy.Sanitize(input))
	}

	return result
}

//
// Func Map
//

// Build FuncMap for template
func (builder *SiteBuilder) FuncMap() template.FuncMap {
	return template.FuncMap{
		"urlFor":     builder.UrlFor,
		"startsWith": builder.StartsWith,
		"mod":        builder.Mod,
		"modBool":    builder.ModBool,
	}
}

// Returns an URL to an internal page
func (builder *SiteBuilder) UrlFor(dest interface{}) (string, error) {
	destValue := reflect.ValueOf(dest)

	var destStr string

	switch destValue.Kind() {
	case reflect.String:
		destStr = destValue.String()
	default:
		return "", errors.New("LinkTo operator needs a string argument")
	}

	var result string
	var err error

	switch destStr {
	case KIND_ACTIVITIES, KIND_MEMBERS, KIND_CONTACT, KIND_HOMEPAGE:
		// find uniq node
		nodes := builder.nodeBuilder(destStr).Nodes()
		if len(nodes) == 0 {
			err = errors.New("No node loaded yet")
		} else if len(nodes) > 1 {
			err = errors.New("That method logic is broken, fix it!")
		} else {
			result = nodes[0].Url
		}

	case KIND_POSTS, KIND_EVENTS:
		// find correct node
		nodes := builder.nodeBuilder(destStr).Nodes()

		for _, node := range nodes {
			if node.Kind == destStr {
				result = node.Url
				break
			}
		}

	default:
		// KIND_PAGE, KIND_POST
		err = errors.New("Internal link kind not supported yet")
	}

	return result, err
}

// Returns an URL to an internal page
func (builder *SiteBuilder) StartsWith(check interface{}, prefix interface{}) (bool, error) {
	checkValue := reflect.ValueOf(check)
	prefixValue := reflect.ValueOf(prefix)

	var checkStr string
	var prefixStr string

	switch checkValue.Kind() {
	case reflect.String:
		checkStr = checkValue.String()
	default:
		return false, errors.New("StartsWith operator needs string arguments")
	}

	switch prefixValue.Kind() {
	case reflect.String:
		prefixStr = prefixValue.String()
	default:
		return false, errors.New("StartsWith operator needs string arguments")
	}

	return strings.HasPrefix(checkStr, prefixStr), nil
}

// Borrowed from https://github.com/spf13/hugo/blob/master/tpl/template.go
func (builder *SiteBuilder) Mod(a, b interface{}) (int64, error) {
	av := reflect.ValueOf(a)
	bv := reflect.ValueOf(b)
	var ai, bi int64

	switch av.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		ai = av.Int()
	default:
		return 0, errors.New("Modulo operator can't be used with non integer value")
	}

	switch bv.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		bi = bv.Int()
	default:
		return 0, errors.New("Modulo operator can't be used with non integer value")
	}

	if bi == 0 {
		return 0, errors.New("The number can't be divided by zero at modulo operation")
	}

	return ai % bi, nil
}

// Borrowed from https://github.com/spf13/hugo/blob/master/tpl/template.go
func (builder *SiteBuilder) ModBool(a, b interface{}) (bool, error) {
	res, err := builder.Mod(a, b)
	if err != nil {
		return false, err
	}
	return res == int64(0), nil
}
<commit_msg>Allows target attr on anchors<commit_after>package builder

import (
	"errors"
	"html/template"
	"reflect"
	"strings"

	"github.com/microcosm-cc/bluemonday"
	"github.com/russross/blackfriday"

	"github.com/aymerick/kowa/models"
)

func generateHTML(inputFormat string, input string) template.HTML {
	var result template.HTML

	if inputFormat == models.FORMAT_MARKDOWN {
		html := blackfriday.MarkdownCommon([]byte(input))

		result = template.HTML(bluemonday.UGCPolicy().SanitizeBytes(html))
	} else {
		sanitizePolicy := bluemonday.UGCPolicy()
		sanitizePolicy.AllowAttrs("style").OnElements("p", "span", "div") // I know this is bad
		sanitizePolicy.AllowAttrs("target").OnElements("a")

		result = template.HTML(sanitizePolicy.Sanitize(input))
	}

	return result
}

//
// Func Map
//

// Build FuncMap for template
func (builder *SiteBuilder) FuncMap() template.FuncMap {
	return template.FuncMap{
		"urlFor":     builder.UrlFor,
		"startsWith": builder.StartsWith,
		"mod":        builder.Mod,
		"modBool":    builder.ModBool,
	}
}

// Returns an URL to an internal page
func (builder *SiteBuilder) UrlFor(dest interface{}) (string, error) {
	destValue := reflect.ValueOf(dest)

	var destStr string

	switch destValue.Kind() {
	case reflect.String:
		destStr = destValue.String()
	default:
		return "", errors.New("LinkTo operator needs a string argument")
	}

	var result string
	var err error

	switch destStr {
	case KIND_ACTIVITIES, KIND_MEMBERS, KIND_CONTACT, KIND_HOMEPAGE:
		// find uniq node
		nodes := builder.nodeBuilder(destStr).Nodes()
		if len(nodes) == 0 {
			err = errors.New("No node loaded yet")
		} else if len(nodes) > 1 {
			err = errors.New("That method logic is broken, fix it!")
		} else {
			result = nodes[0].Url
		}

	case KIND_POSTS, KIND_EVENTS:
		// find correct node
		nodes := builder.nodeBuilder(destStr).Nodes()

		for _, node := range nodes {
			if node.Kind == destStr {
				result = node.Url
				break
			}
		}

	default:
		// KIND_PAGE, KIND_POST
		err = errors.New("Internal link kind not supported yet")
	}

	return result, err
}

// Returns an URL to an internal page
func (builder *SiteBuilder) StartsWith(check interface{}, prefix interface{}) (bool, error) {
	checkValue := reflect.ValueOf(check)
	prefixValue := reflect.ValueOf(prefix)

	var checkStr string
	var prefixStr string

	switch checkValue.Kind() {
	case reflect.String:
		checkStr = checkValue.String()
	default:
		return false, errors.New("StartsWith operator needs string arguments")
	}

	switch prefixValue.Kind() {
	case reflect.String:
		prefixStr = prefixValue.String()
	default:
		return false, errors.New("StartsWith operator needs string arguments")
	}

	return strings.HasPrefix(checkStr, prefixStr), nil
}

// Borrowed from https://github.com/spf13/hugo/blob/master/tpl/template.go
func (builder *SiteBuilder) Mod(a, b interface{}) (int64, error) {
	av := reflect.ValueOf(a)
	bv := reflect.ValueOf(b)
	var ai, bi int64

	switch av.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		ai = av.Int()
	default:
		return 0, errors.New("Modulo operator can't be used with non integer value")
	}

	switch bv.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		bi = bv.Int()
	default:
		return 0, errors.New("Modulo operator can't be used with non integer value")
	}

	if bi == 0 {
		return 0, errors.New("The number can't be divided by zero at modulo operation")
	}

	return ai % bi, nil
}

// Borrowed from https://github.com/spf13/hugo/blob/master/tpl/template.go
func (builder *SiteBuilder) ModBool(a, b interface{}) (bool, error) {
	res, err := builder.Mod(a, b)
	if err != nil {
		return false, err
	}
	return res == int64(0), nil
}
<|endoftext|>


<commit_before>package buf

import (
	"io"

	"v2ray.com/core/common/errors"
)

// BufferToBytesWriter is a Writer that writes alloc.Buffer into underlying writer.
type BufferToBytesWriter struct {
	io.Writer
}

func NewBufferToBytesWriter(writer io.Writer) *BufferToBytesWriter {
	return &BufferToBytesWriter{
		Writer: writer,
	}
}

// WriteMultiBuffer implements Writer. This method takes ownership of the given buffer.
func (w *BufferToBytesWriter) WriteMultiBuffer(mb MultiBuffer) error {
	defer mb.Release()

	bs := mb.ToNetBuffers()
	_, err := bs.WriteTo(w)
	return err
}

// ReadFrom implements io.ReaderFrom.
func (w *BufferToBytesWriter) ReadFrom(reader io.Reader) (int64, error) {
	var sc SizeCounter
	err := Copy(NewReader(reader), w, CountSize(&sc))
	return sc.Size, err
}

// BufferedWriter is a Writer with internal buffer.
type BufferedWriter struct {
	writer   Writer
	buffer   *Buffer
	buffered bool
}

// NewBufferedWriter creates a new BufferedWriter.
func NewBufferedWriter(writer Writer) *BufferedWriter {
	return &BufferedWriter{
		writer:   writer,
		buffer:   New(),
		buffered: true,
	}
}

func (w *BufferedWriter) WriteByte(c byte) error {
	_, err := w.Write([]byte{c})
	return err
}

// Write implements io.Writer.
func (w *BufferedWriter) Write(b []byte) (int, error) {
	if !w.buffered {
		if writer, ok := w.writer.(io.Writer); ok {
			return writer.Write(b)
		}
	}

	totalBytes := 0
	for len(b) > 0 {
		if w.buffer == nil {
			w.buffer = New()
		}

		nBytes, err := w.buffer.Write(b)
		totalBytes += nBytes
		if err != nil {
			return totalBytes, err
		}
		if !w.buffered || w.buffer.IsFull() {
			if err := w.Flush(); err != nil {
				return totalBytes, err
			}
		}
		b = b[nBytes:]
	}

	return totalBytes, nil
}

// WriteMultiBuffer implements Writer. It takes ownership of the given MultiBuffer.
func (w *BufferedWriter) WriteMultiBuffer(b MultiBuffer) error {
	if !w.buffered {
		return w.writer.WriteMultiBuffer(b)
	}

	defer b.Release()

	for !b.IsEmpty() {
		if err := w.buffer.AppendSupplier(ReadFrom(&b)); err != nil {
			return err
		}
		if w.buffer.IsFull() {
			if err := w.Flush(); err != nil {
				return err
			}
		}
	}

	return nil
}

// Flush flushes buffered content into underlying writer.
func (w *BufferedWriter) Flush() error {
	if !w.buffer.IsEmpty() {
		if err := w.writer.WriteMultiBuffer(NewMultiBufferValue(w.buffer)); err != nil {
			return err
		}

		if w.buffered {
			w.buffer = New()
		} else {
			w.buffer = nil
		}
	}
	return nil
}

func (w *BufferedWriter) SetBuffered(f bool) error {
	w.buffered = f
	if !f {
		return w.Flush()
	}
	return nil
}

// ReadFrom implements io.ReaderFrom.
func (w *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) {
	if err := w.SetBuffered(false); err != nil {
		return 0, err
	}

	var sc SizeCounter
	err := Copy(NewReader(reader), w, CountSize(&sc))
	return sc.Size, err
}

type seqWriter struct {
	writer io.Writer
}

func (w *seqWriter) WriteMultiBuffer(mb MultiBuffer) error {
	defer mb.Release()

	for _, b := range mb {
		if b.IsEmpty() {
			continue
		}
		if _, err := w.writer.Write(b.Bytes()); err != nil {
			return err
		}
	}

	return nil
}

type noOpWriter byte

func (noOpWriter) WriteMultiBuffer(b MultiBuffer) error {
	b.Release()
	return nil
}

func (noOpWriter) Write(b []byte) (int, error) {
	return len(b), nil
}

func (noOpWriter) ReadFrom(reader io.Reader) (int64, error) {
	b := New()
	defer b.Release()

	totalBytes := int64(0)
	for {
		err := b.Reset(ReadFrom(reader))
		totalBytes += int64(b.Len())
		if err != nil {
			if errors.Cause(err) == io.EOF {
				return totalBytes, nil
			}
			return totalBytes, err
		}
	}
}

var (
	// Discard is a Writer that swallows all contents written in.
	Discard Writer = noOpWriter(0)

	// DiscardBytes is an io.Writer that swallows all contents written in.
	DiscardBytes io.Writer = noOpWriter(0)
)
<commit_msg>fix a buffer leak in buffered reader<commit_after>package buf

import (
	"io"

	"v2ray.com/core/common/errors"
)

// BufferToBytesWriter is a Writer that writes alloc.Buffer into underlying writer.
type BufferToBytesWriter struct {
	io.Writer
}

func NewBufferToBytesWriter(writer io.Writer) *BufferToBytesWriter {
	return &BufferToBytesWriter{
		Writer: writer,
	}
}

// WriteMultiBuffer implements Writer. This method takes ownership of the given buffer.
func (w *BufferToBytesWriter) WriteMultiBuffer(mb MultiBuffer) error {
	defer mb.Release()

	bs := mb.ToNetBuffers()
	_, err := bs.WriteTo(w)
	return err
}

// ReadFrom implements io.ReaderFrom.
func (w *BufferToBytesWriter) ReadFrom(reader io.Reader) (int64, error) {
	var sc SizeCounter
	err := Copy(NewReader(reader), w, CountSize(&sc))
	return sc.Size, err
}

// BufferedWriter is a Writer with internal buffer.
type BufferedWriter struct {
	writer   Writer
	buffer   *Buffer
	buffered bool
}

// NewBufferedWriter creates a new BufferedWriter.
func NewBufferedWriter(writer Writer) *BufferedWriter {
	return &BufferedWriter{
		writer:   writer,
		buffer:   New(),
		buffered: true,
	}
}

func (w *BufferedWriter) WriteByte(c byte) error {
	_, err := w.Write([]byte{c})
	return err
}

// Write implements io.Writer.
func (w *BufferedWriter) Write(b []byte) (int, error) {
	if !w.buffered {
		if writer, ok := w.writer.(io.Writer); ok {
			return writer.Write(b)
		}
	}

	totalBytes := 0
	for len(b) > 0 {
		if w.buffer == nil {
			w.buffer = New()
		}

		nBytes, err := w.buffer.Write(b)
		totalBytes += nBytes
		if err != nil {
			return totalBytes, err
		}
		if !w.buffered || w.buffer.IsFull() {
			if err := w.Flush(); err != nil {
				return totalBytes, err
			}
		}
		b = b[nBytes:]
	}

	return totalBytes, nil
}

// WriteMultiBuffer implements Writer. It takes ownership of the given MultiBuffer.
func (w *BufferedWriter) WriteMultiBuffer(b MultiBuffer) error {
	if !w.buffered {
		return w.writer.WriteMultiBuffer(b)
	}

	defer b.Release()

	for !b.IsEmpty() {
		if w.buffer == nil {
			w.buffer = New()
		}
		if err := w.buffer.AppendSupplier(ReadFrom(&b)); err != nil {
			return err
		}
		if w.buffer.IsFull() {
			if err := w.Flush(); err != nil {
				return err
			}
		}
	}

	return nil
}

// Flush flushes buffered content into underlying writer.
func (w *BufferedWriter) Flush() error {
	if !w.buffer.IsEmpty() {
		if err := w.writer.WriteMultiBuffer(NewMultiBufferValue(w.buffer)); err != nil {
			return err
		}

		w.buffer = nil
	}
	return nil
}

func (w *BufferedWriter) SetBuffered(f bool) error {
	w.buffered = f
	if !f {
		return w.Flush()
	}
	return nil
}

// ReadFrom implements io.ReaderFrom.
func (w *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) {
	if err := w.SetBuffered(false); err != nil {
		return 0, err
	}

	var sc SizeCounter
	err := Copy(NewReader(reader), w, CountSize(&sc))
	return sc.Size, err
}

type seqWriter struct {
	writer io.Writer
}

func (w *seqWriter) WriteMultiBuffer(mb MultiBuffer) error {
	defer mb.Release()

	for _, b := range mb {
		if b.IsEmpty() {
			continue
		}
		if _, err := w.writer.Write(b.Bytes()); err != nil {
			return err
		}
	}

	return nil
}

type noOpWriter byte

func (noOpWriter) WriteMultiBuffer(b MultiBuffer) error {
	b.Release()
	return nil
}

func (noOpWriter) Write(b []byte) (int, error) {
	return len(b), nil
}

func (noOpWriter) ReadFrom(reader io.Reader) (int64, error) {
	b := New()
	defer b.Release()

	totalBytes := int64(0)
	for {
		err := b.Reset(ReadFrom(reader))
		totalBytes += int64(b.Len())
		if err != nil {
			if errors.Cause(err) == io.EOF {
				return totalBytes, nil
			}
			return totalBytes, err
		}
	}
}

var (
	// Discard is a Writer that swallows all contents written in.
	Discard Writer = noOpWriter(0)

	// DiscardBytes is an io.Writer that swallows all contents written in.
	DiscardBytes io.Writer = noOpWriter(0)
)
<|endoftext|>