<commit_before>package bing

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"strings"
)

var (
	apiKey = ""
)

type BingWebSearchResult struct {
	Type            string           `json:"_type,omitempty"`
	WebPages        *WebPages        `json:"webPages,omitempty"`
	Images          *Images          `json:"images,omitempty"`
	News            *News            `json:"news,omitempty"`
	Videos          *Videos          `json:"videos,omitempty"`
	RankingResponse *RankingResponse `json:"rankingResponse,omitempty"`
	Sidebar         *Sidebar         `json:"sidebar,omitempty"`
}

type BingNewsSearchResult struct {
	Type                  string        `json:"_type"`
	ReadLink              string        `json:"readLink"`
	TotalEstimatedMatches int64         `json:"totalEstimatedMatches"`
	Sort                  []*SortType   `json:"sort"`
	Value                 []*NewsResult `json:"value"`
}

type SortType struct {
	Name       string `json:"name"`
	ID         string `json:"id"`
	IsSelected bool   `json:"isSelected"`
	URL        string `json:"url"`
}

type WebPages struct {
	WebSearchURL          string     `json:"webSearchUrl,omitempty"`
	TotalEstimatedMatches int64      `json:"totalEstimatedMatches,omitempty"`
	Value                 []*WebPage `json:"value,omitempty"`
}

// WebPage is a value in the webpages section of the bing response
type WebPage struct {
	ID              string   `json:"id,omitempty"`
	Name            string   `json:"name,omitempty"`
	URL             string   `json:"url,omitempty"`
	About           []*About `json:"about,omitempty"`
	DisplayURL      string   `json:"displayUrl,omitempty"`
	Snippet         string   `json:"snippet,omitempty"`
	DateLastCrawled string   `json:"dateLastCrawled,omitempty"`
}

// About is the about section of the result
type About struct {
	Name string `json:"name,omitempty"`
}

type Images struct {
	ID                           string   `json:"id,omitempty"`
	ReadLink                     string   `json:"readLink,omitempty"`
	WebSearchURL                 string   `json:"webSearchUrl,omitempty"`
	IsFamilyFriendly             bool     `json:"isFamilyFriendly,omitempty"`
	Value                        []*Image `json:"value, omitempty"`
	DisplayShoppingSourcesBadges bool     `json:"displayShoppingSourcesBadges,omitempty"`
	DisplayRecipeSourcesBadges   bool     `json:"displayRecipeSourcesBadges,omitempty"`
}

type Image struct {
	Name               string     `json:"name,omitempty"`
	WebSearchURL       string     `json:"webSearchUrl,omitempty"`
	ThumbnailURL       string     `json:"thumbnailUrl,omitempty"`
	DatePublished      string     `json:"datePublished,omitempty"`
	ContentURL         string     `json:"contentUrl,omitempty"`
	HostPageURL        string     `json:"hostPageUrl,omitempty"`
	ContentSize        string     `json:"contentSize,omitempty"`
	EncodingFormat     string     `json:"encodingFormat,omitempty"`
	HostPageDisplayURL string     `json:"hostPageDisplayUrl,omitempty"`
	Width              int64      `json:"width,omitempty"`
	Height             int64      `json:"height,omitempty"`
	Thumbnail          *Thumbnail `json:"thumbnail,omitempty"`
}

type Thumbnail struct {
	Width      int64  `json:"width,omitempty"`
	Height     int64  `json:"height,omitempty"`
	ContentURL string `json:"contentUrl,omitempty"`
}

// News results from bing search
type News struct {
	ID       string        `json:"id,omitempty"`
	ReadLink string        `json:"readLink,omitempty"`
	Value    []*NewsResult `json:"value,omitempty"`
}

type NewsResult struct {
	Name          string     `json:"name,omitempty"`
	URL           string     `json:"url,omitempty"`
	Image         *NewsImage `json:"image,omitempty"`
	Description   string     `json:"description,omitempty"`
	About         *AboutNews `json:"about,omitempty"`
	Provider      *Provider  `json:"provider,omitempty"`
	DatePublished string     `json:"datePublished,omitempty"`
	Category      string     `json:"category,omitempty"`
}

type NewsImage struct {
	ContentUrl string     `json:"contentUrl,omitempty"`
	Thumbnail  *Thumbnail `json:"thumbnail,omitempty"`
}

type AboutNews struct {
	Name     string `json:"name,omitempty"`
	ReadLink string `json:"readLink,omitempty"`
}

type Provider struct {
	Type string `json:"_type,omitempty"`
	Name string `json:"name,omitempty"`
}

type Videos struct {
	ID               string   `json:"id,omitempty"`
	ReadLink         string   `json:"readLink,omitempty"`
	WebSearchURL     string   `json:"webSearchUrl,omitempty"`
	IsFamilyFriendly bool     `json:"isFamilyFriendly,omitempty"`
	Value            []*Video `json:"value,omitempty"`
}

type Video struct {
	Name               string     `json:"name,omitempty"`
	Description        string     `json:"description,omitempty"`
	WebSearchURL       string     `json:"webSearchUrl,omitempty"`
	ThumbnailURL       string     `json:"thumbnailUrl,omitempty"`
	DatePublished      string     `json:"datePublished,omitempty"`
	Publisher          *Publisher `json:"publisher,omitempty"`
	ContentURL         string     `json:"contentUrl,omitempty"`
	HostPageURL        string     `json:"hostPageUrl,omitempty"`
	EncodingFormat     string     `json:"encodingFormat,omitempty"`
	HostPageDisplayURL string     `json:"hostPageDisplayUrl,omitempty"`
	Width              int64      `json:"width,omitempty"`
	Height             int64      `json:"height,omitempty"`
	Duration           string     `json:"duration,omitempty"`
	MotionThumbnailURL string     `json:"motionThumbnailUrl,omitempty"`
	EmbedHTML          string     `json:"embedHtml,omitempty"`
	AllowHTTPSEmbed    bool       `json:"allowHttpsEmbed,omitempty"`
	ViewCount          int64      `json:"viewCount,omitempty"`
	Thumbnail          *Thumbnail `json:"thumbnail,omitempty"`
	AllowMobileEmbed   bool       `json:"allowMobileEmbed,omitempty"`
	IsSuperfresh       bool       `json:"isSuperfresh,omitempty"`
}

type Publisher struct {
	Name string `json:"publisher,omitempty"`
}

type RankingResponse struct {
	Mainline []*Item `json:"mainline,omitempty"`
}

type Item struct {
	AnswerType  string `json:"answerType,omitempty"`
	ResultIndex int64  `json:"resultIndex,omitempty"`
	Value       *Value `json:"value,omitempty"`
}

type Value struct {
	ID string `json:"id,omitempty"`
}

type Sidebar struct {
	Items []*SidebarItem `json:"items,omitempty"`
}

type SidebarItem struct {
	AnswerType string `json:"answerType,omitempty"`
	Value      *Value `json:"value,omitempty"`
}

func (bingSearchResult *BingWebSearchResult) MakeBingRequest(query string, resultCount string, offset int) error {
	client := &http.Client{}
	newQuery := strings.Replace(query, " ", "+", -1)
	reqURL := "https://api.cognitive.microsoft.com/bing/v5.0/search?q=" + newQuery + "&offset=" + strconv.Itoa(offset) + "&count=" + resultCount + "&mkt=en-us"

	req, err := http.NewRequest("GET", reqURL, nil)
	req.Header.Set("Ocp-Apim-Subscription-Key", apiKey)
	resp, err := client.Do(req)
	if err != nil {
		log.Println("Error: " + err.Error())
		return err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	json.Unmarshal(body, &bingSearchResult)

	return nil
}

func (bingSearchResult *BingNewsSearchResult) MakeBingRequest(query string, resultCount string, offset int) error {
	client := &http.Client{}
	newQuery := strings.Replace(query, " ", "+", -1)
	reqURL := "https://api.cognitive.microsoft.com/bing/v5.0/news/search?q=" +
		newQuery + "&offset=" + strconv.Itoa(offset) + "&count=" + resultCount + "&freshness=Month&mkt=en-us"

	req, err := http.NewRequest("GET", reqURL, nil)
	req.Header.Set("Ocp-Apim-Subscription-Key", apiKey)
	resp, err := client.Do(req)
	if err != nil {
		log.Println("Error: " + err.Error())
		return err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	json.Unmarshal(body, &bingSearchResult)

	return nil
}

// GetSiteURLFromBingURL takes the url for each result bing gives (which has a bunch of junk in it)
// and gets the legit permanent url from it.
func GetSiteURLFromBingURL(url string) string {
	return strings.Split(strings.Split(url, "r=")[1], "&")[0]
}
<commit_msg>export ApiKey.<commit_after>package bing

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"strings"
)

var (
	ApiKey = ""
)

type BingWebSearchResult struct {
	Type            string           `json:"_type,omitempty"`
	WebPages        *WebPages        `json:"webPages,omitempty"`
	Images          *Images          `json:"images,omitempty"`
	News            *News            `json:"news,omitempty"`
	Videos          *Videos          `json:"videos,omitempty"`
	RankingResponse *RankingResponse `json:"rankingResponse,omitempty"`
	Sidebar         *Sidebar         `json:"sidebar,omitempty"`
}

type BingNewsSearchResult struct {
	Type                  string        `json:"_type"`
	ReadLink              string        `json:"readLink"`
	TotalEstimatedMatches int64         `json:"totalEstimatedMatches"`
	Sort                  []*SortType   `json:"sort"`
	Value                 []*NewsResult `json:"value"`
}

type SortType struct {
	Name       string `json:"name"`
	ID         string `json:"id"`
	IsSelected bool   `json:"isSelected"`
	URL        string `json:"url"`
}

type WebPages struct {
	WebSearchURL          string     `json:"webSearchUrl,omitempty"`
	TotalEstimatedMatches int64      `json:"totalEstimatedMatches,omitempty"`
	Value                 []*WebPage `json:"value,omitempty"`
}

// WebPage is a value in the webpages section of the bing response
type WebPage struct {
	ID              string   `json:"id,omitempty"`
	Name            string   `json:"name,omitempty"`
	URL             string   `json:"url,omitempty"`
	About           []*About `json:"about,omitempty"`
	DisplayURL      string   `json:"displayUrl,omitempty"`
	Snippet         string   `json:"snippet,omitempty"`
	DateLastCrawled string   `json:"dateLastCrawled,omitempty"`
}

// About is the about section of the result
type About struct {
	Name string `json:"name,omitempty"`
}

type Images struct {
	ID                           string   `json:"id,omitempty"`
	ReadLink                     string   `json:"readLink,omitempty"`
	WebSearchURL                 string   `json:"webSearchUrl,omitempty"`
	IsFamilyFriendly             bool     `json:"isFamilyFriendly,omitempty"`
	Value                        []*Image `json:"value, omitempty"`
	DisplayShoppingSourcesBadges bool     `json:"displayShoppingSourcesBadges,omitempty"`
	DisplayRecipeSourcesBadges   bool     `json:"displayRecipeSourcesBadges,omitempty"`
}

type Image struct {
	Name               string     `json:"name,omitempty"`
	WebSearchURL       string     `json:"webSearchUrl,omitempty"`
	ThumbnailURL       string     `json:"thumbnailUrl,omitempty"`
	DatePublished      string     `json:"datePublished,omitempty"`
	ContentURL         string     `json:"contentUrl,omitempty"`
	HostPageURL        string     `json:"hostPageUrl,omitempty"`
	ContentSize        string     `json:"contentSize,omitempty"`
	EncodingFormat     string     `json:"encodingFormat,omitempty"`
	HostPageDisplayURL string     `json:"hostPageDisplayUrl,omitempty"`
	Width              int64      `json:"width,omitempty"`
	Height             int64      `json:"height,omitempty"`
	Thumbnail          *Thumbnail `json:"thumbnail,omitempty"`
}

type Thumbnail struct {
	Width      int64  `json:"width,omitempty"`
	Height     int64  `json:"height,omitempty"`
	ContentURL string `json:"contentUrl,omitempty"`
}

// News results from bing search
type News struct {
	ID       string        `json:"id,omitempty"`
	ReadLink string        `json:"readLink,omitempty"`
	Value    []*NewsResult `json:"value,omitempty"`
}

type NewsResult struct {
	Name          string     `json:"name,omitempty"`
	URL           string     `json:"url,omitempty"`
	Image         *NewsImage `json:"image,omitempty"`
	Description   string     `json:"description,omitempty"`
	About         *AboutNews `json:"about,omitempty"`
	Provider      *Provider  `json:"provider,omitempty"`
	DatePublished string     `json:"datePublished,omitempty"`
	Category      string     `json:"category,omitempty"`
}

type NewsImage struct {
	ContentUrl string     `json:"contentUrl,omitempty"`
	Thumbnail  *Thumbnail `json:"thumbnail,omitempty"`
}

type AboutNews struct {
	Name     string `json:"name,omitempty"`
	ReadLink string `json:"readLink,omitempty"`
}

type Provider struct {
	Type string `json:"_type,omitempty"`
	Name string `json:"name,omitempty"`
}

type Videos struct {
	ID               string   `json:"id,omitempty"`
	ReadLink         string   `json:"readLink,omitempty"`
	WebSearchURL     string   `json:"webSearchUrl,omitempty"`
	IsFamilyFriendly bool     `json:"isFamilyFriendly,omitempty"`
	Value            []*Video `json:"value,omitempty"`
}

type Video struct {
	Name               string     `json:"name,omitempty"`
	Description        string     `json:"description,omitempty"`
	WebSearchURL       string     `json:"webSearchUrl,omitempty"`
	ThumbnailURL       string     `json:"thumbnailUrl,omitempty"`
	DatePublished      string     `json:"datePublished,omitempty"`
	Publisher          *Publisher `json:"publisher,omitempty"`
	ContentURL         string     `json:"contentUrl,omitempty"`
	HostPageURL        string     `json:"hostPageUrl,omitempty"`
	EncodingFormat     string     `json:"encodingFormat,omitempty"`
	HostPageDisplayURL string     `json:"hostPageDisplayUrl,omitempty"`
	Width              int64      `json:"width,omitempty"`
	Height             int64      `json:"height,omitempty"`
	Duration           string     `json:"duration,omitempty"`
	MotionThumbnailURL string     `json:"motionThumbnailUrl,omitempty"`
	EmbedHTML          string     `json:"embedHtml,omitempty"`
	AllowHTTPSEmbed    bool       `json:"allowHttpsEmbed,omitempty"`
	ViewCount          int64      `json:"viewCount,omitempty"`
	Thumbnail          *Thumbnail `json:"thumbnail,omitempty"`
	AllowMobileEmbed   bool       `json:"allowMobileEmbed,omitempty"`
	IsSuperfresh       bool       `json:"isSuperfresh,omitempty"`
}

type Publisher struct {
	Name string `json:"publisher,omitempty"`
}

type RankingResponse struct {
	Mainline []*Item `json:"mainline,omitempty"`
}

type Item struct {
	AnswerType  string `json:"answerType,omitempty"`
	ResultIndex int64  `json:"resultIndex,omitempty"`
	Value       *Value `json:"value,omitempty"`
}

type Value struct {
	ID string `json:"id,omitempty"`
}

type Sidebar struct {
	Items []*SidebarItem `json:"items,omitempty"`
}

type SidebarItem struct {
	AnswerType string `json:"answerType,omitempty"`
	Value      *Value `json:"value,omitempty"`
}

func (bingSearchResult *BingWebSearchResult) MakeBingRequest(query string, resultCount string, offset int) error {
	client := &http.Client{}
	newQuery := strings.Replace(query, " ", "+", -1)
	reqURL := "https://api.cognitive.microsoft.com/bing/v5.0/search?q=" + newQuery + "&offset=" + strconv.Itoa(offset) + "&count=" + resultCount + "&mkt=en-us"

	req, err := http.NewRequest("GET", reqURL, nil)
	req.Header.Set("Ocp-Apim-Subscription-Key", ApiKey)
	resp, err := client.Do(req)
	if err != nil {
		log.Println("Error: " + err.Error())
		return err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	json.Unmarshal(body, &bingSearchResult)

	return nil
}

func (bingSearchResult *BingNewsSearchResult) MakeBingRequest(query string, resultCount string, offset int) error {
	client := &http.Client{}
	newQuery := strings.Replace(query, " ", "+", -1)
	reqURL := "https://api.cognitive.microsoft.com/bing/v5.0/news/search?q=" +
		newQuery + "&offset=" + strconv.Itoa(offset) + "&count=" + resultCount + "&freshness=Month&mkt=en-us"

	req, err := http.NewRequest("GET", reqURL, nil)
	req.Header.Set("Ocp-Apim-Subscription-Key", ApiKey)
	resp, err := client.Do(req)
	if err != nil {
		log.Println("Error: " + err.Error())
		return err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	json.Unmarshal(body, &bingSearchResult)

	return nil
}

// GetSiteURLFromBingURL takes the url for each result bing gives (which has a bunch of junk in it)
// and gets the legit permanent url from it.
func GetSiteURLFromBingURL(url string) string {
	return strings.Split(strings.Split(url, "r=")[1], "&")[0]
}
<|endoftext|>


<commit_before>// Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
//
// 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 main

import (
	"encoding/json"
	"fmt"
	"log"
	"log/syslog"
	"net"
	"os"

	"github.com/osrg/gobgp/packet"
)

const (
	DEFAULT_BMPD_HOST = "0.0.0.0"
	DEFAULT_BMPD_PORT = "11019"
)

func processBMPClinet(conn net.Conn) {
	tcpConn := conn.(*net.TCPConn)
	defer tcpConn.Close()

	for {
		msg, err := bgp.ReadBMPMessage(tcpConn)
		if err != nil {
			fmt.Println(err)
			log.Println("BMP client disconnected", conn.RemoteAddr())
			break
		}
		j, _ := json.Marshal(msg)
		log.Println(string(j))
	}
}

func main() {
	logwriter, err := syslog.New(syslog.LOG_INFO, "bmpd")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	log.SetOutput(logwriter)

	serverHost := os.Getenv("BMPD_HOST")
	if serverHost == "" {
		serverHost = DEFAULT_BMP_SERVER_HOST
	}

	serverPort := os.Getenv("BMPD_PORT")
	if serverPort == "" {
		serverPort = DEFAULT_BMP_SERVER_PORT
	}

	listener, err := net.Listen("tcp", serverHost+":"+serverPort)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	log.Println("listening on", serverHost+":"+serverPort)

	for {
		conn, err := listener.Accept()
		log.Println("BMP client connected", conn.RemoteAddr())
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			continue
		}
		go processBMPClinet(conn)
	}
}
<commit_msg>bmpd: fix typos<commit_after>// Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
//
// 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 main

import (
	"encoding/json"
	"fmt"
	"log"
	"log/syslog"
	"net"
	"os"

	"github.com/osrg/gobgp/packet"
)

const (
	DEFAULT_BMPD_HOST = "0.0.0.0"
	DEFAULT_BMPD_PORT = "11019"
)

func processBMPClinet(conn net.Conn) {
	tcpConn := conn.(*net.TCPConn)
	defer tcpConn.Close()

	for {
		msg, err := bgp.ReadBMPMessage(tcpConn)
		if err != nil {
			fmt.Println(err)
			log.Println("BMP client disconnected", conn.RemoteAddr())
			break
		}
		j, _ := json.Marshal(msg)
		log.Println(string(j))
	}
}

func main() {
	logwriter, err := syslog.New(syslog.LOG_INFO, "bmpd")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	log.SetOutput(logwriter)

	serverHost := os.Getenv("BMPD_HOST")
	if serverHost == "" {
		serverHost = DEFAULT_BMPD_HOST
	}

	serverPort := os.Getenv("BMPD_PORT")
	if serverPort == "" {
		serverPort = DEFAULT_BMPD_PORT
	}

	listener, err := net.Listen("tcp", serverHost+":"+serverPort)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	log.Println("listening on", serverHost+":"+serverPort)

	for {
		conn, err := listener.Accept()
		log.Println("BMP client connected", conn.RemoteAddr())
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			continue
		}
		go processBMPClinet(conn)
	}
}
<|endoftext|>


<commit_before>// Copyright 2011, 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package environs

import (
	"errors"
	"io"
	"launchpad.net/juju-core/constraints"
	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/instance"
	"launchpad.net/juju-core/state"
	"launchpad.net/juju-core/state/api"
)

// A EnvironProvider represents a computing and storage provider.
type EnvironProvider interface {
	// Open opens the environment and returns it.
	Open(cfg *config.Config) (Environ, error)

	// Validate ensures that config is a valid configuration for this
	// provider, applying changes to it if necessary, and returns the
	// validated configuration.
	// If old is not nil, it holds the previous environment configuration
	// for consideration when validating changes.
	Validate(cfg, old *config.Config) (valid *config.Config, err error)

	// Boilerplate returns a default configuration for the environment in yaml format.
	// The text should be a key followed by some number of attributes:
	//    `environName:
	//        type: environTypeName
	//        attr1: val1
	//    `
	// The text is used as a template (see the template package) with one extra template
	// function available, rand, which expands to a random hexadecimal string when invoked.
	BoilerplateConfig() string

	// SecretAttrs filters the supplied configuration returning only values
	// which are considered sensitive.
	SecretAttrs(cfg *config.Config) (map[string]interface{}, error)

	// PublicAddress returns this machine's public host name.
	PublicAddress() (string, error)

	// PrivateAddress returns this machine's private host name.
	PrivateAddress() (string, error)

	// InstanceId returns this machine's instance id.
	InstanceId() (instance.Id, error)
}

var ErrNoInstances = errors.New("no instances found")
var ErrPartialInstances = errors.New("only some instances were found")

// A StorageReader can retrieve and list files from a storage provider.
type StorageReader interface {
	// Get opens the given storage file and returns a ReadCloser
	// that can be used to read its contents.  It is the caller's
	// responsibility to close it after use.  If the name does not
	// exist, it should return a *NotFoundError.
	Get(name string) (io.ReadCloser, error)

	// List lists all names in the storage with the given prefix, in
	// alphabetical order.  The names in the storage are considered
	// to be in a flat namespace, so the prefix may include slashes
	// and the names returned are the full names for the matching
	// entries.
	List(prefix string) ([]string, error)

	// URL returns a URL that can be used to access the given storage file.
	URL(name string) (string, error)
}

// A StorageWriter adds and removes files in a storage provider.
type StorageWriter interface {
	// Put reads from r and writes to the given storage file.
	// The length must give the total length of the file.
	Put(name string, r io.Reader, length int64) error

	// Remove removes the given file from the environment's
	// storage. It should not return an error if the file does
	// not exist.
	Remove(name string) error

	// RemoveAll deletes all files that have been stored here.
	// If the underlying storage implementation may be shared
	// with other actors, it must be sure not to delete their
	// file as well.
	// Nevertheless, use with care!  This method is only mean
	// for cleaning up an environment that's being destroyed.
	RemoveAll() error
}

// Storage represents storage that can be both
// read and written.
type Storage interface {
	StorageReader
	StorageWriter
}

// An Environ represents a juju environment as specified
// in the environments.yaml file.
//
// Due to the limitations of some providers (for example ec2), the
// results of the Environ methods may not be fully sequentially
// consistent. In particular, while a provider may retry when it
// gets an error for an operation, it will not retry when
// an operation succeeds, even if that success is not
// consistent with a previous operation.
//
// Even though Juju takes care not to share an Environ between concurrent
// workers, it does allow concurrent method calls into the provider
// implementation.  The typical provider implementation needs locking to
// avoid undefined behaviour when the configuration changes.
type Environ interface {
	// Name returns the Environ's name.
	Name() string

	// Bootstrap initializes the state for the ehttp://e.linkedin.com/pub/cc?_ri_=X0Gzc2X%3DWQpglLjHJlYQGnWM9Wmzczb5jcumzdzbUza0krpJ1IHy1zbKM6oudBVXtpKX%3DSACTCD&_ei_=ElhY7pRVQKMkByKfU5j5nyTdqpv_9wz7Jge06DvYsd6c0nIJozNk4cNMOPC1Urjg7VaJ00kOxaaDHWP4Pi6FQTEX7HtnX6dCCY5_xSJOUbu4ajHGueKYqV91dfEPm_weAS30DdZlQpvjwJZconUle6z6-oOidmOLrLjX70.nvironment, possibly
	// starting one or more instances.  If the configuration's
	// AdminSecret is non-empty, the adminstrator password on the
	// newly bootstrapped state will be set to a hash of it (see
	// utils.PasswordHash), When first connecting to the
	// environment via the juju package, the password hash will be
	// automatically replaced by the real password.
	//
	// The supplied constraints are used to choose the initial instance
	// specification, and will be stored in the new environment's state.
	Bootstrap(cons constraints.Value) error

	// StateInfo returns information on the state initialized
	// by Bootstrap.
	StateInfo() (*state.Info, *api.Info, error)

	// Config returns the current configuration of this Environ.
	Config() *config.Config

	// SetConfig updates the Environ's configuration.
	//
	// Calls to SetConfig do not affect the configuration of
	// values previously obtained from Storage and PublicStorage.
	SetConfig(cfg *config.Config) error

	// StartInstance asks for a new instance to be created, associated
	// with the provided machine identifier. The given info describes
	// the juju state for the new instance to connect to. The nonce,
	// which must be unique within an environment, is used by juju to
	// protect against the consequences of multiple instances being
	// started with the same machine id.
	StartInstance(machineId, machineNonce string, series string, cons constraints.Value,
		info *state.Info, apiInfo *api.Info) (instance.Instance, *instance.HardwareCharacteristics, error)

	// StopInstances shuts down the given instances.
	StopInstances([]instance.Instance) error

	// Instances returns a slice of instances corresponding to the
	// given instance ids.  If no instances were found, but there
	// was no other error, it will return ErrNoInstances.  If
	// some but not all the instances were found, the returned slice
	// will have some nil slots, and an ErrPartialInstances error
	// will be returned.
	Instances(ids []instance.Id) ([]instance.Instance, error)

	// AllInstances returns all instances currently known to the
	// environment.
	AllInstances() ([]instance.Instance, error)

	// Storage returns storage specific to the environment.
	Storage() Storage

	// PublicStorage returns storage shared between environments.
	PublicStorage() StorageReader

	// Destroy shuts down all known machines and destroys the
	// rest of the environment. A list of instances known to
	// be part of the environment can be given with insts.
	// This is because recently started machines might not
	// yet be visible in the environment, so this method
	// can wait until they are.
	//
	// When Destroy has been called, any Environ referring to the
	// same remote environment may become invalid
	Destroy(insts []instance.Instance) error

	// OpenPorts opens the given ports for the whole environment.
	// Must only be used if the environment was setup with the
	// FwGlobal firewall mode.
	OpenPorts(ports []instance.Port) error

	// ClosePorts closes the given ports for the whole environment.
	// Must only be used if the environment was setup with the
	// FwGlobal firewall mode.
	ClosePorts(ports []instance.Port) error

	// Ports returns the ports opened for the whole environment.
	// Must only be used if the environment was setup with the
	// FwGlobal firewall mode.
	Ports() ([]instance.Port, error)

	// Provider returns the EnvironProvider that created this Environ.
	Provider() EnvironProvider
}
<commit_msg>Removed rogue paste, thanks fwereade...<commit_after>// Copyright 2011, 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package environs

import (
	"errors"
	"io"
	"launchpad.net/juju-core/constraints"
	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/instance"
	"launchpad.net/juju-core/state"
	"launchpad.net/juju-core/state/api"
)

// A EnvironProvider represents a computing and storage provider.
type EnvironProvider interface {
	// Open opens the environment and returns it.
	Open(cfg *config.Config) (Environ, error)

	// Validate ensures that config is a valid configuration for this
	// provider, applying changes to it if necessary, and returns the
	// validated configuration.
	// If old is not nil, it holds the previous environment configuration
	// for consideration when validating changes.
	Validate(cfg, old *config.Config) (valid *config.Config, err error)

	// Boilerplate returns a default configuration for the environment in yaml format.
	// The text should be a key followed by some number of attributes:
	//    `environName:
	//        type: environTypeName
	//        attr1: val1
	//    `
	// The text is used as a template (see the template package) with one extra template
	// function available, rand, which expands to a random hexadecimal string when invoked.
	BoilerplateConfig() string

	// SecretAttrs filters the supplied configuration returning only values
	// which are considered sensitive.
	SecretAttrs(cfg *config.Config) (map[string]interface{}, error)

	// PublicAddress returns this machine's public host name.
	PublicAddress() (string, error)

	// PrivateAddress returns this machine's private host name.
	PrivateAddress() (string, error)

	// InstanceId returns this machine's instance id.
	InstanceId() (instance.Id, error)
}

var ErrNoInstances = errors.New("no instances found")
var ErrPartialInstances = errors.New("only some instances were found")

// A StorageReader can retrieve and list files from a storage provider.
type StorageReader interface {
	// Get opens the given storage file and returns a ReadCloser
	// that can be used to read its contents.  It is the caller's
	// responsibility to close it after use.  If the name does not
	// exist, it should return a *NotFoundError.
	Get(name string) (io.ReadCloser, error)

	// List lists all names in the storage with the given prefix, in
	// alphabetical order.  The names in the storage are considered
	// to be in a flat namespace, so the prefix may include slashes
	// and the names returned are the full names for the matching
	// entries.
	List(prefix string) ([]string, error)

	// URL returns a URL that can be used to access the given storage file.
	URL(name string) (string, error)
}

// A StorageWriter adds and removes files in a storage provider.
type StorageWriter interface {
	// Put reads from r and writes to the given storage file.
	// The length must give the total length of the file.
	Put(name string, r io.Reader, length int64) error

	// Remove removes the given file from the environment's
	// storage. It should not return an error if the file does
	// not exist.
	Remove(name string) error

	// RemoveAll deletes all files that have been stored here.
	// If the underlying storage implementation may be shared
	// with other actors, it must be sure not to delete their
	// file as well.
	// Nevertheless, use with care!  This method is only mean
	// for cleaning up an environment that's being destroyed.
	RemoveAll() error
}

// Storage represents storage that can be both
// read and written.
type Storage interface {
	StorageReader
	StorageWriter
}

// An Environ represents a juju environment as specified
// in the environments.yaml file.
//
// Due to the limitations of some providers (for example ec2), the
// results of the Environ methods may not be fully sequentially
// consistent. In particular, while a provider may retry when it
// gets an error for an operation, it will not retry when
// an operation succeeds, even if that success is not
// consistent with a previous operation.
//
// Even though Juju takes care not to share an Environ between concurrent
// workers, it does allow concurrent method calls into the provider
// implementation.  The typical provider implementation needs locking to
// avoid undefined behaviour when the configuration changes.
type Environ interface {
	// Name returns the Environ's name.
	Name() string

	// Bootstrap initializes the state for the environment, possibly
	// starting one or more instances.  If the configuration's
	// AdminSecret is non-empty, the adminstrator password on the
	// newly bootstrapped state will be set to a hash of it (see
	// utils.PasswordHash), When first connecting to the
	// environment via the juju package, the password hash will be
	// automatically replaced by the real password.
	//
	// The supplied constraints are used to choose the initial instance
	// specification, and will be stored in the new environment's state.
	Bootstrap(cons constraints.Value) error

	// StateInfo returns information on the state initialized
	// by Bootstrap.
	StateInfo() (*state.Info, *api.Info, error)

	// Config returns the current configuration of this Environ.
	Config() *config.Config

	// SetConfig updates the Environ's configuration.
	//
	// Calls to SetConfig do not affect the configuration of
	// values previously obtained from Storage and PublicStorage.
	SetConfig(cfg *config.Config) error

	// StartInstance asks for a new instance to be created, associated
	// with the provided machine identifier. The given info describes
	// the juju state for the new instance to connect to. The nonce,
	// which must be unique within an environment, is used by juju to
	// protect against the consequences of multiple instances being
	// started with the same machine id.
	StartInstance(machineId, machineNonce string, series string, cons constraints.Value,
		info *state.Info, apiInfo *api.Info) (instance.Instance, *instance.HardwareCharacteristics, error)

	// StopInstances shuts down the given instances.
	StopInstances([]instance.Instance) error

	// Instances returns a slice of instances corresponding to the
	// given instance ids.  If no instances were found, but there
	// was no other error, it will return ErrNoInstances.  If
	// some but not all the instances were found, the returned slice
	// will have some nil slots, and an ErrPartialInstances error
	// will be returned.
	Instances(ids []instance.Id) ([]instance.Instance, error)

	// AllInstances returns all instances currently known to the
	// environment.
	AllInstances() ([]instance.Instance, error)

	// Storage returns storage specific to the environment.
	Storage() Storage

	// PublicStorage returns storage shared between environments.
	PublicStorage() StorageReader

	// Destroy shuts down all known machines and destroys the
	// rest of the environment. A list of instances known to
	// be part of the environment can be given with insts.
	// This is because recently started machines might not
	// yet be visible in the environment, so this method
	// can wait until they are.
	//
	// When Destroy has been called, any Environ referring to the
	// same remote environment may become invalid
	Destroy(insts []instance.Instance) error

	// OpenPorts opens the given ports for the whole environment.
	// Must only be used if the environment was setup with the
	// FwGlobal firewall mode.
	OpenPorts(ports []instance.Port) error

	// ClosePorts closes the given ports for the whole environment.
	// Must only be used if the environment was setup with the
	// FwGlobal firewall mode.
	ClosePorts(ports []instance.Port) error

	// Ports returns the ports opened for the whole environment.
	// Must only be used if the environment was setup with the
	// FwGlobal firewall mode.
	Ports() ([]instance.Port, error)

	// Provider returns the EnvironProvider that created this Environ.
	Provider() EnvironProvider
}
<|endoftext|>


<commit_before>package views

import "html/template"

var List = template.Must(template.New("list").Parse(list))

const list = `<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Rivelin</title>

        {{range .UpdatedFeeds.UpdatedFeed}}

              {{.FeedTitle}}
              (Feed)

            {{.WhenLastUpdate.HtmlFormat}}

            {{range .Item}}

{{.Title}}

{{.FilteredBody}}

              {{.PubDate.HtmlFormat}}

            {{end}}

        {{end}}

        rivelin + riviera

`
<commit_msg>Remove explicit http: protocol from favicon<commit_after>package views

import "html/template"

var List = template.Must(template.New("list").Parse(list))

const list = `<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Rivelin</title>

        {{range .UpdatedFeeds.UpdatedFeed}}

              {{.FeedTitle}}
              (Feed)

            {{.WhenLastUpdate.HtmlFormat}}

            {{range .Item}}

{{.Title}}

{{.FilteredBody}}

              {{.PubDate.HtmlFormat}}

            {{end}}

        {{end}}

        rivelin + riviera

`
<|endoftext|>


<commit_before>// Copyright 2013 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package errors

import (
	"launchpad.net/gocheck"
	"testing"
)

func Test(t *testing.T) { gocheck.TestingT(t) }

type S struct{}

var _ = gocheck.Suite(&S{})

func (s *S) TestHttpError(c *gocheck.C) {
	e := Http{500, "Internal server error"}
	c.Assert(e.Error(), gocheck.Equals, e.Message)
}

func (s *S) TestValidationError(c *gocheck.C) {
	e := ValidationError{Message: "something"}
	c.Assert(e.Error(), gocheck.Equals, "something")
}
<commit_msg>errors: fix golint warning<commit_after>// Copyright 2013 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package errors

import (
	"launchpad.net/gocheck"
	"testing"
)

func Test(t *testing.T) { gocheck.TestingT(t) }

type S struct{}

var _ = gocheck.Suite(&S{})

func (s *S) TestHTTPError(c *gocheck.C) {
	e := Http{500, "Internal server error"}
	c.Assert(e.Error(), gocheck.Equals, e.Message)
}

func (s *S) TestValidationError(c *gocheck.C) {
	e := ValidationError{Message: "something"}
	c.Assert(e.Error(), gocheck.Equals, "something")
}
<|endoftext|>


<commit_before>package dls

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

	"github.com/200sc/klangsynthese/font/riffutil"
	"github.com/stretchr/testify/assert"
	"golang.org/x/image/riff"
)

func TestDLS(t *testing.T) {
	fl, err := os.Open("nolicenseforthis.dls")
	assert.Nil(t, err)
	typ, reader, err := riff.NewReader(fl)
	fmt.Println(riffutil.Header(typ))
	riffutil.DeepRead(reader)
}

func TestDLSUnmarshal(t *testing.T) {
	fl, err := os.Open("nolicenseforthis.dls")
	assert.Nil(t, err)
	dls := &DLS{}
	by, err := ioutil.ReadAll(fl)
	assert.Nil(t, err)
	err = riffutil.Unmarshal(by, dls)
	assert.Nil(t, err)
	//afmt := audio.Format{44100, 1, 16}
	fmt.Println(len(dls.Lins))
	fmt.Println("Version", dls.Vers)
	for _, ins := range dls.Lins {
		fmt.Println(ins.Insh)
		for _, rgn := range ins.Lrgn {
			fmt.Println(rgn)
		}
	}
	fmt.Println(dls.Info)
	//for _, w := range dls.Wvpl {
	//fmt.Println(w.Fmt)
	//a, err := afmt.Wave(w.Data)
	//assert.Nil(t, err)
	//a.Play()
	//time.Sleep(a.PlayLength())
	//}
}<commit_msg>Test fixes<commit_after>package dls

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

	"github.com/200sc/klangsynthese/font/riff"
	"github.com/stretchr/testify/assert"
)

func TestDLSUnmarshal(t *testing.T) {
	fl, err := os.Open("nolicenseforthis.dls")
	assert.Nil(t, err)
	dls := &DLS{}
	by, err := ioutil.ReadAll(fl)
	assert.Nil(t, err)
	err = riff.Unmarshal(by, dls)
	assert.Nil(t, err)
	//afmt := audio.Format{44100, 1, 16}
	fmt.Println(len(dls.Lins))
	fmt.Println("Version", dls.Vers)
	for _, ins := range dls.Lins {
		fmt.Println(ins.Insh)
		for _, rgn := range ins.Lrgn {
			fmt.Println(rgn)
		}
	}
	fmt.Println(dls.INFO)
	//for _, w := range dls.Wvpl {
	//fmt.Println(w.Fmt)
	//a, err := afmt.Wave(w.Data)
	//assert.Nil(t, err)
	//a.Play()
	//time.Sleep(a.PlayLength())
	//}
}
<|endoftext|>


<commit_before>package main

import (
	"database/sql"
	"testing"
	"time"
)

func TestInsertNextEvent(t *testing.T) {
	// overwrite DB query function to return locally defined event
	evt := event{}
	getNextEvent = func() (*event, error) {
		return &evt, nil
	}

	// setup different possibilities and expected results
	date := time.Date(2014, 4, 23, 18, 12, 0, 0, time.UTC)
	evtTreff := event{
		stammtisch: false,
		override:   "",
		location:   sql.NullString{"garbage", false},
		date:       date,
		topic:      sql.NullString{"Testing", true},
		speaker:    sql.NullString{"Test-Speaker", true},
	}
	strTreff := RobotBlockIdentifier + " 2014-04-23: c¼h: Testing von Test-Speaker"

	evtStammtisch := event{
		stammtisch: true,
		override:   "",
		location:   sql.NullString{"Mr. Woot", true},
		date:       date,
		topic:      sql.NullString{"GARBAGE", false},
		speaker:    sql.NullString{"GaRbAgE", false},
	}
	strStammtisch := RobotBlockIdentifier + " 2014-04-23: Stammtisch @ Mr. Woot https://www.noname-ev.de/yarpnarp.html bitte zu/absagen"

	now := time.Now()
	evtSpecial := event{
		stammtisch: false,
		override:   "RGB2R",
		location:   sql.NullString{"gArBaGe", false},
		date:       now,
		topic:      sql.NullString{"GArbAGe", false},
		speaker:    sql.NullString{"gaRBagE", false},
	}
	strSpecial := RobotBlockIdentifier + " HEUTE (" + now.Format("02.Jan") + "): Ausnahmsweise: RGB2R"

	strOld := RobotBlockIdentifier + " Derp"

	// Test if replacement works correctly
	evt = evtTreff

	var tests = map[event]map[string]string{
		evtTreff: map[string]string{
			"NoName":                         "NoName | " + strTreff,
			"NoName | " + strOld:             "NoName | " + strTreff,
			"NoName | " + strOld + " | Derp": "NoName | " + strTreff + " | Derp",
		},
		evtStammtisch: map[string]string{
			"NoName": "NoName | " + strStammtisch,
		},
		evtSpecial: map[string]string{
			"NoName": "NoName | " + strSpecial,
		},
	}

	for curEvt, topics := range tests {
		evt = curEvt
		for from, to := range topics {
			newTopic, err := replaceTopic(from)
			if err != nil {
				t.Fatal(err)
			}
			if newTopic != to {
				t.Errorf("insertNextEvent(%v)\n GOT: %q\nWANT: %q", from, newTopic, to)
			}
		}
	}
}
<commit_msg>use keyed fields to silence go vet<commit_after>package main

import (
	"database/sql"
	"testing"
	"time"
)

func TestInsertNextEvent(t *testing.T) {
	// overwrite DB query function to return locally defined event
	evt := event{}
	getNextEvent = func() (*event, error) {
		return &evt, nil
	}

	// setup different possibilities and expected results
	date := time.Date(2014, 4, 23, 18, 12, 0, 0, time.UTC)
	evtTreff := event{
		stammtisch: false,
		override:   "",
		location:   sql.NullString{String: "garbage", Valid: false},
		date:       date,
		topic:      sql.NullString{String: "Testing", Valid: true},
		speaker:    sql.NullString{String: "Test-Speaker", Valid: true},
	}
	strTreff := RobotBlockIdentifier + " 2014-04-23: c¼h: Testing von Test-Speaker"

	evtStammtisch := event{
		stammtisch: true,
		override:   "",
		location:   sql.NullString{String: "Mr. Woot", Valid: true},
		date:       date,
		topic:      sql.NullString{String: "GARBAGE", Valid: false},
		speaker:    sql.NullString{String: "GaRbAgE", Valid: false},
	}
	strStammtisch := RobotBlockIdentifier + " 2014-04-23: Stammtisch @ Mr. Woot https://www.noname-ev.de/yarpnarp.html bitte zu/absagen"

	now := time.Now()
	evtSpecial := event{
		stammtisch: false,
		override:   "RGB2R",
		location:   sql.NullString{String: "gArBaGe", Valid: false},
		date:       now,
		topic:      sql.NullString{String: "GArbAGe", Valid: false},
		speaker:    sql.NullString{String: "gaRBagE", Valid: false},
	}
	strSpecial := RobotBlockIdentifier + " HEUTE (" + now.Format("02.Jan") + "): Ausnahmsweise: RGB2R"

	strOld := RobotBlockIdentifier + " Derp"

	// Test if replacement works correctly
	evt = evtTreff

	var tests = map[event]map[string]string{
		evtTreff: map[string]string{
			"NoName":                         "NoName | " + strTreff,
			"NoName | " + strOld:             "NoName | " + strTreff,
			"NoName | " + strOld + " | Derp": "NoName | " + strTreff + " | Derp",
		},
		evtStammtisch: map[string]string{
			"NoName": "NoName | " + strStammtisch,
		},
		evtSpecial: map[string]string{
			"NoName": "NoName | " + strSpecial,
		},
	}

	for curEvt, topics := range tests {
		evt = curEvt
		for from, to := range topics {
			newTopic, err := replaceTopic(from)
			if err != nil {
				t.Fatal(err)
			}
			if newTopic != to {
				t.Errorf("insertNextEvent(%v)\n GOT: %q\nWANT: %q", from, newTopic, to)
			}
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>change the transformation function in tests<commit_after><|endoftext|>


<commit_before>package lnwallet

import (
	"errors"
	"fmt"
	"sync"

	"github.com/roasbeef/btcd/btcec"
	"github.com/roasbeef/btcd/txscript"
	"github.com/roasbeef/btcd/wire"
	"github.com/roasbeef/btcutil"
)

// ErrNotMine is an error denoting that a WalletController instance is unable
// to spend a specifid output.
var ErrNotMine = errors.New("the passed output doesn't belong to the wallet")

// AddressType is a enum-like type which denotes the possible address types
// WalletController supports.
type AddressType uint8

const (
	// WitnessPubKey represents a p2wkh address.
	WitnessPubKey AddressType = iota

	// NestedWitnessPubKey represents a p2sh output which is itself a
	// nested p2wkh output.
	NestedWitnessPubKey

	// PublicKey represents a regular p2pkh output.
	PubKeyHash
)

// Utxo is an unspent output denoted by its outpoint, and output value of the
// original output.
type Utxo struct {
	Value btcutil.Amount
	wire.OutPoint
}

// WalletController defines an abstract interface for controlling a local Pure
// Go wallet, a local or remote wallet via an RPC mechanism, or possibly even
// a daemon assisted hardware wallet. This interface serves the purpose of
// allowing LightningWallet to be seamlessly compatible with several wallets
// such as: uspv, btcwallet, Bitcoin Core, Electrum, etc. This interface then
// serves as a "base wallet", with Lightning Network awareness taking place at
// a "higher" level of abstraction. Essentially, an overlay wallet.
// Implementors of this interface must closely adhere to the documented
// behavior of all interface methods in order to ensure identical behavior
// across all concrete implementations.
type WalletController interface {
	// FetchInputInfo queries for the WalletController's knowledge of the
	// passed outpoint. If the base wallet determines this output is under
	// its control, then the original txout should be returned. Otherwise,
	// a non-nil error value of ErrNotMine should be returned instead.
	FetchInputInfo(prevOut *wire.OutPoint) (*wire.TxOut, error)

	// ConfirmedBalance returns the sum of all the wallet's unspent outputs
	// that have at least confs confirmations. If confs is set to zero,
	// then all unspent outputs, including those currently in the mempool
	// will be included in the final sum.
	ConfirmedBalance(confs int32, witness bool) (btcutil.Amount, error)

	// NewAddress returns the next external or internal address for the
	// wallet dicatated by the value of the `change` paramter. If change is
	// true, then an internal address should be used, otherwise an external
	// address should be returned. The type of address returned is dictated
	// by the wallet's capabilities, and may be of type: p2sh, p2pkh,
	// p2wkh, p2wsh, etc.
	NewAddress(addrType AddressType, change bool) (btcutil.Address, error)

	// GetPrivKey retrives the underlying private key associated with the
	// passed address. If the wallet is unable to locate this private key
	// due to the address not being under control of the wallet, then an
	// error should be returned.
	// TODO(roasbeef): should instead take tadge's derivation scheme in
	GetPrivKey(a btcutil.Address) (*btcec.PrivateKey, error)

	// NewRawKey returns a raw private key controlled by the wallet. These
	// keys are used for the 2-of-2 multi-sig outputs for funding
	// transactions, as well as the pub key used for commitment transactions.
	// TODO(roasbeef): may be scrapped, see above TODO
	NewRawKey() (*btcec.PublicKey, error)

	// FetchRootKey returns a root key which will be used by the
	// LightningWallet to deterministically generate secrets. The private
	// key returned by this method should remain constant in-between
	// WalletController restarts.
	FetchRootKey() (*btcec.PrivateKey, error)

	// SendOutputs funds, signs, and broadcasts a Bitcoin transaction
	// paying out to the specified outputs. In the case the wallet has
	// insufficient funds, or the outputs are non-standard, and error
	// should be returned.
	SendOutputs(outputs []*wire.TxOut) (*wire.ShaHash, error)

	// ListUnspentWitness returns all unspent outputs which are version 0
	// witness programs. The 'confirms' parameter indicates the minimum
	// number of confirmations an output needs in order to be returned by
	// this method. Passing -1 as 'confirms' indicates that even
	// unconfirmed outputs should be returned.
	ListUnspentWitness(confirms int32) ([]*Utxo, error)

	// LockOutpoint marks an outpoint as locked meaning it will no longer
	// be deemed as eligible for coin selection. Locking outputs are
	// utilized in order to avoid race conditions when selecting inputs for
	// usage when funding a channel.
	LockOutpoint(o wire.OutPoint)

	// UnlockOutpoint unlocks an previously locked output, marking it
	// eligible for coin seleciton.
	UnlockOutpoint(o wire.OutPoint)

	// PublishTransaction performs cursory validation (dust checks, etc),
	// then finally broadcasts the passed transaction to the Bitcoin network.
	PublishTransaction(tx *wire.MsgTx) error

	// Start initializes the wallet, making any neccessary connections,
	// starting up required goroutines etc.
	Start() error

	// Stop signals the wallet for shutdown. Shutdown may entail closing
	// any active sockets, database handles, stopping goroutines, etc.
	Stop() error
}

// BlockChainIO is a dedicated source which will be used to obtain queries
// related to the current state of the blockchain. The data returned by each of
// the defined methods within this interface should always return the most up
// to date data possible.
//
// TODO(roasbeef): move to diff package perhaps?
// TODO(roasbeef): move publish txn here?
type BlockChainIO interface {
	// GetCurrentHeight returns the current height of the valid most-work
	// chain the implementation is aware of.
	GetCurrentHeight() (int32, error)

	// GetTxOut returns the original output referenced by the passed
	// outpoint.
	GetUtxo(txid *wire.ShaHash, index uint32) (*wire.TxOut, error)

	// GetTransaction returns the full transaction identified by the passed
	// transaction ID.
	GetTransaction(txid *wire.ShaHash) (*wire.MsgTx, error)
}

// SignDescriptor houses the necessary information required to succesfully sign
// a given output. This struct is used by the Signer interface in order to gain
// access to critial data needed to generate a valid signature.
type SignDescriptor struct {
	// Pubkey is the public key to which the signature should be generated
	// over. The Signer should then generate a signature with the private
	// key corresponding to this public key.
	PubKey *btcec.PublicKey

	// RedeemScript is the full script required to properly redeem the
	// output. This field will only be populated if a p2wsh or a p2sh
	// output is being signed.
	RedeemScript []byte

	// Output is the target output which should be signed. The PkScript and
	// Value fields within the output should be properly populated,
	// otherwise an invalid signature may be generated.
	Output *wire.TxOut

	// HashType is the target sighash type that should be used when
	// generating the final sighash, and signature.
	HashType txscript.SigHashType

	// SigHashes is the pre-computed sighash midstate to be used when
	// generating the final sighash for signing.
	SigHashes *txscript.TxSigHashes

	// InputIndex is the target input within the transaction that should be
	// signed.
	InputIndex int
}

// Signer represents an abstract object capable of generating raw signatures as
// well as full complete input scripts given a valid SignDescriptor and
// transaction. This interface fully abstracts away signing paving the way for
// Signer implementations such as hardware wallets, hardware tokens, HSM's, or
// simply a regular wallet.
type Signer interface {
	// SignOutputRaw generates a signature for the passed transaction
	// according to the data within the passed SignDescriptor.
	//
	// NOTE: The resulting signature should be void of a sighash byte.
	SignOutputRaw(tx *wire.MsgTx, signDesc *SignDescriptor) ([]byte, error)

	// ComputeInputScript generates a complete InputIndex for the passed
	// transaction with the signature as defined within the passed
	// SignDescriptor. This method should be capable of generating the
	// proper input script for both regular p2wkh output and p2wkh outputs
	// nested within a regualr p2sh output.
	ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor) (*InputScript, error)
}

// WalletDriver represents a "driver" for a particular concrete
// WalletController implementation. A driver is indentified by a globally
// unique string identifier along with a 'New()' method which is responsible
// for initializing a particular WalletController concrete implementation.
type WalletDriver struct {
	// WalletType is a string which uniquely identifes the WalletController
	// that this driver, drives.
	WalletType string

	// New creates a new instance of a concrete WalletController
	// implementation given a variadic set up arguments. The function takes
	// a varidaic number of interface paramters in order to provide
	// initialization flexibility, thereby accomodating several potential
	// WalletController implementations.
	New func(args ...interface{}) (WalletController, error)
}

var (
	wallets     = make(map[string]*WalletDriver)
	registerMtx sync.Mutex
)

// RegisteredWallets returns a slice of all currently registered notifiers.
//
// NOTE: This function is safe for concurrent access.
func RegisteredWallets() []*WalletDriver {
	registerMtx.Lock()
	defer registerMtx.Unlock()

	registeredWallets := make([]*WalletDriver, 0, len(wallets))
	for _, wallet := range wallets {
		registeredWallets = append(registeredWallets, wallet)
	}

	return registeredWallets
}

// RegisterWallet registers a WalletDriver which is capable of driving a
// concrete WalletController interface. In the case that this driver has
// already been registered, an error is returned.
//
// NOTE: This function is safe for concurrent access.
func RegisterWallet(driver *WalletDriver) error {
	registerMtx.Lock()
	defer registerMtx.Unlock()

	if _, ok := wallets[driver.WalletType]; ok {
		return fmt.Errorf("wallet already registered")
	}

	wallets[driver.WalletType] = driver

	return nil
}

// SupportedWallets returns a slice of strings that represents the walelt
// drivers that have been registered and are therefore supported.
//
// NOTE: This function is safe for concurrent access.
func SupportedWallets() []string {
	registerMtx.Lock()
	defer registerMtx.Unlock()

	supportedWallets := make([]string, 0, len(wallets))
	for walletName := range wallets {
		supportedWallets = append(supportedWallets, walletName)
	}

	return supportedWallets
}
<commit_msg>lnwallet: add method to list relevant txns to WalletController interface<commit_after>package lnwallet

import (
	"errors"
	"fmt"
	"sync"

	"github.com/roasbeef/btcd/btcec"
	"github.com/roasbeef/btcd/txscript"
	"github.com/roasbeef/btcd/wire"
	"github.com/roasbeef/btcutil"
)

// ErrNotMine is an error denoting that a WalletController instance is unable
// to spend a specifid output.
var ErrNotMine = errors.New("the passed output doesn't belong to the wallet")

// AddressType is a enum-like type which denotes the possible address types
// WalletController supports.
type AddressType uint8

const (
	// WitnessPubKey represents a p2wkh address.
	WitnessPubKey AddressType = iota

	// NestedWitnessPubKey represents a p2sh output which is itself a
	// nested p2wkh output.
	NestedWitnessPubKey

	// PublicKey represents a regular p2pkh output.
	PubKeyHash
)

// Utxo is an unspent output denoted by its outpoint, and output value of the
// original output.
type Utxo struct {
	Value btcutil.Amount
	wire.OutPoint
}

// TransactionDetail describes a transaction with either inputs which belong to
// the wallet, or has outputs that pay to the wallet.
type TransactionDetail struct {
	// Hash is the transaction hash of the transaction.
	Hash wire.ShaHash

	// Value is the net value of this transaction (in satoshis) from the
	// PoV of the wallet. If this transaction purely spends from the
	// wallet's funds, then this value will be negative. Similarly, if this
	// transaction credits the wallet, then this value will be positive.
	Value btcutil.Amount

	// NumConfirmations is the number of confirmations this transaction
	// has. If the transaction is unconfirmed, then this value will be
	// zero.
	NumConfirmations int32

	// BlockHeight is the hash of the block which includes this
	// transaction. Unconfirmed transactions will have a nil value for this
	// field.
	BlockHash *wire.ShaHash

	// BlockHeight is the height of the block including this transaction.
	// Unconfirmed transaction will show a height of zero.
	BlockHeight int32

	// Timestamp is the unix timestamp of the block including this
	// transaction. If the transaction is unconfirmed, then this will be a
	// timestamp of txn creation.
	Timestamp int64

	// TotalFees is the total fee in satoshis paid by this transaction.
	TotalFees int64
}
// WalletController defines an abstract interface for controlling a local Pure
// Go wallet, a local or remote wallet via an RPC mechanism, or possibly even
// a daemon assisted hardware wallet. This interface serves the purpose of
// allowing LightningWallet to be seamlessly compatible with several wallets
// such as: uspv, btcwallet, Bitcoin Core, Electrum, etc. This interface then
// serves as a "base wallet", with Lightning Network awareness taking place at
// a "higher" level of abstraction. Essentially, an overlay wallet.
// Implementors of this interface must closely adhere to the documented
// behavior of all interface methods in order to ensure identical behavior
// across all concrete implementations.
type WalletController interface {
	// FetchInputInfo queries for the WalletController's knowledge of the
	// passed outpoint. If the base wallet determines this output is under
	// its control, then the original txout should be returned. Otherwise,
	// a non-nil error value of ErrNotMine should be returned instead.
	FetchInputInfo(prevOut *wire.OutPoint) (*wire.TxOut, error)

	// ConfirmedBalance returns the sum of all the wallet's unspent outputs
	// that have at least confs confirmations. If confs is set to zero,
	// then all unspent outputs, including those currently in the mempool
	// will be included in the final sum.
	ConfirmedBalance(confs int32, witness bool) (btcutil.Amount, error)

	// NewAddress returns the next external or internal address for the
	// wallet dicatated by the value of the `change` paramter. If change is
	// true, then an internal address should be used, otherwise an external
	// address should be returned. The type of address returned is dictated
	// by the wallet's capabilities, and may be of type: p2sh, p2pkh,
	// p2wkh, p2wsh, etc.
	NewAddress(addrType AddressType, change bool) (btcutil.Address, error)

	// GetPrivKey retrives the underlying private key associated with the
	// passed address. If the wallet is unable to locate this private key
	// due to the address not being under control of the wallet, then an
	// error should be returned.
	GetPrivKey(a btcutil.Address) (*btcec.PrivateKey, error)

	// NewRawKey returns a raw private key controlled by the wallet. These
	// keys are used for the 2-of-2 multi-sig outputs for funding
	// transactions, as well as the pub key used for commitment transactions.
	NewRawKey() (*btcec.PublicKey, error)

	// FetchRootKey returns a root key which will be used by the
	// LightningWallet to deterministically generate secrets. The private
	// key returned by this method should remain constant in-between
	// WalletController restarts.
	FetchRootKey() (*btcec.PrivateKey, error)

	// SendOutputs funds, signs, and broadcasts a Bitcoin transaction
	// paying out to the specified outputs. In the case the wallet has
	// insufficient funds, or the outputs are non-standard, and error
	// should be returned.
	SendOutputs(outputs []*wire.TxOut) (*wire.ShaHash, error)

	// ListUnspentWitness returns all unspent outputs which are version 0
	// witness programs. The 'confirms' parameter indicates the minimum
	// number of confirmations an output needs in order to be returned by
	// this method. Passing -1 as 'confirms' indicates that even
	// unconfirmed outputs should be returned.
	ListUnspentWitness(confirms int32) ([]*Utxo, error)

	// ListTransactionDetails returns a list of all transactions which are
	// relevant to the wallet.
	ListTransactionDetails() ([]*TransactionDetail, error)

	// LockOutpoint marks an outpoint as locked meaning it will no longer
	// be deemed as eligible for coin selection. Locking outputs are
	// utilized in order to avoid race conditions when selecting inputs for
	// usage when funding a channel.
	LockOutpoint(o wire.OutPoint)

	// UnlockOutpoint unlocks an previously locked output, marking it
	// eligible for coin seleciton.
	UnlockOutpoint(o wire.OutPoint)

	// PublishTransaction performs cursory validation (dust checks, etc),
	// then finally broadcasts the passed transaction to the Bitcoin network.
	PublishTransaction(tx *wire.MsgTx) error

	// Start initializes the wallet, making any neccessary connections,
	// starting up required goroutines etc.
	Start() error

	// Stop signals the wallet for shutdown. Shutdown may entail closing
	// any active sockets, database handles, stopping goroutines, etc.
	Stop() error
}

// BlockChainIO is a dedicated source which will be used to obtain queries
// related to the current state of the blockchain. The data returned by each of
// the defined methods within this interface should always return the most up
// to date data possible.
//
// TODO(roasbeef): move to diff package perhaps?
// TODO(roasbeef): move publish txn here?
type BlockChainIO interface {
	// GetCurrentHeight returns the current height of the valid most-work
	// chain the implementation is aware of.
	GetCurrentHeight() (int32, error)

	// GetTxOut returns the original output referenced by the passed
	// outpoint.
	GetUtxo(txid *wire.ShaHash, index uint32) (*wire.TxOut, error)

	// GetTransaction returns the full transaction identified by the passed
	// transaction ID.
	GetTransaction(txid *wire.ShaHash) (*wire.MsgTx, error)
}

// SignDescriptor houses the necessary information required to succesfully sign
// a given output. This struct is used by the Signer interface in order to gain
// access to critial data needed to generate a valid signature.
type SignDescriptor struct {
	// Pubkey is the public key to which the signature should be generated
	// over. The Signer should then generate a signature with the private
	// key corresponding to this public key.
	PubKey *btcec.PublicKey

	// RedeemScript is the full script required to properly redeem the
	// output. This field will only be populated if a p2wsh or a p2sh
	// output is being signed.
	RedeemScript []byte

	// Output is the target output which should be signed. The PkScript and
	// Value fields within the output should be properly populated,
	// otherwise an invalid signature may be generated.
	Output *wire.TxOut

	// HashType is the target sighash type that should be used when
	// generating the final sighash, and signature.
	HashType txscript.SigHashType

	// SigHashes is the pre-computed sighash midstate to be used when
	// generating the final sighash for signing.
	SigHashes *txscript.TxSigHashes

	// InputIndex is the target input within the transaction that should be
	// signed.
	InputIndex int
}

// Signer represents an abstract object capable of generating raw signatures as
// well as full complete input scripts given a valid SignDescriptor and
// transaction. This interface fully abstracts away signing paving the way for
// Signer implementations such as hardware wallets, hardware tokens, HSM's, or
// simply a regular wallet.
type Signer interface {
	// SignOutputRaw generates a signature for the passed transaction
	// according to the data within the passed SignDescriptor.
	//
	// NOTE: The resulting signature should be void of a sighash byte.
	SignOutputRaw(tx *wire.MsgTx, signDesc *SignDescriptor) ([]byte, error)

	// ComputeInputScript generates a complete InputIndex for the passed
	// transaction with the signature as defined within the passed
	// SignDescriptor. This method should be capable of generating the
	// proper input script for both regular p2wkh output and p2wkh outputs
	// nested within a regualr p2sh output.
	ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor) (*InputScript, error)
}

// WalletDriver represents a "driver" for a particular concrete
// WalletController implementation. A driver is indentified by a globally
// unique string identifier along with a 'New()' method which is responsible
// for initializing a particular WalletController concrete implementation.
type WalletDriver struct {
	// WalletType is a string which uniquely identifes the WalletController
	// that this driver, drives.
	WalletType string

	// New creates a new instance of a concrete WalletController
	// implementation given a variadic set up arguments. The function takes
	// a varidaic number of interface paramters in order to provide
	// initialization flexibility, thereby accomodating several potential
	// WalletController implementations.
	New func(args ...interface{}) (WalletController, error)
}

var (
	wallets     = make(map[string]*WalletDriver)
	registerMtx sync.Mutex
)

// RegisteredWallets returns a slice of all currently registered notifiers.
//
// NOTE: This function is safe for concurrent access.
func RegisteredWallets() []*WalletDriver {
	registerMtx.Lock()
	defer registerMtx.Unlock()

	registeredWallets := make([]*WalletDriver, 0, len(wallets))
	for _, wallet := range wallets {
		registeredWallets = append(registeredWallets, wallet)
	}

	return registeredWallets
}

// RegisterWallet registers a WalletDriver which is capable of driving a
// concrete WalletController interface. In the case that this driver has
// already been registered, an error is returned.
//
// NOTE: This function is safe for concurrent access.
func RegisterWallet(driver *WalletDriver) error {
	registerMtx.Lock()
	defer registerMtx.Unlock()

	if _, ok := wallets[driver.WalletType]; ok {
		return fmt.Errorf("wallet already registered")
	}

	wallets[driver.WalletType] = driver

	return nil
}

// SupportedWallets returns a slice of strings that represents the walelt
// drivers that have been registered and are therefore supported.
//
// NOTE: This function is safe for concurrent access.
func SupportedWallets() []string {
	registerMtx.Lock()
	defer registerMtx.Unlock()

	supportedWallets := make([]string, 0, len(wallets))
	for walletName := range wallets {
		supportedWallets = append(supportedWallets, walletName)
	}

	return supportedWallets
}
<|endoftext|>


<commit_before>package udp

import (
	"net"
	"testing"
	"time"
)

var (
	testAddr = ":8126"
)

func TestAll(t *testing.T) {
	udpClient, err := net.DialTimeout("udp", testAddr, time.Second)
	if err != nil {
		t.Fatal(err)
	}

	SetAddr(testAddr)

	testValues := [][]interface{}{
		[]interface{}{"foo", "foo", true, true},
		[]interface{}{"foo", "bar", false, false},
		[]interface{}{"foo", "foobar", false, true},
		[]interface{}{"", "", true, true},
	}

	for _, values := range testValues {
		shouldGet := values[0].(string)
		sendString := values[1].(string)
		shouldEquals := values[2].(bool)
		shouldContains := values[3].(bool)

		got, equals, contains := get(t, shouldGet, func() {
			udpClient.Write([]byte(sendString))
		})

		if got != sendString {
			t.Errorf("Should've got %s but got %s", sendString, got)
		}
		if equals != shouldEquals {
			t.Errorf("Equals should've been %s but was %s", shouldEquals, equals)
		}
		if contains != shouldContains {
			t.Errorf("Contains should've been %s but was %s", shouldContains, contains)
		}
	}

	ShouldReceiveOnly(t, "foo", func() {
		udpClient.Write([]byte("foo"))
	})

	ShouldNotReceiveOnly(t, "bar", func() {
		udpClient.Write([]byte("foo"))
	})

	ShouldReceive(t, "foo", func() {
		udpClient.Write([]byte("barfoo"))
	})

	ShouldNotReceive(t, "bar", func() {
		udpClient.Write([]byte("fooba"))
	})

	ShouldReceiveAll(t, []string{"foo", "bar"}, func() {
		udpClient.Write([]byte("foobizbar"))
	})

	ShouldNotReceiveAny(t, []string{"fooby", "bars"}, func() {
		udpClient.Write([]byte("foobizbar"))
	})

	ShouldReceiveAllAndNotReceiveAny(t, []string{"foo", "bar"}, []string{"fooby", "bars"}, func() {
		udpClient.Write([]byte("foobizbar"))
	})
}
<commit_msg>Add another (commented out) test for the stalling bug.<commit_after>package udp

import (
	"net"
	"testing"
	"time"
)

var (
	testAddr = ":8126"
)

func TestAll(t *testing.T) {
	udpClient, err := net.DialTimeout("udp", testAddr, time.Second)
	if err != nil {
		t.Fatal(err)
	}

	SetAddr(testAddr)

	testValues := [][]interface{}{
		[]interface{}{"foo", "foo", true, true},
		[]interface{}{"foo", "bar", false, false},
		[]interface{}{"foo", "foobar", false, true},
		[]interface{}{"", "", true, true},
	}

	for _, values := range testValues {
		shouldGet := values[0].(string)
		sendString := values[1].(string)
		shouldEquals := values[2].(bool)
		shouldContains := values[3].(bool)

		got, equals, contains := get(t, shouldGet, func() {
			udpClient.Write([]byte(sendString))
		})

		if got != sendString {
			t.Errorf("Should've got %s but got %s", sendString, got)
		}
		if equals != shouldEquals {
			t.Errorf("Equals should've been %s but was %s", shouldEquals, equals)
		}
		if contains != shouldContains {
			t.Errorf("Contains should've been %s but was %s", shouldContains, contains)
		}
	}

	ShouldReceiveOnly(t, "foo", func() {
		udpClient.Write([]byte("foo"))
	})

	ShouldNotReceiveOnly(t, "bar", func() {
		udpClient.Write([]byte("foo"))
	})

	ShouldReceive(t, "foo", func() {
		udpClient.Write([]byte("barfoo"))
	})

	ShouldNotReceive(t, "bar", func() {
		udpClient.Write([]byte("fooba"))
	})

	ShouldReceiveAll(t, []string{"foo", "bar"}, func() {
		udpClient.Write([]byte("foobizbar"))
	})

	ShouldNotReceiveAny(t, []string{"fooby", "bars"}, func() {
		udpClient.Write([]byte("foobizbar"))
	})

	ShouldReceiveAllAndNotReceiveAny(t, []string{"foo", "bar"}, []string{"fooby", "bars"}, func() {
		udpClient.Write([]byte("foobizbar"))
	})

	// This should fail, but it also shouldn't stall out
	// ShouldReceive(t, "foo", func() {})
}
<|endoftext|>


<commit_before>package ui

import (
	"fmt"
	"os"

	"github.com/ValeLint/vale/core"
	"github.com/fatih/color"
	"github.com/olekukonko/tablewriter"
)

const (
	errorColor      color.Attribute = color.FgRed
	warningColor                    = color.FgYellow
	suggestionColor                 = color.FgBlue
	underlineColor                  = color.Underline
)

// PrintVerboseAlerts prints Alerts in verbose format.
func PrintVerboseAlerts(linted []*core.File, wrap bool) bool {
	var errors, warnings, suggestions int
	var e, w, s int
	var symbol string

	for _, f := range linted {
		e, w, s = printVerboseAlert(f, wrap)
		errors += e
		warnings += w
		suggestions += s
	}

	etotal := fmt.Sprintf("%d %s", errors, pluralize("error", errors))
	wtotal := fmt.Sprintf("%d %s", warnings, pluralize("warning", warnings))
	stotal := fmt.Sprintf("%d %s", suggestions, pluralize("suggestion", suggestions))

	if errors > 0 || warnings > 0 {
		symbol = "\u2716"
	} else {
		symbol = "\u2714"
	}

	n := len(linted)
	fmt.Printf("%s %s, %s and %s in %d %s.\n", symbol,
		colorize(etotal, errorColor), colorize(wtotal, warningColor),
		colorize(stotal, suggestionColor), n, pluralize("file", n))

	return errors != 0
}

// printVerboseAlert includes an alert's line, column, level, and message.
func printVerboseAlert(f *core.File, wrap bool) (int, int, int) {
	var loc, level string
	var errors, warnings, notifications int

	alerts := f.SortedAlerts()
	if len(alerts) == 0 {
		return 0, 0, 0
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetCenterSeparator("")
	table.SetColumnSeparator("")
	table.SetRowSeparator("")
	table.SetAutoWrapText(!wrap)

	fmt.Printf("\n %s", colorize(f.Path, underlineColor))
	for _, a := range alerts {
		a.Message = fixOutputSpacing(a.Message)
		if a.Severity == "suggestion" {
			level = colorize(a.Severity, suggestionColor)
			notifications++
		} else if a.Severity == "warning" {
			level = colorize(a.Severity, warningColor)
			warnings++
		} else {
			level = colorize(a.Severity, errorColor)
			errors++
		}
		loc = fmt.Sprintf("%d:%d", a.Line, a.Span[0])
		table.Append([]string{loc, level, a.Message, a.Check})
	}
	table.Render()
	return errors, warnings, notifications
}

func colorize(message string, textColor color.Attribute) string {
	colorPrinter := color.New(textColor)
	f := colorPrinter.SprintFunc()
	return f(message)
}
<commit_msg>refactor: list stdin instead of 'n file(s)' when applicable<commit_after>package ui

import (
	"fmt"
	"os"
	"strings"

	"github.com/ValeLint/vale/core"
	"github.com/fatih/color"
	"github.com/olekukonko/tablewriter"
)

const (
	errorColor      color.Attribute = color.FgRed
	warningColor                    = color.FgYellow
	suggestionColor                 = color.FgBlue
	underlineColor                  = color.Underline
)

// PrintVerboseAlerts prints Alerts in verbose format.
func PrintVerboseAlerts(linted []*core.File, wrap bool) bool {
	var errors, warnings, suggestions int
	var e, w, s int
	var symbol string

	for _, f := range linted {
		e, w, s = printVerboseAlert(f, wrap)
		errors += e
		warnings += w
		suggestions += s
	}

	etotal := fmt.Sprintf("%d %s", errors, pluralize("error", errors))
	wtotal := fmt.Sprintf("%d %s", warnings, pluralize("warning", warnings))
	stotal := fmt.Sprintf("%d %s", suggestions, pluralize("suggestion", suggestions))

	if errors > 0 || warnings > 0 {
		symbol = "\u2716"
	} else {
		symbol = "\u2714"
	}

	n := len(linted)
	if n == 1 && strings.HasPrefix(linted[0].Path, "stdin") {
		fmt.Printf("%s %s, %s and %s in %s.\n", symbol,
			colorize(etotal, errorColor), colorize(wtotal, warningColor),
			colorize(stotal, suggestionColor), "stdin")
	} else {
		fmt.Printf("%s %s, %s and %s in %d %s.\n", symbol,
			colorize(etotal, errorColor), colorize(wtotal, warningColor),
			colorize(stotal, suggestionColor), n, pluralize("file", n))
	}

	return errors != 0
}

// printVerboseAlert includes an alert's line, column, level, and message.
func printVerboseAlert(f *core.File, wrap bool) (int, int, int) {
	var loc, level string
	var errors, warnings, notifications int

	alerts := f.SortedAlerts()
	if len(alerts) == 0 {
		return 0, 0, 0
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetCenterSeparator("")
	table.SetColumnSeparator("")
	table.SetRowSeparator("")
	table.SetAutoWrapText(!wrap)

	fmt.Printf("\n %s", colorize(f.Path, underlineColor))
	for _, a := range alerts {
		a.Message = fixOutputSpacing(a.Message)
		if a.Severity == "suggestion" {
			level = colorize(a.Severity, suggestionColor)
			notifications++
		} else if a.Severity == "warning" {
			level = colorize(a.Severity, warningColor)
			warnings++
		} else {
			level = colorize(a.Severity, errorColor)
			errors++
		}
		loc = fmt.Sprintf("%d:%d", a.Line, a.Span[0])
		table.Append([]string{loc, level, a.Message, a.Check})
	}
	table.Render()
	return errors, warnings, notifications
}

func colorize(message string, textColor color.Attribute) string {
	colorPrinter := color.New(textColor)
	f := colorPrinter.SprintFunc()
	return f(message)
}
<|endoftext|>


<commit_before>package sentry

import (
	"fmt"
	"net/http"
	"testing"

	"time"

	"github.com/stretchr/testify/assert"
)

func TestOrganizationService_List(t *testing.T) {
	httpClient, mux, server := testServer()
	defer server.Close()

	mux.HandleFunc("/api/0/organizations/", func(w http.ResponseWriter, r *http.Request) {
		assertMethod(t, "GET", r)
		assertQuery(t, map[string]string{"cursor": "1500300636142:0:1"}, r)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `[
			{
				"name": "The Interstellar Jurisdiction",
				"slug": "the-interstellar-jurisdiction",
				"avatar": {
					"avatarUuid": null,
					"avatarType": "letter_avatar"
				},
				"dateCreated": "2017-07-17T14:10:36.141Z",
				"id": "2",
				"isEarlyAdopter": false
			}
		]`)
	})

	client := NewClient(httpClient, nil, "")
	organizations, _, err := client.Organizations.List(&ListOrganizationParams{
		Cursor: "1500300636142:0:1",
	})
	assert.NoError(t, err)

	expectedDateCreated, _ := time.Parse(time.RFC3339, "2017-07-17T14:10:36.141Z")
	expected := []Organization{
		{
			ID:             "2",
			Slug:           "the-interstellar-jurisdiction",
			Name:           "The Interstellar Jurisdiction",
			DateCreated:    expectedDateCreated,
			IsEarlyAdopter: false,
			Avatar: &OrganizationAvatar{
				UUID: nil,
				Type: "letter_avatar",
			},
		},
	}
	assert.Equal(t, expected, organizations)
}

func TestOrganizationService_Create(t *testing.T) {
	httpClient, mux, server := testServer()
	defer server.Close()

	mux.HandleFunc("/api/0/organizations/", func(w http.ResponseWriter, r *http.Request) {
		assertMethod(t, "POST", r)
		assertPostJSON(t, map[string]interface{}{
			"name": "The Interstellar Jurisdiction",
			"slug": "the-interstellar-jurisdiction",
		}, r)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `{
			"name": "The Interstellar Jurisdiction",
			"slug": "the-interstellar-jurisdiction",
			"id": "2"
		}`)
	})

	client := NewClient(httpClient, nil, "")
	params := &CreateOrganizationParams{
		Name: "The Interstellar Jurisdiction",
		Slug: "the-interstellar-jurisdiction",
	}
	organization, _, err := client.Organizations.Create(params)
	assert.NoError(t, err)
	expected := &Organization{
		ID:   "2",
		Name: "The Interstellar Jurisdiction",
		Slug: "the-interstellar-jurisdiction",
	}
	assert.Equal(t, expected, organization)
}
<commit_msg>Test update organization<commit_after>package sentry

import (
	"fmt"
	"net/http"
	"testing"

	"time"

	"github.com/stretchr/testify/assert"
)

func TestOrganizationService_List(t *testing.T) {
	httpClient, mux, server := testServer()
	defer server.Close()

	mux.HandleFunc("/api/0/organizations/", func(w http.ResponseWriter, r *http.Request) {
		assertMethod(t, "GET", r)
		assertQuery(t, map[string]string{"cursor": "1500300636142:0:1"}, r)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `[
			{
				"name": "The Interstellar Jurisdiction",
				"slug": "the-interstellar-jurisdiction",
				"avatar": {
					"avatarUuid": null,
					"avatarType": "letter_avatar"
				},
				"dateCreated": "2017-07-17T14:10:36.141Z",
				"id": "2",
				"isEarlyAdopter": false
			}
		]`)
	})

	client := NewClient(httpClient, nil, "")
	organizations, _, err := client.Organizations.List(&ListOrganizationParams{
		Cursor: "1500300636142:0:1",
	})
	assert.NoError(t, err)

	expectedDateCreated, _ := time.Parse(time.RFC3339, "2017-07-17T14:10:36.141Z")
	expected := []Organization{
		{
			ID:             "2",
			Slug:           "the-interstellar-jurisdiction",
			Name:           "The Interstellar Jurisdiction",
			DateCreated:    expectedDateCreated,
			IsEarlyAdopter: false,
			Avatar: &OrganizationAvatar{
				UUID: nil,
				Type: "letter_avatar",
			},
		},
	}
	assert.Equal(t, expected, organizations)
}

func TestOrganizationService_Create(t *testing.T) {
	httpClient, mux, server := testServer()
	defer server.Close()

	mux.HandleFunc("/api/0/organizations/", func(w http.ResponseWriter, r *http.Request) {
		assertMethod(t, "POST", r)
		assertPostJSON(t, map[string]interface{}{
			"name": "The Interstellar Jurisdiction",
			"slug": "the-interstellar-jurisdiction",
		}, r)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `{
			"name": "The Interstellar Jurisdiction",
			"slug": "the-interstellar-jurisdiction",
			"id": "2"
		}`)
	})

	client := NewClient(httpClient, nil, "")
	params := &CreateOrganizationParams{
		Name: "The Interstellar Jurisdiction",
		Slug: "the-interstellar-jurisdiction",
	}
	organization, _, err := client.Organizations.Create(params)
	assert.NoError(t, err)
	expected := &Organization{
		ID:   "2",
		Name: "The Interstellar Jurisdiction",
		Slug: "the-interstellar-jurisdiction",
	}
	assert.Equal(t, expected, organization)
}

func TestOrganizationService_Update(t *testing.T) {
	httpClient, mux, server := testServer()
	defer server.Close()

	mux.HandleFunc("/api/0/organizations/badly-misnamed/", func(w http.ResponseWriter, r *http.Request) {
		assertMethod(t, "PUT", r)
		assertPostJSON(t, map[string]interface{}{
			"name": "Impeccably Designated",
			"slug": "impeccably-designated",
		}, r)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `{
			"name": "Impeccably Designated",
			"slug": "impeccably-designated",
			"id": "2"
		}`)
	})

	client := NewClient(httpClient, nil, "")
	params := &UpdateOrganizationParams{
		Name: "Impeccably Designated",
		Slug: "impeccably-designated",
	}
	organization, _, err := client.Organizations.Update("badly-misnamed", params)
	assert.NoError(t, err)
	expected := &Organization{
		ID:   "2",
		Name: "Impeccably Designated",
		Slug: "impeccably-designated",
	}
	assert.Equal(t, expected, organization)
}
<|endoftext|>


<commit_before>package handlers_test

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	log "github.com/Sirupsen/logrus"
	"github.com/jrzimmerman/bestrida-server-go/handlers"
	strava "github.com/strava/go.strava"
)

func TestGetAthleteByIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var a *strava.AthleteDetailed
	if err := json.NewDecoder(rec.Body).Decode(&a); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.WithField("Athlete ID", a.Id).Info("Athlete returned from Strava")

	if a.Id != int64(id) {
		t.Errorf("unexpected athlete")
	}
}

func TestGetAthleteByIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetAthleteByIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetFriendsByUserIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var as *[]strava.AthleteSummary
	if err := json.NewDecoder(rec.Body).Decode(&as); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.Info("Athlete friends returned from Strava")
}

func TestGetFriendsByUserIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetFriendsByUserIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetSegmentsByUserIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var ss *[]strava.SegmentSummary
	if err := json.NewDecoder(rec.Body).Decode(&ss); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.Info("Athlete segments returned from Strava")
}

func TestGetSegmentsByUserIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetSegmentsByUserIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}
<commit_msg>add comments<commit_after>package handlers_test

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	log "github.com/Sirupsen/logrus"
	"github.com/jrzimmerman/bestrida-server-go/handlers"
	strava "github.com/strava/go.strava"
)

func TestGetAthleteByIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var a *strava.AthleteDetailed
	if err := json.NewDecoder(rec.Body).Decode(&a); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.WithField("Athlete ID", a.Id).Info("Athlete returned from Strava")

	if a.Id != int64(id) {
		t.Errorf("unexpected athlete")
	}
}

func TestGetAthleteByIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetAthleteByIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetFriendsByUserIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var as *[]strava.AthleteSummary
	if err := json.NewDecoder(rec.Body).Decode(&as); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.Info("Athlete friends returned from Strava")
}

func TestGetFriendsByUserIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetFriendsByUserIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetSegmentsByUserIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var ss *[]strava.SegmentSummary
	if err := json.NewDecoder(rec.Body).Decode(&ss); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.Info("Athlete segments returned from Strava")
}

// TestGetSegmentsByUserIDFromStravaFailureURL will test retrieving a user from strava with a bad athlete ID
func TestGetSegmentsByUserIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

// TestGetSegmentsByUserIDFromStravaFailureID will test retrieving a user from strava with a bad athlete ID
func TestGetSegmentsByUserIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}
<|endoftext|>