<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// More information about Google Distance Matrix API is available on
// https://developers.google.com/maps/documentation/distancematrix/

package maps

// Mode is for specifying travel mode.
type Mode string

// Avoid is for specifying routes that avoid certain features.
type Avoid string

// Units specifies which units system to return human readable results in.
type Units string

// TransitMode is for specifying a transit mode for a request
type TransitMode string

// TransitRoutingPreference biases which routes are returned
type TransitRoutingPreference string

// Travel mode preferences.
const (
	TravelModeDriving   = Mode("driving")
	TravelModeWalking   = Mode("walking")
	TravelModeBicycling = Mode("bicycling")
	TravelModeTransit   = Mode("transit")
)

// Features to avoid.
const (
	AvoidTolls    = Avoid("tolls")
	AvoidHighways = Avoid("highways")
	AvoidFerries  = Avoid("ferries")
)

// Units to use on human readable distances.
const (
	UnitsMetric   = Units("metric")
	UnitsImperial = Units("imperial")
)

// Transit mode of directions or distance matrix request.
const (
	TransitModeBus    = TransitMode("bus")
	TransitModeSubway = TransitMode("subway")
	TransitModeTrain  = TransitMode("train")
	TransitModeTram   = TransitMode("tram")
	TransitModeRail   = TransitMode("rail")
)

// Transit Routing preferences for transit mode requests
const (
	TransitRoutingPreferenceLessWalking    = TransitRoutingPreference("less_walking")
	TransitRoutingPreferenceFewerTransfers = TransitRoutingPreference("fewer_transfers")
)

// Distance is the API representation for a distance between two points.
type Distance struct {
	// HumanReadable is the human friendly distance. This is rounded and in an appropriate unit for the
	// request. The units can be overriden with a request parameter.
	HumanReadable string `json:"text"`
	// Meters is the numeric distance, always in meters. This is intended to be used only in
	// algorithmic situations, e.g. sorting results by some user specified metric.
	Meters int `json:"value"`
}

// PriceLevel is the Price Levels for Places API
type PriceLevel string

// Price Levels for the Places API
const (
	PriceLevelFree          = PriceLevel("0")
	PriceLevelInexpensive   = PriceLevel("1")
	PriceLevelModerate      = PriceLevel("2")
	PriceLevelExpensive     = PriceLevel("3")
	PriceLevelVeryExpensive = PriceLevel("4")
)

// OpeningHours describes the opening hours for a Place Details result.
type OpeningHours struct {
	// OpenNow is a boolean value indicating if the place is open at the current time. Please note, this field will be null if it isn't present in the response.
	OpenNow *bool `json:"open_now"`
	// Periods is an array of opening periods covering seven days, starting from Sunday, in chronological order.
	Periods []OpeningHoursPeriod `json:"periods"`
	// weekdayText is an array of seven strings representing the formatted opening hours for each day of the week, for example "Monday: 8:30 am – 5:30 pm".
	WeekdayText []string `json:"weekday_text"`
	// PermanentlyClosed indicates that the place has permanently shut down. Please note, this field will be null if it isn't present in the response.
	PermanentlyClosed *bool `json:"permanently_closed"`
}

// OpeningHoursPeriod is a single OpeningHours day describing when the place opens and closes.
type OpeningHoursPeriod struct {
	// Open is when the place opens.
	Open OpeningHoursOpenClose `json:"open"`
	// Close is when the place closes.
	Close OpeningHoursOpenClose `json:"close"`
}

// OpeningHoursOpenClose describes when the place is open.
type OpeningHoursOpenClose struct {
	// Day is a number from 0–6, corresponding to the days of the week, starting on Sunday. For example, 2 means Tuesday.
	Day int `json:"day"`
	// Time contains a time of day in 24-hour hhmm format. Values are in the range 0000–2359. The time will be reported in the place’s time zone.
	Time string `json:"time"`
}

// Photo describes a photo available with a Search Result.
type Photo struct {
	// PhotoReference is used to identify the photo when you perform a Photo request.
	PhotoReference string `json:"photo_reference"`
	// Height is the maximum height of the image.
	Height int
	// Width is the maximum width of the image.
	Width int
	// htmlAttributions contains any required attributions.
	HTMLAttributions []string `json:"html_attributions"`
}
<commit_msg>Adding JSON tags and typing Day appropriately.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// More information about Google Distance Matrix API is available on
// https://developers.google.com/maps/documentation/distancematrix/

package maps

import "time"

// Mode is for specifying travel mode.
type Mode string

// Avoid is for specifying routes that avoid certain features.
type Avoid string

// Units specifies which units system to return human readable results in.
type Units string

// TransitMode is for specifying a transit mode for a request
type TransitMode string

// TransitRoutingPreference biases which routes are returned
type TransitRoutingPreference string

// Travel mode preferences.
const (
	TravelModeDriving   = Mode("driving")
	TravelModeWalking   = Mode("walking")
	TravelModeBicycling = Mode("bicycling")
	TravelModeTransit   = Mode("transit")
)

// Features to avoid.
const (
	AvoidTolls    = Avoid("tolls")
	AvoidHighways = Avoid("highways")
	AvoidFerries  = Avoid("ferries")
)

// Units to use on human readable distances.
const (
	UnitsMetric   = Units("metric")
	UnitsImperial = Units("imperial")
)

// Transit mode of directions or distance matrix request.
const (
	TransitModeBus    = TransitMode("bus")
	TransitModeSubway = TransitMode("subway")
	TransitModeTrain  = TransitMode("train")
	TransitModeTram   = TransitMode("tram")
	TransitModeRail   = TransitMode("rail")
)

// Transit Routing preferences for transit mode requests
const (
	TransitRoutingPreferenceLessWalking    = TransitRoutingPreference("less_walking")
	TransitRoutingPreferenceFewerTransfers = TransitRoutingPreference("fewer_transfers")
)

// Distance is the API representation for a distance between two points.
type Distance struct {
	// HumanReadable is the human friendly distance. This is rounded and in an appropriate unit for the
	// request. The units can be overriden with a request parameter.
	HumanReadable string `json:"text"`
	// Meters is the numeric distance, always in meters. This is intended to be used only in
	// algorithmic situations, e.g. sorting results by some user specified metric.
	Meters int `json:"value"`
}

// PriceLevel is the Price Levels for Places API
type PriceLevel string

// Price Levels for the Places API
const (
	PriceLevelFree          = PriceLevel("0")
	PriceLevelInexpensive   = PriceLevel("1")
	PriceLevelModerate      = PriceLevel("2")
	PriceLevelExpensive     = PriceLevel("3")
	PriceLevelVeryExpensive = PriceLevel("4")
)

// OpeningHours describes the opening hours for a Place Details result.
type OpeningHours struct {
	// OpenNow is a boolean value indicating if the place is open at the current time. Please note, this field will be null if it isn't present in the response.
	OpenNow *bool `json:"open_now"`
	// Periods is an array of opening periods covering seven days, starting from Sunday, in chronological order.
	Periods []OpeningHoursPeriod `json:"periods"`
	// weekdayText is an array of seven strings representing the formatted opening hours for each day of the week, for example "Monday: 8:30 am – 5:30 pm".
	WeekdayText []string `json:"weekday_text"`
	// PermanentlyClosed indicates that the place has permanently shut down. Please note, this field will be null if it isn't present in the response.
	PermanentlyClosed *bool `json:"permanently_closed"`
}

// OpeningHoursPeriod is a single OpeningHours day describing when the place opens and closes.
type OpeningHoursPeriod struct {
	// Open is when the place opens.
	Open OpeningHoursOpenClose `json:"open"`
	// Close is when the place closes.
	Close OpeningHoursOpenClose `json:"close"`
}

// OpeningHoursOpenClose describes when the place is open.
type OpeningHoursOpenClose struct {
	// Day is a number from 0–6, corresponding to the days of the week, starting on Sunday. For example, 2 means Tuesday.
	Day time.Weekday `json:"day"`
	// Time contains a time of day in 24-hour hhmm format. Values are in the range 0000–2359. The time will be reported in the place’s time zone.
	Time string `json:"time"`
}

// Photo describes a photo available with a Search Result.
type Photo struct {
	// PhotoReference is used to identify the photo when you perform a Photo request.
	PhotoReference string `json:"photo_reference"`
	// Height is the maximum height of the image.
	Height int `json:"height"`
	// Width is the maximum width of the image.
	Width int `json:"width"`
	// htmlAttributions contains any required attributions.
	HTMLAttributions []string `json:"html_attributions"`
}
<|endoftext|>


<commit_before>package vsolver

type ProjectName string

type Solver interface {
	Solve(root ProjectInfo, toUpgrade []ProjectName) Result
}

type ProjectAtom struct {
	Name    ProjectName
	Version Version
}

var emptyProjectAtom ProjectAtom

type ProjectDep struct {
	Name       ProjectName
	Constraint Constraint
}

type Dependency struct {
	Depender ProjectAtom
	Dep      ProjectDep
}

// ProjectInfo holds the spec and lock information for a given ProjectAtom
type ProjectInfo struct {
	pa ProjectAtom
	Manifest
	Lock
}

// LockedProject is a single project entry from a lock file. It expresses the
// project's name, one or both of version and underlying revision, the URI for
// accessing it, and the path at which it should be placed within a vendor
// directory.
//
// TODO note that sometime soon, we also plan to allow pkgs. this'll change
type LockedProject struct {
	n         ProjectName
	v         UnpairedVersion
	r         Revision
	path, uri string
}

// NewLockedProject creates a new LockedProject struct with a given name,
// version, upstream repository URI, and on-disk path at which the project is to
// be checked out under a vendor directory.
//
// Note that passing a nil version will cause a panic. This is a correctness
// measure to ensure that the solver is never exposed to a version-less lock
// entry. Such a case would be meaningless - the solver would have no choice but
// to simply dismiss that project. By creating a hard failure case via panic
// instead, we are trying to avoid inflicting the resulting pain on the user by
// instead forcing a decision on the Analyzer implementation.
func NewLockedProject(n ProjectName, v Version, uri, path string) LockedProject {
	if v == nil {
		panic("must provide a non-nil version to create a LockedProject")
	}

	lp := LockedProject{
		n:    n,
		uri:  uri,
		path: path,
	}

	switch tv := v.(type) {
	case Revision:
		lp.r = tv
	case branchVersion:
		lp.v = tv
	case semVersion:
		lp.v = tv
	case plainVersion:
		lp.v = tv
	case versionPair:
		lp.r = tv.r
		lp.v = tv.v
	}

	return lp
}

// Name returns the name of the locked project.
func (lp LockedProject) Name() ProjectName {
	return lp.n
}

// Version assembles together whatever version and/or revision data is
// available into a single Version.
func (lp LockedProject) Version() Version {
	if lp.r == "" {
		return lp.v
	}

	if lp.v == nil {
		return lp.r
	}

	return lp.v.Is(lp.r)
}

// URI returns the upstream URI of the locked project.
func (lp LockedProject) URI() string {
	return lp.uri
}

// Path returns the path relative to the vendor directory to which the locked
// project should be checked out.
func (lp LockedProject) Path() string {
	return lp.path
}

// TODO undecided on whether having a struct lke this is good/helpful
// PI (Project Info) holds the two key pieces of information that an analyzer
// can produce about a project: a Manifest, describing its intended dependencies
// and certain governing configuration
//type PI struct {
//Manifest
//Lock
////Extra interface{} // TODO allow analyzers to tuck data away if they want
//}

// Manifest represents the data from a manifest file (or however the
// implementing tool chooses to store it) at a particular version that is
// relevant to the satisfiability solving process:
//
// - A list of dependencies: project name, and a constraint
// - A list of development-time dependencies (e.g. for testing - only
// the root project's are incorporated)
//
// Finding a solution that satisfies the constraints expressed by all of these
// dependencies (and those from all other projects, transitively), is what the
// solver does.
//
// Note that vsolver does perform static analysis on all projects' codebases;
// if dependencies it finds through that analysis are missing from what the
// Manifest lists, it is considered an error that will eliminate that version
// from consideration in the solving algorithm.
type Manifest interface {
	Name() ProjectName
	GetDependencies() []ProjectDep
	GetDevDependencies() []ProjectDep
}

// Lock represents data from a lock file (or however the implementing tool
// chooses to store it) at a particular version that is relevant to the
// satisfiability solving process.
//
// In general, the information produced by vsolver on finding a successful
// solution is all that would be necessary to constitute a lock file, though
// tools can include whatever other information they want in their storage.
type Lock interface {
	// Indicates the version of the solver used to generate this lock data
	//SolverVersion() string

	// The hash of inputs to vsolver that resulted in this lock data
	InputHash() string

	// Projects returns the list of LockedProjects contained in the lock data.
	Projects() []LockedProject
}
<commit_msg>Add Simple{Lock,Manifest} for ephemeral metadata<commit_after>package vsolver

type ProjectName string

type Solver interface {
	Solve(root ProjectInfo, toUpgrade []ProjectName) Result
}

type ProjectAtom struct {
	Name    ProjectName
	Version Version
}

var emptyProjectAtom ProjectAtom

type ProjectDep struct {
	Name       ProjectName
	Constraint Constraint
}

type Dependency struct {
	Depender ProjectAtom
	Dep      ProjectDep
}

// ProjectInfo holds the spec and lock information for a given ProjectAtom
type ProjectInfo struct {
	pa ProjectAtom
	Manifest
	Lock
}

// LockedProject is a single project entry from a lock file. It expresses the
// project's name, one or both of version and underlying revision, the URI for
// accessing it, and the path at which it should be placed within a vendor
// directory.
//
// TODO note that sometime soon, we also plan to allow pkgs. this'll change
type LockedProject struct {
	n         ProjectName
	v         UnpairedVersion
	r         Revision
	path, uri string
}

// NewLockedProject creates a new LockedProject struct with a given name,
// version, upstream repository URI, and on-disk path at which the project is to
// be checked out under a vendor directory.
//
// Note that passing a nil version will cause a panic. This is a correctness
// measure to ensure that the solver is never exposed to a version-less lock
// entry. Such a case would be meaningless - the solver would have no choice but
// to simply dismiss that project. By creating a hard failure case via panic
// instead, we are trying to avoid inflicting the resulting pain on the user by
// instead forcing a decision on the Analyzer implementation.
func NewLockedProject(n ProjectName, v Version, uri, path string) LockedProject {
	if v == nil {
		panic("must provide a non-nil version to create a LockedProject")
	}

	lp := LockedProject{
		n:    n,
		uri:  uri,
		path: path,
	}

	switch tv := v.(type) {
	case Revision:
		lp.r = tv
	case branchVersion:
		lp.v = tv
	case semVersion:
		lp.v = tv
	case plainVersion:
		lp.v = tv
	case versionPair:
		lp.r = tv.r
		lp.v = tv.v
	}

	return lp
}

// Name returns the name of the locked project.
func (lp LockedProject) Name() ProjectName {
	return lp.n
}

// Version assembles together whatever version and/or revision data is
// available into a single Version.
func (lp LockedProject) Version() Version {
	if lp.r == "" {
		return lp.v
	}

	if lp.v == nil {
		return lp.r
	}

	return lp.v.Is(lp.r)
}

// URI returns the upstream URI of the locked project.
func (lp LockedProject) URI() string {
	return lp.uri
}

// Path returns the path relative to the vendor directory to which the locked
// project should be checked out.
func (lp LockedProject) Path() string {
	return lp.path
}

// TODO undecided on whether having a struct lke this is good/helpful
// PI (Project Info) holds the two key pieces of information that an analyzer
// can produce about a project: a Manifest, describing its intended dependencies
// and certain governing configuration
//type PI struct {
//Manifest
//Lock
////Extra interface{} // TODO allow analyzers to tuck data away if they want
//}

// Manifest represents the data from a manifest file (or however the
// implementing tool chooses to store it) at a particular version that is
// relevant to the satisfiability solving process:
//
// - A list of dependencies: project name, and a constraint
// - A list of development-time dependencies (e.g. for testing - only
// the root project's are incorporated)
//
// Finding a solution that satisfies the constraints expressed by all of these
// dependencies (and those from all other projects, transitively), is what the
// solver does.
//
// Note that vsolver does perform static analysis on all projects' codebases;
// if dependencies it finds through that analysis are missing from what the
// Manifest lists, it is considered an error that will eliminate that version
// from consideration in the solving algorithm.
type Manifest interface {
	Name() ProjectName
	GetDependencies() []ProjectDep
	GetDevDependencies() []ProjectDep
}

// Lock represents data from a lock file (or however the implementing tool
// chooses to store it) at a particular version that is relevant to the
// satisfiability solving process.
//
// In general, the information produced by vsolver on finding a successful
// solution is all that would be necessary to constitute a lock file, though
// tools can include whatever other information they want in their storage.
type Lock interface {
	// Indicates the version of the solver used to generate this lock data
	//SolverVersion() string

	// The hash of inputs to vsolver that resulted in this lock data
	InputHash() string

	// Projects returns the list of LockedProjects contained in the lock data.
	Projects() []LockedProject
}

// SimpleLock is a helper for tools to simply enumerate lock data when they know
// that no hash, or other complex information, is available.
type SimpleLock []LockedProject

// InputHash always returns an empty string for SimpleLock. This makes it useless
// as a stable lock to be written to disk, but still useful for some ephemeral
// purposes.
func (SimpleLock) InputHash() string {
	return ""
}

// Projects returns the entire contents of the SimpleLock.
func (l SimpleLock) Projects() []LockedProject {
	return l
}

// SimpleManifest is a helper for tools to enumerate manifest data. It's
// intended for ephemeral manifests, such as those created by Analyzers on the
// fly.
type SimpleManifest struct {
	N  ProjectName
	P  []ProjectDep
	DP []ProjectDep
}

// Name returns the name of the project described by the manifest.
func (m SimpleManifest) Name() ProjectName {
	return m.N
}

// GetDependencies returns the project's dependencies.
func (m SimpleManifest) GetDependencies() []ProjectDep {
	return m.P
}

// GetDependencies returns the project's test dependencies.
func (m SimpleManifest) GetDevDependencies() []ProjectDep {
	return m.DP
}
<|endoftext|>


<commit_before>package ics

import (
	"encoding/base64"
	"errors"
	"io"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/MJKWoolnough/parser"
)

type Binary []byte

func (b *Binary) Decode(params map[string]string, data string) error {
	if params["ENCODING"] != "BASE64" {
		return ErrInvalidEncoding
	}
	cb, err := base64.StdEncoding.DecodeString(data)
	*b = cb
	return err
}

func (b *Binary) Encode(w io.Writer) {
	e := base64.NewEncoder(base64.StdEncoding, w)
	e.Write([]byte(*b))
	e.Close()
}

type Boolean bool

func (b *Boolean) Decode(params map[string]string, data string) error {
	cb, err := strconv.ParseBool(data)
	*b = cb
	return err
}

var (
	booleanTrue  = [...]byte{'T', 'R', 'U', 'E'}
	booleanFalse = [...]byte{'F', 'A', 'L', 'S', 'E'}
)

func (b *Boolean) Encode(w io.Writer) {
	if *b {
		w.Write(booleanTrue[:])
	} else {
		w.Write(booleanFalse[:])
	}
}

type CalAddress struct {
	URI
}

type Date struct {
	time.Time
}

func (d *Date) Decode(params map[string]string, data string) error {
	t, err := time.Parse("20060102", data)
	if err != nil {
		return err
	}
	d.Time = t
	return nil
}

func (d *Date) Encode(w io.Writer) {
	b := make([]byte, 0, 8)
	w.Write([]byte(d.AppendFormat(b, "20060102")))
}

type DateTime struct {
	time.Time
}

func (d *DateTime) Decode(params map[string]string, data string) error {
	if tz, ok := params["TZID"]; ok {
		l, err := time.LoadLocation(tz)
		if err != nil {
			return err
		}
		t, err := time.ParseInLocation("20060102T150405", data, l)
		if err != nil {
			return err
		}
		d.Time = t
	} else if len(data) > 0 && data[len(data)-1] == 'Z' {
		t, err := time.ParseInLocation("20060102T150405Z", data, time.UTC)
		if err != nil {
			return err
		}
		d.Time = t
	} else {
		t, err := time.ParseInLocation("20060102T150405", data, time.Local)
		if err != nil {
			return err
		}
		d.Time = t
	}
	return nil
}

func (d *DateTime) Encode(w io.Writer) {
	b := make([]byte, 0, 16)
	switch d.Location() {
	case time.UTC:
		b = d.AppendFormat(b, "20060102T150405Z")
	case time.Local:
		b = d.AppendFormat(b, "20060102T150405")
	default:
		b = d.AppendFormat(b, "20060102T150405")
	}
	w.Write(b)
}

type Duration struct {
	Negative                             bool
	Weeks, Days, Hours, Minutes, Seconds uint
}

func (d *Duration) Decode(params map[string]string, data string) error {
	t := parser.NewStringTokeniser(data)
	var neg bool
	if t.Accept("-") {
		neg = true
	} else {
		t.Accept("+")
	}
	if !t.Accept("P") {
		return ErrInvalidDuration
	}
	var level uint8
	for t.Peek() != -1 {
		t.Get()
		mode := t.AcceptRun("0123456789")
		num, err := strconv.ParseUint(t.Get(), 10, 0)
		if err != nil {
			return err
		}
		switch mode {
		case 'W':
			t.Accept("W")
			if t.Peek() != -1 {
				return ErrInvalidDuration
			}
			d.Weeks = num
			return nil
		case 'D':
			if level > 0 {
				return ErrInvalidDuration
			}
			t.Accept("D")
			d.Days = num
			level = 1
		case 'H':
			if level > 1 {
				return ErrInvalidDuration
			}
			t.Accept("H")
			d.Hours = num
			level = 2
		case 'M':
			if level > 2 {
				return ErrInvalidDuration
			}
			t.Accept("M")
			d.Minutes = num
			level = 3
		case 'S':
			if level > 3 {
				return ErrInvalidDuration
			}
			t.Accept("S")
			if t.Peek() != -1 {
				return ErrInvalidDuration
			}
			d.Seconds = num
		default:
			return ErrInvalidDuration
		}
	}
	if level == 0 {
		return ErrInvalidDuration
	}
	return nil
}

func itoa(i uint) []byte {
	if i == 0 {
		return []byte{'0'}
	}
	var digits [20]byte
	pos := 20
	for ; n > 0; n /= 10 {
		pos--
		digits[pos] = '0' + byte(n%10)
	}
	return digits[pos:]
}

func (d *Duration) Encode(w io.Writer) {
	data := make([]byte, 0, 64)
	if d.Negative {
		data = append(data, '-')
	}
	data = append(data, 'P')
	if d.Weeks != 0 {
		data = append(data, itoa(d.Weeks)...)
		data = append(data, 'W')
		return nil
	} else {
		if d.Days != 0 {
			data = append(data, itoa(d.Days)...)
			data = append(data, 'D')
		}
		if d.Days == 0 || (d.Hours != 0 || d.Minutes != 0 || d.Seconds != 0) {
			data = append(data, 'T')
			if d.Hours != 0 {
				data = append(data, itoa(d.Hours)...)
				data = append(data, 'H')
				if d.Minutes != 0 || d.Seconds != 0 {
					data = append(data, itoa(d.Minutes)...)
					data = append(data, 'M')
					if d.Seconds != 0 {
						data = append(data, itoa(d.Seconds)...)
						data = append(data, 'S')
					}
				}
			} else if d.Minutes != 0 {
				data = append(data, itoa(d.Minutes)...)
				data = append(data, 'M')
				if d.Seconds != 0 {
					data = append(data, itoa(d.Seconds)...)
					data = append(data, 'S')
				}
			} else {
				data = append(data, itoa(d.Seconds)...)
				data = append(data, 'S')
			}
		}
	}
	w.Write(data)
}

type Float float64

func (f *Float) Decode(params map[string]string, data string) error {
	cf, err := strconv.ParseFloat(data, 64)
	if err != nil {
		return err
	}
	*f = Float(cf)
	return nil
}

func (f *Float) Encode(w io.Writer) {
	w.Write([]byte(strconv.FormatFloat(float64(*f), 'f', 64)))
}

type Integer int32

func (i *Integer) Decode(params map[string]string, data string) error {
	ci, err := strconv.ParseInt(data, 10, 32)
	if err != nil {
		return err
	}
	*i = Integer(ci)
	return nil
}

func (i *Integer) Encode(w io.Writer) {
	w.Write([]byte(strconv.FormatInt(int64(*i), 10)))
}

type Period struct {
	Start, End DateTime
	Duration   Duration
}

func (p *Period) Decode(params map[string]string, data string) error {
	i := strings.IndexByte(data, '/')
	if i == -1 || len(data) == i+1 {
		return ErrInvalidPeriod
	}
	err := p.Start.Decode(params, data[:i])
	if err != nil {
		return err
	}
	if data[i+1] == 'P' || data[i+1] == '+' {
		return p.Duration.Decode(params, data[i+1:])
	}
	return p.End.Decode(params, data[i+1:])
}

func (p *Period) Encode(w io.Writer) {
	p.Start.Encode(w)
	w.Write([]byte{'/'})
	if p.End.IsZero() {
		p.Duration.Encode(w)
	} else {
		p.End.Encode(w)
	}
}

type Recur struct {
}

func (r *Recur) Decode(params map[string]string, data string) error {
	return nil
}

func (r *Recur) Encode(w io.Writer) {

}

type Text string

func (t *Text) Decode(params map[string]string, data string) error {
	t := parser.NewStringTokeniser(data)
	d := make([]byte, 0, len(data))
Loop:
	for {
		c := t.ExceptRun("\";:\\,^")
		d = append(d, t.Get()...)
		switch c {
		case -1:
			break Loop
		case '\\':
			t.Accept("\\")
			switch t.Except("") {
			case '\\':
				d = append(d, '\\')
			case ';':
				d = append(d, ';')
			case ',':
				d = append(d, ',')
			case 'N', 'n':
				d = append(d, '\n')
			default:
				return ErrInvalidText
			}
		case '^':
			t.Accept("^")
			switch c := t.Except(""); c {
			case 'n':
				d = append(d, '\n')
			case -1, '^':
				d = append(d, '^')
			case '\'':
				d = append(d, '"')
			default:
				d = append(d, '^', c)
			}
		default:
			return ErrInvalidText
		}
	}
	*t = Text(d)
	return nil
}

func (t *Text) Encode(w io.Writer) {
	d := make([]byte, 0, len(data)+256)
	for _, c := range *t {
		switch c {
		case '\\':
			d = append(d, '\\', '\\')
		case '\n':
			d = append(d, '\\', 'n')
		case ';':
			d = append(d, '\\', ';')
		case ',':
			d = append(d, '\\', ',')
		case '^':
			d = append(d, '^', '^')
		case '"':
			d = append(d, '^', '\'')
		default:
			d = append(d, c)
		}
	}
	w.Write(d)
}

type Time struct {
	time.Time
}

func (t *Time) Decode(params map[string]string, data string) error {
	if tz, ok := params["TZID"]; ok {
		l, err := time.LoadLocation(tz)
		if err != nil {
			return err
		}
		ct, err := time.ParseInLocation("150405", data, l)
		if err != nil {
			return err
		}
		t.Time = ct
	} else if len(data) > 0 && data[len(data)-1] == 'Z' {
		ct, err := time.ParseInLocation("150405Z", data, time.UTC)
		if err != nil {
			return err
		}
		t.Time = ct
	} else {
		ct, err := time.ParseInLocation("150405", data, time.Local)
		if err != nil {
			return err
		}
		t.Time = ct
	}
	return nil
}

func (t *Time) Encode(w io.Writer) {
	b := make([]byte, 0, 7)
	switch d.Location() {
	case time.UTC:
		b = d.AppendFormat(b, "150405Z")
	case time.Local:
		b = d.AppendFormat(b, "150405")
	default:
		b = d.AppendFormat(b, "150405")
	}
	w.Write(b)
}

type URI struct {
	url.URL
}

func (u *URI) Decode(params map[string]string, data string) error {
	cu, err := url.Parse(data)
	if err != nil {
		return err
	}
	u.URL = cu
	return nil
}

func (u *URI) Encode(w io.Writer) {
	w.Write([]byte(u.URL.String()))
}

type UTCOffset int

func (u *UTCOffset) Decode(params map[string]string, data string) error {
	return nil
}

func (u *UTCOffset) Encode(w io.Writer) {

}

// Errors
var (
	ErrInvalidEncoding = errors.New("invalid binary encoding")
	ErrInvalidPeriod   = errors.New("invalid period")
	ErrInvalidDuration = errors.New("invalid duration")
	ErrInvalidText     = errors.New("invalid encoded text")
)
<commit_msg>fixed compile-time errors<commit_after>package ics

import (
	"encoding/base64"
	"errors"
	"io"
	"net/url"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"

	"github.com/MJKWoolnough/parser"
)

type Binary []byte

func (b *Binary) Decode(params map[string]string, data string) error {
	if params["ENCODING"] != "BASE64" {
		return ErrInvalidEncoding
	}
	cb, err := base64.StdEncoding.DecodeString(data)
	*b = cb
	return err
}

func (b *Binary) Encode(w io.Writer) {
	e := base64.NewEncoder(base64.StdEncoding, w)
	e.Write([]byte(*b))
	e.Close()
}

type Boolean bool

func (b *Boolean) Decode(params map[string]string, data string) error {
	cb, err := strconv.ParseBool(data)
	*b = Boolean(cb)
	return err
}

var (
	booleanTrue  = [...]byte{'T', 'R', 'U', 'E'}
	booleanFalse = [...]byte{'F', 'A', 'L', 'S', 'E'}
)

func (b *Boolean) Encode(w io.Writer) {
	if *b {
		w.Write(booleanTrue[:])
	} else {
		w.Write(booleanFalse[:])
	}
}

type CalAddress struct {
	URI
}

type Date struct {
	time.Time
}

func (d *Date) Decode(params map[string]string, data string) error {
	t, err := time.Parse("20060102", data)
	if err != nil {
		return err
	}
	d.Time = t
	return nil
}

func (d *Date) Encode(w io.Writer) {
	b := make([]byte, 0, 8)
	w.Write([]byte(d.AppendFormat(b, "20060102")))
}

type DateTime struct {
	time.Time
}

func (d *DateTime) Decode(params map[string]string, data string) error {
	if tz, ok := params["TZID"]; ok {
		l, err := time.LoadLocation(tz)
		if err != nil {
			return err
		}
		t, err := time.ParseInLocation("20060102T150405", data, l)
		if err != nil {
			return err
		}
		d.Time = t
	} else if len(data) > 0 && data[len(data)-1] == 'Z' {
		t, err := time.ParseInLocation("20060102T150405Z", data, time.UTC)
		if err != nil {
			return err
		}
		d.Time = t
	} else {
		t, err := time.ParseInLocation("20060102T150405", data, time.Local)
		if err != nil {
			return err
		}
		d.Time = t
	}
	return nil
}

func (d *DateTime) Encode(w io.Writer) {
	b := make([]byte, 0, 16)
	switch d.Location() {
	case time.UTC:
		b = d.AppendFormat(b, "20060102T150405Z")
	case time.Local:
		b = d.AppendFormat(b, "20060102T150405")
	default:
		b = d.AppendFormat(b, "20060102T150405")
	}
	w.Write(b)
}

type Duration struct {
	Negative                             bool
	Weeks, Days, Hours, Minutes, Seconds uint
}

func (d *Duration) Decode(params map[string]string, data string) error {
	t := parser.NewStringTokeniser(data)
	if t.Accept("-") {
		d.Negative = true
	} else {
		t.Accept("+")
	}
	if !t.Accept("P") {
		return ErrInvalidDuration
	}
	var level uint8
	for t.Peek() != -1 {
		t.Get()
		mode := t.AcceptRun("0123456789")
		n, err := strconv.ParseUint(t.Get(), 10, 0)
		num := uint(n)
		if err != nil {
			return err
		}
		switch mode {
		case 'W':
			t.Accept("W")
			if t.Peek() != -1 {
				return ErrInvalidDuration
			}
			d.Weeks = num
			return nil
		case 'D':
			if level > 0 {
				return ErrInvalidDuration
			}
			t.Accept("D")
			d.Days = num
			level = 1
		case 'H':
			if level > 1 {
				return ErrInvalidDuration
			}
			t.Accept("H")
			d.Hours = num
			level = 2
		case 'M':
			if level > 2 {
				return ErrInvalidDuration
			}
			t.Accept("M")
			d.Minutes = num
			level = 3
		case 'S':
			if level > 3 {
				return ErrInvalidDuration
			}
			t.Accept("S")
			if t.Peek() != -1 {
				return ErrInvalidDuration
			}
			d.Seconds = num
		default:
			return ErrInvalidDuration
		}
	}
	if level == 0 {
		return ErrInvalidDuration
	}
	return nil
}

func itoa(n uint) []byte {
	if n == 0 {
		return []byte{'0'}
	}
	var digits [20]byte
	pos := 20
	for ; n > 0; n /= 10 {
		pos--
		digits[pos] = '0' + byte(n%10)
	}
	return digits[pos:]
}

func (d *Duration) Encode(w io.Writer) {
	data := make([]byte, 0, 64)
	if d.Negative {
		data = append(data, '-')
	}
	data = append(data, 'P')
	if d.Weeks != 0 {
		data = append(data, itoa(d.Weeks)...)
		data = append(data, 'W')
	} else {
		if d.Days != 0 {
			data = append(data, itoa(d.Days)...)
			data = append(data, 'D')
		}
		if d.Days == 0 || (d.Hours != 0 || d.Minutes != 0 || d.Seconds != 0) {
			data = append(data, 'T')
			if d.Hours != 0 {
				data = append(data, itoa(d.Hours)...)
				data = append(data, 'H')
				if d.Minutes != 0 || d.Seconds != 0 {
					data = append(data, itoa(d.Minutes)...)
					data = append(data, 'M')
					if d.Seconds != 0 {
						data = append(data, itoa(d.Seconds)...)
						data = append(data, 'S')
					}
				}
			} else if d.Minutes != 0 {
				data = append(data, itoa(d.Minutes)...)
				data = append(data, 'M')
				if d.Seconds != 0 {
					data = append(data, itoa(d.Seconds)...)
					data = append(data, 'S')
				}
			} else {
				data = append(data, itoa(d.Seconds)...)
				data = append(data, 'S')
			}
		}
	}
	w.Write(data)
}

type Float float64

func (f *Float) Decode(params map[string]string, data string) error {
	cf, err := strconv.ParseFloat(data, 64)
	if err != nil {
		return err
	}
	*f = Float(cf)
	return nil
}

func (f *Float) Encode(w io.Writer) {
	w.Write([]byte(strconv.FormatFloat(float64(*f), 'f', -1, 64)))
}

type Integer int32

func (i *Integer) Decode(params map[string]string, data string) error {
	ci, err := strconv.ParseInt(data, 10, 32)
	if err != nil {
		return err
	}
	*i = Integer(ci)
	return nil
}

func (i *Integer) Encode(w io.Writer) {
	w.Write([]byte(strconv.FormatInt(int64(*i), 10)))
}

type Period struct {
	Start, End DateTime
	Duration   Duration
}

func (p *Period) Decode(params map[string]string, data string) error {
	i := strings.IndexByte(data, '/')
	if i == -1 || len(data) == i+1 {
		return ErrInvalidPeriod
	}
	err := p.Start.Decode(params, data[:i])
	if err != nil {
		return err
	}
	if data[i+1] == 'P' || data[i+1] == '+' {
		return p.Duration.Decode(params, data[i+1:])
	}
	return p.End.Decode(params, data[i+1:])
}

func (p *Period) Encode(w io.Writer) {
	p.Start.Encode(w)
	w.Write([]byte{'/'})
	if p.End.IsZero() {
		p.Duration.Encode(w)
	} else {
		p.End.Encode(w)
	}
}

type Recur struct {
}

func (r *Recur) Decode(params map[string]string, data string) error {
	return nil
}

func (r *Recur) Encode(w io.Writer) {

}

type Text string

func (t *Text) Decode(params map[string]string, data string) error {
	st := parser.NewStringTokeniser(data)
	d := make([]byte, 0, len(data))
	ru := make([]byte, 4)
Loop:
	for {
		c := st.ExceptRun("\";:\\,^")
		d = append(d, st.Get()...)
		switch c {
		case -1:
			break Loop
		case '\\':
			st.Accept("\\")
			switch st.Peek() {
			case '\\':
				d = append(d, '\\')
			case ';':
				d = append(d, ';')
			case ',':
				d = append(d, ',')
			case 'N', 'n':
				d = append(d, '\n')
			default:
				return ErrInvalidText
			}
			st.Except("")
		case '^':
			st.Accept("^")
			switch c := st.Peek(); c {
			case 'n':
				d = append(d, '\n')
			case -1, '^':
				d = append(d, '^')
			case '\'':
				d = append(d, '"')
			default:
				d = append(d, '^')
				l := utf8.EncodeRune(ru, c)
				d = append(d, ru[:l]...)
			}
			st.Except("")
		default:
			return ErrInvalidText
		}
	}
	*t = Text(d)
	return nil
}

func (t *Text) Encode(w io.Writer) {
	d := make([]byte, 0, len(*t)+256)
	ru := make([]byte, 4)
	for _, c := range *t {
		switch c {
		case '\\':
			d = append(d, '\\', '\\')
		case '\n':
			d = append(d, '\\', 'n')
		case ';':
			d = append(d, '\\', ';')
		case ',':
			d = append(d, '\\', ',')
		case '^':
			d = append(d, '^', '^')
		case '"':
			d = append(d, '^', '\'')
		default:
			d = append(d, '^')
			l := utf8.EncodeRune(ru, c)
			d = append(d, ru[:l]...)
		}
	}
	w.Write(d)
}

type Time struct {
	time.Time
}

func (t *Time) Decode(params map[string]string, data string) error {
	if tz, ok := params["TZID"]; ok {
		l, err := time.LoadLocation(tz)
		if err != nil {
			return err
		}
		ct, err := time.ParseInLocation("150405", data, l)
		if err != nil {
			return err
		}
		t.Time = ct
	} else if len(data) > 0 && data[len(data)-1] == 'Z' {
		ct, err := time.ParseInLocation("150405Z", data, time.UTC)
		if err != nil {
			return err
		}
		t.Time = ct
	} else {
		ct, err := time.ParseInLocation("150405", data, time.Local)
		if err != nil {
			return err
		}
		t.Time = ct
	}
	return nil
}

func (t *Time) Encode(w io.Writer) {
	b := make([]byte, 0, 7)
	switch t.Location() {
	case time.UTC:
		b = t.AppendFormat(b, "150405Z")
	case time.Local:
		b = t.AppendFormat(b, "150405")
	default:
		b = t.AppendFormat(b, "150405")
	}
	w.Write(b)
}

type URI struct {
	url.URL
}

func (u *URI) Decode(params map[string]string, data string) error {
	cu, err := url.Parse(data)
	if err != nil {
		return err
	}
	u.URL = *cu
	return nil
}

func (u *URI) Encode(w io.Writer) {
	w.Write([]byte(u.URL.String()))
}

type UTCOffset int

func (u *UTCOffset) Decode(params map[string]string, data string) error {
	return nil
}

func (u *UTCOffset) Encode(w io.Writer) {

}

// Errors
var (
	ErrInvalidEncoding = errors.New("invalid binary encoding")
	ErrInvalidPeriod   = errors.New("invalid period")
	ErrInvalidDuration = errors.New("invalid duration")
	ErrInvalidText     = errors.New("invalid encoded text")
)
<|endoftext|>


<commit_before>// Discordgo - Discord bindings for Go
// Available at https://github.com/bwmarrin/discordgo

// Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file contains custom types, currently only a timestamp wrapper.

package discordgo

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// Timestamp stores a timestamp, as sent by the Discord API.
type Timestamp string

// Parse parses a timestamp string into a time.Time object.
// The only time this can fail is if Discord changes their timestamp format.
func (t Timestamp) Parse() (time.Time, error) {
	return time.Parse(time.RFC3339, string(t))
}

// RESTError stores error information about a request with a bad response code.
// Message is not always present, there are cases where api calls can fail
// without returning a json message.
type RESTError struct {
	Request      *http.Request
	Response     *http.Response
	ResponseBody []byte

	Message *APIErrorMessage // Message may be nil.
}

func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTError {
	restErr := &RESTError{
		Request:      req,
		Response:     resp,
		ResponseBody: body,
	}

	// Attempt to decode the error and assume no message was provided if it fails
	var msg *APIErrorMessage
	err := json.Unmarshal(body, &msg)
	if err == nil {
		restErr.Message = msg
	}

	return restErr
}

func (r RESTError) Error() string {
	return fmt.Sprintf("HTTP %s, %s", r.Response.Status, r.ResponseBody)
}

// IDSlice Is a slice of snowflake id's that properly marshals and unmarshals the way discord expects them to
// They unmarshal from string arrays and marshals back to string arrays
type IDSlice []int64

func (ids *IDSlice) UnmarshalJSON(data []byte) error {
	if len(data) < 2 {
		return nil
	}

	// Split and strip away "[" "]"
	split := strings.Split(string(data[1:len(data)-1]), ",")
	*ids = make([]int64, len(split))
	for i, s := range split {
		s = strings.TrimSpace(s)
		if len(s) < 3 {
			// Empty or invalid
			continue
		}

		// Strip away quotes and parse
		parsed, err := strconv.ParseInt(s[1:len(s)-1], 10, 64)
		if err != nil {
			return err
		}
		(*ids)[i] = parsed
	}

	return nil
}

func (ids IDSlice) MarshalJSON() ([]byte, error) {
	// Capacity:
	// 2 brackets
	// each id is:
	//    18 characters currently, but 1 extra added for the future,
	//    1 comma
	//    2 quotes
	outPut := make([]byte, 1, 2+(len(ids)*22))
	outPut[0] = '['

	for i, id := range ids {
		if i != 0 {
			outPut = append(outPut, '"', ',', '"')
		} else {
			outPut = append(outPut, '"')
		}
		outPut = append(outPut, []byte(strconv.FormatInt(id, 10))...)
	}

	outPut = append(outPut, '"', ']')
	fmt.Println(string(outPut))
	return outPut, nil
}
<commit_msg>Remove debug logging in IDSlice.MarshalJson<commit_after>// Discordgo - Discord bindings for Go
// Available at https://github.com/bwmarrin/discordgo

// Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file contains custom types, currently only a timestamp wrapper.

package discordgo

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// Timestamp stores a timestamp, as sent by the Discord API.
type Timestamp string

// Parse parses a timestamp string into a time.Time object.
// The only time this can fail is if Discord changes their timestamp format.
func (t Timestamp) Parse() (time.Time, error) {
	return time.Parse(time.RFC3339, string(t))
}

// RESTError stores error information about a request with a bad response code.
// Message is not always present, there are cases where api calls can fail
// without returning a json message.
type RESTError struct {
	Request      *http.Request
	Response     *http.Response
	ResponseBody []byte

	Message *APIErrorMessage // Message may be nil.
}

func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTError {
	restErr := &RESTError{
		Request:      req,
		Response:     resp,
		ResponseBody: body,
	}

	// Attempt to decode the error and assume no message was provided if it fails
	var msg *APIErrorMessage
	err := json.Unmarshal(body, &msg)
	if err == nil {
		restErr.Message = msg
	}

	return restErr
}

func (r RESTError) Error() string {
	return fmt.Sprintf("HTTP %s, %s", r.Response.Status, r.ResponseBody)
}

// IDSlice Is a slice of snowflake id's that properly marshals and unmarshals the way discord expects them to
// They unmarshal from string arrays and marshals back to string arrays
type IDSlice []int64

func (ids *IDSlice) UnmarshalJSON(data []byte) error {
	if len(data) < 2 {
		return nil
	}

	// Split and strip away "[" "]"
	split := strings.Split(string(data[1:len(data)-1]), ",")
	*ids = make([]int64, len(split))
	for i, s := range split {
		s = strings.TrimSpace(s)
		if len(s) < 3 {
			// Empty or invalid
			continue
		}

		// Strip away quotes and parse
		parsed, err := strconv.ParseInt(s[1:len(s)-1], 10, 64)
		if err != nil {
			return err
		}
		(*ids)[i] = parsed
	}

	return nil
}

func (ids IDSlice) MarshalJSON() ([]byte, error) {
	// Capacity:
	// 2 brackets
	// each id is:
	//    18 characters currently, but 1 extra added for the future,
	//    1 comma
	//    2 quotes
	if len(ids) < 1 {
		return []byte("[]"), nil
	}

	outPut := make([]byte, 1, 2+(len(ids)*22))
	outPut[0] = '['

	for i, id := range ids {
		if i != 0 {
			outPut = append(outPut, '"', ',', '"')
		} else {
			outPut = append(outPut, '"')
		}
		outPut = append(outPut, []byte(strconv.FormatInt(id, 10))...)
	}

	outPut = append(outPut, '"', ']')
	return outPut, nil
}
<|endoftext|>


<commit_before>// Copyright 2013 The lime Authors.
// Use of this source code is governed by a 2-clause
// BSD-style license that can be found in the LICENSE file.

package sublime

import (
	"code.google.com/p/log4go"
	"fmt"
	"github.com/howeyc/fsnotify"
	"github.com/limetext/gopy/lib"
	"github.com/limetext/lime/backend"
	"github.com/limetext/lime/backend/render"
	"os"
	"path"
	"time"
)

func sublime_Console(tu *py.Tuple, kwargs *py.Dict) (py.Object, error) {
	if tu.Size() != 1 {
		return nil, fmt.Errorf("Unexpected argument count: %d", tu.Size())
	}
	if i, err := tu.GetItem(0); err != nil {
		return nil, err
	} else {
		log4go.Info("Python sez: %s", i)
	}
	return toPython(nil)
}

func sublime_set_timeout(tu *py.Tuple, kwargs *py.Dict) (py.Object, error) {
	var (
		pyarg py.Object
	)
	if tu.Size() != 2 {
		return nil, fmt.Errorf("Unexpected argument count: %d", tu.Size())
	}
	if i, err := tu.GetItem(0); err != nil {
		return nil, err
	} else {
		pyarg = i
	}
	if i, err := tu.GetItem(1); err != nil {
		return nil, err
	} else if v, err := fromPython(i); err != nil {
		return nil, err
	} else if v2, ok := v.(int); !ok {
		return nil, fmt.Errorf("Expected int not %s", i.Type())
	} else {
		pyarg.Incref()
		go func() {
			time.Sleep(time.Millisecond * time.Duration(v2))
			l := py.NewLock()
			defer l.Unlock()
			defer pyarg.Decref()
			if ret, err := pyarg.Base().CallFunctionObjArgs(); err != nil {
				log4go.Debug("Error in callback: %v", err)
			} else {
				ret.Decref()
			}
		}()
	}
	return toPython(nil)
}

func init() {
	sublime_methods = append(sublime_methods, py.Method{Name: "console", Func: sublime_Console}, py.Method{Name: "set_timeout", Func: sublime_set_timeout})
	backend.GetEditor()
	l := py.InitAndLock()
	defer l.Unlock()
	//	py.InitializeEx(false)
	m, err := py.InitModule("sublime", sublime_methods)
	if err != nil {
		panic(err)
	}

	type class struct {
		name string
		c    *py.Class
	}
	classes := []class{
		{"Region", &_regionClass},
		{"RegionSet", &_region_setClass},
		{"View", &_viewClass},
		{"Window", &_windowClass},
		{"Edit", &_editClass},
		{"Settings", &_settingsClass},
		{"WindowCommandGlue", &_windowCommandGlueClass},
		{"TextCommandGlue", &_textCommandGlueClass},
		{"ApplicationCommandGlue", &_applicationCommandGlueClass},
		{"OnQueryContextGlue", &_onQueryContextGlueClass},
		{"ViewEventGlue", &_viewEventGlueClass},
	}
	type constant struct {
		name     string
		constant int
	}
	constants := []constant{
		{"OP_EQUAL", int(backend.OpEqual)},
		{"OP_NOT_EQUAL", int(backend.OpNotEqual)},
		{"OP_REGEX_MATCH", int(backend.OpRegexMatch)},
		{"OP_NOT_REGEX_MATCH", int(backend.OpNotRegexMatch)},
		{"OP_REGEX_CONTAINS", int(backend.OpRegexContains)},
		{"OP_NOT_REGEX_CONTAINS", int(backend.OpNotRegexContains)},
		{"INHIBIT_WORD_COMPLETIONS", 0},
		{"INHIBIT_EXPLICIT_COMPLETIONS", 0},
		{"LITERAL", 0},
		{"IGNORECASE", 0},
		{"CLASS_WORD_START", 1},
		{"CLASS_WORD_END", 2},
		{"CLASS_PUNCTUATION_START", 4},
		{"CLASS_PUNCTUATION_END", 8},
		{"CLASS_SUB_WORD_START", 16},
		{"CLASS_SUB_WORD_END", 32},
		{"CLASS_LINE_START", 64},
		{"CLASS_LINE_END", 128},
		{"CLASS_EMPTY_LINE", 256},
		{"CLASS_MIDDLE_WORD", 512},
		{"CLASS_WORD_START_WITH_PUNCTUATION", 1024},
		{"CLASS_WORD_END_WITH_PUNCTUATION", 2048},
		{"CLASS_OPENING_PARENTHESIS", 4096},
		{"CLASS_CLOSING_PARENTHESIS", 8192},
		{"DRAW_EMPTY", int(render.DRAW_EMPTY)},
		{"HIDE_ON_MINIMAP", int(render.HIDE_ON_MINIMAP)},
		{"DRAW_EMPTY_AS_OVERWRITE", int(render.DRAW_EMPTY_AS_OVERWRITE)},
		{"DRAW_NO_FILL", int(render.DRAW_NO_FILL)},
		{"DRAW_NO_OUTLINE", int(render.DRAW_NO_OUTLINE)},
		{"DRAW_SOLID_UNDERLINE", int(render.DRAW_SOLID_UNDERLINE)},
		{"DRAW_STIPPLED_UNDERLINE", int(render.DRAW_STIPPLED_UNDERLINE)},
		{"DRAW_SQUIGGLY_UNDERLINE", int(render.DRAW_SQUIGGLY_UNDERLINE)},
		{"PERSISTENT", int(render.PERSISTENT)},
		{"HIDDEN", int(render.HIDDEN)},
	}

	for _, cl := range classes {
		c, err := cl.c.Create()
		if err != nil {
			panic(err)
		}
		if err := m.AddObject(cl.name, c); err != nil {
			panic(err)
		}
	}
	for _, c := range constants {
		if err := m.AddIntConstant(c.name, c.constant); err != nil {
			panic(err)
		}
	}
	py.AddToPath(backend.LIME_PACKAGES_PATH)
	py.AddToPath(backend.LIME_USER_PACKAGES_PATH)
	py.AddToPath(path.Join("..", "..", "backend", "sublime"))
}

func loadPlugin(p *backend.Plugin, m *py.Module) {
	fi := p.Get().([]os.FileInfo)
	for _, f := range fi {
		fn := f.Name()
		s, err := py.NewUnicode(path.Base(p.Name()) + "." + fn[:len(fn)-3])
		if err != nil {
			log4go.Error(err)
			return
		}
		if r, err := m.Base().CallMethodObjArgs("reload_plugin", s); err != nil {
			log4go.Error(err)
		} else if r != nil {
			r.Decref()
		}
	}
	p.LoadPackets()
	watch(backend.NewWatchedPackage(p))
}

var (
	watcher        *fsnotify.Watcher
	watchedPlugins map[string]*backend.WatchedPackage
)

func watch(plugin *backend.WatchedPackage) {
	log4go.Finest("Watch(%v)", plugin)
	if err := watcher.Watch(plugin.Name()); err != nil {
		log4go.Error("Could not watch plugin: %v", err)
	} else {
		watchedPlugins[plugin.Name()] = plugin
	}
}

func unWatch(name string) {
	if err := watcher.RemoveWatch(name); err != nil {
		log4go.Error("Couldn't unwatch file: %v", err)
	}
	log4go.Finest("UnWatch(%s)", name)
	delete(watchedPlugins, name)
}

func observePlugins(m *py.Module) {
	for {
		select {
		case ev := <-watcher.Event:
			if !(ev.IsModify() || ev.IsCreate()) {
				continue
			}
			if p, exist := watchedPlugins[path.Dir(ev.Name)]; exist {
				p.Reload()
				loadPlugin(p.Package().(*backend.Plugin), m)
			}
		case err := <-watcher.Error:
			log4go.Error("error:", err)
		}
	}
}

// TODO
func Init() {
	l := py.NewLock()
	defer l.Unlock()
	m, err := py.Import("sublime_plugin")
	if err != nil {
		panic(err)
	}
	sys, err := py.Import("sys")
	if err != nil {
		log4go.Debug(err)
	} else {
		defer sys.Decref()
	}

	watcher, err = fsnotify.NewWatcher()
	if err != nil {
		log4go.Error("Could not create watcher due to: %v", err)
	}
	watchedPlugins = make(map[string]*backend.WatchedPackage)
	go observePlugins(m)

	plugins := backend.ScanPlugins(backend.LIME_USER_PACKAGES_PATH, ".py")
	for _, p := range plugins {
		// TODO: add all plugins after supporting all commands
		if p.Name() == path.Join("..", "..", "3rdparty", "bundles", "Vintageous") {
			loadPlugin(p, m)
		}
	}
}
<commit_msg>backend/sublime: export CLASS_* constants now that we have them defined<commit_after>// Copyright 2013 The lime Authors.
// Use of this source code is governed by a 2-clause
// BSD-style license that can be found in the LICENSE file.

package sublime

import (
	"code.google.com/p/log4go"
	"fmt"
	"github.com/howeyc/fsnotify"
	"github.com/limetext/gopy/lib"
	"github.com/limetext/lime/backend"
	"github.com/limetext/lime/backend/render"
	"os"
	"path"
	"time"
)

func sublime_Console(tu *py.Tuple, kwargs *py.Dict) (py.Object, error) {
	if tu.Size() != 1 {
		return nil, fmt.Errorf("Unexpected argument count: %d", tu.Size())
	}
	if i, err := tu.GetItem(0); err != nil {
		return nil, err
	} else {
		log4go.Info("Python sez: %s", i)
	}
	return toPython(nil)
}

func sublime_set_timeout(tu *py.Tuple, kwargs *py.Dict) (py.Object, error) {
	var (
		pyarg py.Object
	)
	if tu.Size() != 2 {
		return nil, fmt.Errorf("Unexpected argument count: %d", tu.Size())
	}
	if i, err := tu.GetItem(0); err != nil {
		return nil, err
	} else {
		pyarg = i
	}
	if i, err := tu.GetItem(1); err != nil {
		return nil, err
	} else if v, err := fromPython(i); err != nil {
		return nil, err
	} else if v2, ok := v.(int); !ok {
		return nil, fmt.Errorf("Expected int not %s", i.Type())
	} else {
		pyarg.Incref()
		go func() {
			time.Sleep(time.Millisecond * time.Duration(v2))
			l := py.NewLock()
			defer l.Unlock()
			defer pyarg.Decref()
			if ret, err := pyarg.Base().CallFunctionObjArgs(); err != nil {
				log4go.Debug("Error in callback: %v", err)
			} else {
				ret.Decref()
			}
		}()
	}
	return toPython(nil)
}

func init() {
	sublime_methods = append(sublime_methods, py.Method{Name: "console", Func: sublime_Console}, py.Method{Name: "set_timeout", Func: sublime_set_timeout})
	backend.GetEditor()
	l := py.InitAndLock()
	defer l.Unlock()
	//	py.InitializeEx(false)
	m, err := py.InitModule("sublime", sublime_methods)
	if err != nil {
		panic(err)
	}

	type class struct {
		name string
		c    *py.Class
	}
	classes := []class{
		{"Region", &_regionClass},
		{"RegionSet", &_region_setClass},
		{"View", &_viewClass},
		{"Window", &_windowClass},
		{"Edit", &_editClass},
		{"Settings", &_settingsClass},
		{"WindowCommandGlue", &_windowCommandGlueClass},
		{"TextCommandGlue", &_textCommandGlueClass},
		{"ApplicationCommandGlue", &_applicationCommandGlueClass},
		{"OnQueryContextGlue", &_onQueryContextGlueClass},
		{"ViewEventGlue", &_viewEventGlueClass},
	}
	type constant struct {
		name     string
		constant int
	}
	constants := []constant{
		{"OP_EQUAL", int(backend.OpEqual)},
		{"OP_NOT_EQUAL", int(backend.OpNotEqual)},
		{"OP_REGEX_MATCH", int(backend.OpRegexMatch)},
		{"OP_NOT_REGEX_MATCH", int(backend.OpNotRegexMatch)},
		{"OP_REGEX_CONTAINS", int(backend.OpRegexContains)},
		{"OP_NOT_REGEX_CONTAINS", int(backend.OpNotRegexContains)},
		{"INHIBIT_WORD_COMPLETIONS", 0},
		{"INHIBIT_EXPLICIT_COMPLETIONS", 0},
		{"LITERAL", 0},
		{"IGNORECASE", 0},
		{"CLASS_WORD_START", int(backend.CLASS_WORD_START)},
		{"CLASS_WORD_END", int(backend.CLASS_WORD_END)},
		{"CLASS_PUNCTUATION_START", int(backend.CLASS_PUNCTUATION_START)},
		{"CLASS_PUNCTUATION_END", int(backend.CLASS_PUNCTUATION_END)},
		{"CLASS_SUB_WORD_START", int(backend.CLASS_SUB_WORD_START)},
		{"CLASS_SUB_WORD_END", int(backend.CLASS_SUB_WORD_END)},
		{"CLASS_LINE_START", int(backend.CLASS_LINE_START)},
		{"CLASS_LINE_END", int(backend.CLASS_LINE_END)},
		{"CLASS_EMPTY_LINE", int(backend.CLASS_EMPTY_LINE)},
		{"CLASS_MIDDLE_WORD", int(backend.CLASS_MIDDLE_WORD)},
		{"CLASS_WORD_START_WITH_PUNCTUATION", int(backend.CLASS_WORD_START_WITH_PUNCTUATION)},
		{"CLASS_WORD_END_WITH_PUNCTUATION", int(backend.CLASS_WORD_END_WITH_PUNCTUATION)},
		{"CLASS_OPENING_PARENTHESIS", int(backend.CLASS_OPENING_PARENTHESIS)},
		{"CLASS_CLOSING_PARENTHESIS", int(backend.CLASS_CLOSING_PARENTHESIS)},
		{"DRAW_EMPTY", int(render.DRAW_EMPTY)},
		{"HIDE_ON_MINIMAP", int(render.HIDE_ON_MINIMAP)},
		{"DRAW_EMPTY_AS_OVERWRITE", int(render.DRAW_EMPTY_AS_OVERWRITE)},
		{"DRAW_NO_FILL", int(render.DRAW_NO_FILL)},
		{"DRAW_NO_OUTLINE", int(render.DRAW_NO_OUTLINE)},
		{"DRAW_SOLID_UNDERLINE", int(render.DRAW_SOLID_UNDERLINE)},
		{"DRAW_STIPPLED_UNDERLINE", int(render.DRAW_STIPPLED_UNDERLINE)},
		{"DRAW_SQUIGGLY_UNDERLINE", int(render.DRAW_SQUIGGLY_UNDERLINE)},
		{"PERSISTENT", int(render.PERSISTENT)},
		{"HIDDEN", int(render.HIDDEN)},
	}

	for _, cl := range classes {
		c, err := cl.c.Create()
		if err != nil {
			panic(err)
		}
		if err := m.AddObject(cl.name, c); err != nil {
			panic(err)
		}
	}
	for _, c := range constants {
		if err := m.AddIntConstant(c.name, c.constant); err != nil {
			panic(err)
		}
	}
	py.AddToPath(backend.LIME_PACKAGES_PATH)
	py.AddToPath(backend.LIME_USER_PACKAGES_PATH)
	py.AddToPath(path.Join("..", "..", "backend", "sublime"))
}

func loadPlugin(p *backend.Plugin, m *py.Module) {
	fi := p.Get().([]os.FileInfo)
	for _, f := range fi {
		fn := f.Name()
		s, err := py.NewUnicode(path.Base(p.Name()) + "." + fn[:len(fn)-3])
		if err != nil {
			log4go.Error(err)
			return
		}
		if r, err := m.Base().CallMethodObjArgs("reload_plugin", s); err != nil {
			log4go.Error(err)
		} else if r != nil {
			r.Decref()
		}
	}
	p.LoadPackets()
	watch(backend.NewWatchedPackage(p))
}

var (
	watcher        *fsnotify.Watcher
	watchedPlugins map[string]*backend.WatchedPackage
)

func watch(plugin *backend.WatchedPackage) {
	log4go.Finest("Watch(%v)", plugin)
	if err := watcher.Watch(plugin.Name()); err != nil {
		log4go.Error("Could not watch plugin: %v", err)
	} else {
		watchedPlugins[plugin.Name()] = plugin
	}
}

func unWatch(name string) {
	if err := watcher.RemoveWatch(name); err != nil {
		log4go.Error("Couldn't unwatch file: %v", err)
	}
	log4go.Finest("UnWatch(%s)", name)
	delete(watchedPlugins, name)
}

func observePlugins(m *py.Module) {
	for {
		select {
		case ev := <-watcher.Event:
			if !(ev.IsModify() || ev.IsCreate()) {
				continue
			}
			if p, exist := watchedPlugins[path.Dir(ev.Name)]; exist {
				p.Reload()
				loadPlugin(p.Package().(*backend.Plugin), m)
			}
		case err := <-watcher.Error:
			log4go.Error("error:", err)
		}
	}
}

// TODO
func Init() {
	l := py.NewLock()
	defer l.Unlock()
	m, err := py.Import("sublime_plugin")
	if err != nil {
		panic(err)
	}
	sys, err := py.Import("sys")
	if err != nil {
		log4go.Debug(err)
	} else {
		defer sys.Decref()
	}

	watcher, err = fsnotify.NewWatcher()
	if err != nil {
		log4go.Error("Could not create watcher due to: %v", err)
	}
	watchedPlugins = make(map[string]*backend.WatchedPackage)
	go observePlugins(m)

	plugins := backend.ScanPlugins(backend.LIME_USER_PACKAGES_PATH, ".py")
	for _, p := range plugins {
		// TODO: add all plugins after supporting all commands
		if p.Name() == path.Join("..", "..", "3rdparty", "bundles", "Vintageous") {
			loadPlugin(p, m)
		}
	}
}
<|endoftext|>


<commit_before>// Copyright ©2017 The Gonum 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 testblas

import (
	"math/cmplx"
	"testing"

	"gonum.org/v1/gonum/blas"
)

type Zherer interface {
	Zher(uplo blas.Uplo, n int, alpha float64, x []complex128, incX int, a []complex128, lda int)
}

func ZherTest(t *testing.T, impl Zherer) {
	for tc, test := range []struct {
		alpha float64
		x     []complex128
		a     []complex128

		want    []complex128
		wantRev []complex128 // Result when incX is negative.
	}{
		{
			alpha: 1,
		},
		{
			alpha: 3,
			x: []complex128{
				0 - 3i,
				6 + 10i,
				-2 - 7i,
			},
			a: []complex128{
				-2 + 0i, -3 - 11i, 0 + 4i,
				-3 + 11i, -6 + 0i, 7 + 2i,
				0 - 4i, 7 - 2i, 18 + 0i,
			},
			want: []complex128{
				25 + 0i, -93 - 65i, 63 + 22i,
				-93 + 65i, 402 + 0i, -239 + 68i,
				63 - 22i, -239 - 68i, 177 + 0i},
			wantRev: []complex128{
				157 + 0i, -249 - 77i, 63 - 14i,
				-249 + 77i, 402 + 0i, -83 + 56i,
				63 + 14i, -83 - 56i, 45 + 0i,
			},
		},
		{
			alpha: 3,
			x: []complex128{
				-6 + 2i,
				-2 - 4i,
				0 + 0i,
				0 + 7i,
			},
			a: []complex128{
				2 + 0i, -9 + 7i, 3 + 11i, 10 - 1i,
				-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
				3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
				10 + 1i, -7 + 5i, 2 + 1i, 18 + 0i,
			},
			want: []complex128{
				122 + 0i, 3 - 77i, 3 + 11i, 52 + 125i,
				3 + 77i, 76 + 0i, -5 + 2i, -91 + 37i,
				3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
				52 - 125i, -91 - 37i, 2 + 1i, 165 + 0i,
			},
			wantRev: []complex128{
				149 + 0i, -9 + 7i, -81 - 31i, 52 - 127i,
				-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
				-81 + 31i, -5 - 2i, 74 + 0i, 14 + 83i,
				52 + 127i, -7 + 5i, 14 - 83i, 138 + 0i,
			},
		},
		{
			alpha: 0,
			x: []complex128{
				-6 + 2i,
				-2 - 4i,
				0 + 0i,
				0 + 7i,
			},
			a: []complex128{
				2 + 0i, -9 + 7i, 3 + 11i, 10 - 1i,
				-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
				3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
				10 + 1i, -7 + 5i, 2 + 1i, 18 + 0i,
			},
			want: []complex128{
				2 + 0i, -9 + 7i, 3 + 11i, 10 - 1i,
				-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
				3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
				10 + 1i, -7 + 5i, 2 + 1i, 18 + 0i,
			},
			wantRev: []complex128{
				2 + 0i, -9 + 7i, 3 + 11i, 10 - 1i,
				-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
				3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
				10 + 1i, -7 + 5i, 2 + 1i, 18 + 0i,
			},
		},
	} {
		n := len(test.x)
		for _, uplo := range []blas.Uplo{blas.Lower, blas.Upper} {
			for _, incX := range []int{-11, -2, -1, 1, 2, 7} {
				for _, lda := range []int{max(1, n), n + 11} {
					x := makeZVector(test.x, incX)
					xCopy := make([]complex128, len(x))
					copy(xCopy, x)

					a := makeZGeneral(test.a, n, n, lda)

					var want []complex128
					if incX > 0 {
						want = makeZGeneral(test.want, n, n, lda)
					} else {
						want = makeZGeneral(test.wantRev, n, n, lda)
					}

					if uplo == blas.Upper {
						for i := 0; i < n; i++ {
							for j := 0; j < i; j++ {
								a[i*lda+j] = cmplx.NaN()
								want[i*lda+j] = cmplx.NaN()
							}
						}
					} else {
						for i := 0; i < n; i++ {
							for j := i + 1; j < n; j++ {
								a[i*lda+j] = cmplx.NaN()
								want[i*lda+j] = cmplx.NaN()
							}
						}
					}

					impl.Zher(uplo, n, test.alpha, x, incX, a, lda)

					if !zsame(x, xCopy) {
						t.Errorf("Case %v (uplo=%v,incX=%v,lda=%v,alpha=%v): unexpected modification of x", tc, uplo, incX, test.alpha, lda)
					}
					if !zsame(want, a) {
						t.Errorf("Case %v (uplo=%v,incX=%v,lda=%v,alpha=%v): unexpected result\nwant: %v\ngot:  %v", tc, uplo, incX, lda, test.alpha, want, a)
					}
				}
			}
		}
	}
}
<commit_msg>blas/testblas: move test cases for Zher to package-level variable<commit_after>// Copyright ©2017 The Gonum 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 testblas

import (
	"math/cmplx"
	"testing"

	"gonum.org/v1/gonum/blas"
)

var zherTestCases = []struct {
	alpha float64
	x     []complex128
	a     []complex128

	want    []complex128
	wantRev []complex128 // Result when incX is negative.
}{
	{
		alpha: 1,
	},
	{
		alpha: 3,
		x: []complex128{
			0 - 3i,
			6 + 10i,
			-2 - 7i,
		},
		a: []complex128{
			-2 + 0i, -3 - 11i, 0 + 4i,
			-3 + 11i, -6 + 0i, 7 + 2i,
			0 - 4i, 7 - 2i, 18 + 0i,
		},
		want: []complex128{
			25 + 0i, -93 - 65i, 63 + 22i,
			-93 + 65i, 402 + 0i, -239 + 68i,
			63 - 22i, -239 - 68i, 177 + 0i},
		wantRev: []complex128{
			157 + 0i, -249 - 77i, 63 - 14i,
			-249 + 77i, 402 + 0i, -83 + 56i,
			63 + 14i, -83 - 56i, 45 + 0i,
		},
	},
	{
		alpha: 3,
		x: []complex128{
			-6 + 2i,
			-2 - 4i,
			0 + 0i,
			0 + 7i,
		},
		a: []complex128{
			2 + 0i, -9 + 7i, 3 + 11i, 10 - 1i,
			-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
			3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
			10 + 1i, -7 + 5i, 2 + 1i, 18 + 0i,
		},
		want: []complex128{
			122 + 0i, 3 - 77i, 3 + 11i, 52 + 125i,
			3 + 77i, 76 + 0i, -5 + 2i, -91 + 37i,
			3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
			52 - 125i, -91 - 37i, 2 + 1i, 165 + 0i,
		},
		wantRev: []complex128{
			149 + 0i, -9 + 7i, -81 - 31i, 52 - 127i,
			-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
			-81 + 31i, -5 - 2i, 74 + 0i, 14 + 83i,
			52 + 127i, -7 + 5i, 14 - 83i, 138 + 0i,
		},
	},
	{
		alpha: 0,
		x: []complex128{
			-6 + 2i,
			-2 - 4i,
			0 + 0i,
			0 + 7i,
		},
		a: []complex128{
			2 + 0i, -9 + 7i, 3 + 11i, 10 - 1i,
			-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
			3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
			10 + 1i, -7 + 5i, 2 + 1i, 18 + 0i,
		},
		want: []complex128{
			2 + 0i, -9 + 7i, 3 + 11i, 10 - 1i,
			-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
			3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
			10 + 1i, -7 + 5i, 2 + 1i, 18 + 0i,
		},
		wantRev: []complex128{
			2 + 0i, -9 + 7i, 3 + 11i, 10 - 1i,
			-9 - 7i, 16 + 0i, -5 + 2i, -7 - 5i,
			3 - 11i, -5 - 2i, 14 + 0i, 2 - 1i,
			10 + 1i, -7 + 5i, 2 + 1i, 18 + 0i,
		},
	},
}

type Zherer interface {
	Zher(uplo blas.Uplo, n int, alpha float64, x []complex128, incX int, a []complex128, lda int)
}

func ZherTest(t *testing.T, impl Zherer) {
	for tc, test := range zherTestCases {
		n := len(test.x)
		for _, uplo := range []blas.Uplo{blas.Lower, blas.Upper} {
			for _, incX := range []int{-11, -2, -1, 1, 2, 7} {
				for _, lda := range []int{max(1, n), n + 11} {
					x := makeZVector(test.x, incX)
					xCopy := make([]complex128, len(x))
					copy(xCopy, x)

					a := makeZGeneral(test.a, n, n, lda)

					var want []complex128
					if incX > 0 {
						want = makeZGeneral(test.want, n, n, lda)
					} else {
						want = makeZGeneral(test.wantRev, n, n, lda)
					}

					if uplo == blas.Upper {
						for i := 0; i < n; i++ {
							for j := 0; j < i; j++ {
								a[i*lda+j] = cmplx.NaN()
								want[i*lda+j] = cmplx.NaN()
							}
						}
					} else {
						for i := 0; i < n; i++ {
							for j := i + 1; j < n; j++ {
								a[i*lda+j] = cmplx.NaN()
								want[i*lda+j] = cmplx.NaN()
							}
						}
					}

					impl.Zher(uplo, n, test.alpha, x, incX, a, lda)

					if !zsame(x, xCopy) {
						t.Errorf("Case %v (uplo=%v,incX=%v,lda=%v,alpha=%v): unexpected modification of x", tc, uplo, incX, test.alpha, lda)
					}
					if !zsame(want, a) {
						t.Errorf("Case %v (uplo=%v,incX=%v,lda=%v,alpha=%v): unexpected result\nwant: %v\ngot:  %v", tc, uplo, incX, lda, test.alpha, want, a)
					}
				}
			}
		}
	}
}
<|endoftext|>


<commit_before>// Copyright 2013 The lime Authors.
// Use of this source code is governed by a 2-clause
// BSD-style license that can be found in the LICENSE file.

package sublime

import (
	"code.google.com/p/log4go"
	"fmt"
	"github.com/howeyc/fsnotify"
	"github.com/limetext/gopy/lib"
	"github.com/limetext/lime/backend"
	"github.com/limetext/lime/backend/packages"
	"github.com/limetext/lime/backend/render"
	"github.com/limetext/lime/backend/util"
	"os"
	"path"
	"time"
)

func sublime_Console(tu *py.Tuple, kwargs *py.Dict) (py.Object, error) {
	if tu.Size() != 1 {
		return nil, fmt.Errorf("Unexpected argument count: %d", tu.Size())
	}
	if i, err := tu.GetItem(0); err != nil {
		return nil, err
	} else {
		log4go.Info("Python sez: %s", i)
	}
	return toPython(nil)
}

func sublime_set_timeout(tu *py.Tuple, kwargs *py.Dict) (py.Object, error) {
	var (
		pyarg py.Object
	)
	if tu.Size() != 2 {
		return nil, fmt.Errorf("Unexpected argument count: %d", tu.Size())
	}
	if i, err := tu.GetItem(0); err != nil {
		return nil, err
	} else {
		pyarg = i
	}
	if i, err := tu.GetItem(1); err != nil {
		return nil, err
	} else if v, err := fromPython(i); err != nil {
		return nil, err
	} else if v2, ok := v.(int); !ok {
		return nil, fmt.Errorf("Expected int not %s", i.Type())
	} else {
		pyarg.Incref()
		go func() {
			time.Sleep(time.Millisecond * time.Duration(v2))
			l := py.NewLock()
			defer l.Unlock()
			defer pyarg.Decref()
			if ret, err := pyarg.Base().CallFunctionObjArgs(); err != nil {
				log4go.Debug("Error in callback: %v", err)
			} else {
				ret.Decref()
			}
		}()
	}
	return toPython(nil)
}

func init() {
	sublime_methods = append(sublime_methods, py.Method{Name: "console", Func: sublime_Console}, py.Method{Name: "set_timeout", Func: sublime_set_timeout})
	backend.GetEditor()
	l := py.InitAndLock()
	defer l.Unlock()
	//	py.InitializeEx(false)
	m, err := py.InitModule("sublime", sublime_methods)
	if err != nil {
		panic(err)
	}

	type class struct {
		name string
		c    *py.Class
	}
	classes := []class{
		{"Region", &_regionClass},
		{"RegionSet", &_region_setClass},
		{"View", &_viewClass},
		{"Window", &_windowClass},
		{"Edit", &_editClass},
		{"Settings", &_settingsClass},
		{"WindowCommandGlue", &_windowCommandGlueClass},
		{"TextCommandGlue", &_textCommandGlueClass},
		{"ApplicationCommandGlue", &_applicationCommandGlueClass},
		{"OnQueryContextGlue", &_onQueryContextGlueClass},
		{"ViewEventGlue", &_viewEventGlueClass},
	}
	type constant struct {
		name     string
		constant int
	}
	constants := []constant{
		{"OP_EQUAL", int(util.OpEqual)},
		{"OP_NOT_EQUAL", int(util.OpNotEqual)},
		{"OP_REGEX_MATCH", int(util.OpRegexMatch)},
		{"OP_NOT_REGEX_MATCH", int(util.OpNotRegexMatch)},
		{"OP_REGEX_CONTAINS", int(util.OpRegexContains)},
		{"OP_NOT_REGEX_CONTAINS", int(util.OpNotRegexContains)},
		{"INHIBIT_WORD_COMPLETIONS", 0},
		{"INHIBIT_EXPLICIT_COMPLETIONS", 0},
		{"LITERAL", 0},
		{"IGNORECASE", 0},
		{"CLASS_WORD_START", int(backend.CLASS_WORD_START)},
		{"CLASS_WORD_END", int(backend.CLASS_WORD_END)},
		{"CLASS_PUNCTUATION_START", int(backend.CLASS_PUNCTUATION_START)},
		{"CLASS_PUNCTUATION_END", int(backend.CLASS_PUNCTUATION_END)},
		{"CLASS_SUB_WORD_START", int(backend.CLASS_SUB_WORD_START)},
		{"CLASS_SUB_WORD_END", int(backend.CLASS_SUB_WORD_END)},
		{"CLASS_LINE_START", int(backend.CLASS_LINE_START)},
		{"CLASS_LINE_END", int(backend.CLASS_LINE_END)},
		{"CLASS_EMPTY_LINE", int(backend.CLASS_EMPTY_LINE)},
		{"CLASS_MIDDLE_WORD", int(backend.CLASS_MIDDLE_WORD)},
		{"CLASS_WORD_START_WITH_PUNCTUATION", int(backend.CLASS_WORD_START_WITH_PUNCTUATION)},
		{"CLASS_WORD_END_WITH_PUNCTUATION", int(backend.CLASS_WORD_END_WITH_PUNCTUATION)},
		{"CLASS_OPENING_PARENTHESIS", int(backend.CLASS_OPENING_PARENTHESIS)},
		{"CLASS_CLOSING_PARENTHESIS", int(backend.CLASS_CLOSING_PARENTHESIS)},
		{"DRAW_EMPTY", int(render.DRAW_EMPTY)},
		{"HIDE_ON_MINIMAP", int(render.HIDE_ON_MINIMAP)},
		{"DRAW_EMPTY_AS_OVERWRITE", int(render.DRAW_EMPTY_AS_OVERWRITE)},
		{"DRAW_NO_FILL", int(render.DRAW_NO_FILL)},
		{"DRAW_NO_OUTLINE", int(render.DRAW_NO_OUTLINE)},
		{"DRAW_SOLID_UNDERLINE", int(render.DRAW_SOLID_UNDERLINE)},
		{"DRAW_STIPPLED_UNDERLINE", int(render.DRAW_STIPPLED_UNDERLINE)},
		{"DRAW_SQUIGGLY_UNDERLINE", int(render.DRAW_SQUIGGLY_UNDERLINE)},
		{"PERSISTENT", int(render.PERSISTENT)},
		{"HIDDEN", int(render.HIDDEN)},
	}

	for _, cl := range classes {
		c, err := cl.c.Create()
		if err != nil {
			panic(err)
		}
		if err := m.AddObject(cl.name, c); err != nil {
			panic(err)
		}
	}
	for _, c := range constants {
		if err := m.AddIntConstant(c.name, c.constant); err != nil {
			panic(err)
		}
	}
	py.AddToPath(backend.LIME_PACKAGES_PATH)
	py.AddToPath(backend.LIME_USER_PACKAGES_PATH)
	py.AddToPath(path.Join("..", "..", "backend", "sublime"))
}

func loadPlugin(p *packages.Plugin, m *py.Module) {
	fi := p.Get().([]os.FileInfo)
	for _, f := range fi {
		fn := f.Name()
		s, err := py.NewUnicode(path.Base(p.Name()) + "." + fn[:len(fn)-3])
		if err != nil {
			log4go.Error(err)
			return
		}
		if r, err := m.Base().CallMethodObjArgs("reload_plugin", s); err != nil {
			log4go.Error(err)
		} else if r != nil {
			r.Decref()
		}
	}
	p.LoadPackets()
	watch(backend.NewWatchedPackage(p))
}

var (
	watcher        *fsnotify.Watcher
	watchedPlugins map[string]*backend.WatchedPackage
)

func watch(plugin *backend.WatchedPackage) {
	log4go.Finest("Watch(%v)", plugin)
	if err := watcher.Watch(plugin.Name()); err != nil {
		log4go.Error("Could not watch plugin: %v", err)
	} else {
		watchedPlugins[plugin.Name()] = plugin
	}
}

func unWatch(name string) {
	if err := watcher.RemoveWatch(name); err != nil {
		log4go.Error("Couldn't unwatch file: %v", err)
	}
	log4go.Finest("UnWatch(%s)", name)
	delete(watchedPlugins, name)
}

func observePlugins(m *py.Module) {
	for {
		select {
		case ev := <-watcher.Event:
			if !(ev.IsModify() || ev.IsCreate()) {
				continue
			}
			if p, exist := watchedPlugins[path.Dir(ev.Name)]; exist {
				p.Reload()
				loadPlugin(p.Package().(*packages.Plugin), m)
			}
		case err := <-watcher.Error:
			log4go.Error("error:", err)
		}
	}
}

// TODO
func Init() {
	l := py.NewLock()
	defer l.Unlock()
	m, err := py.Import("sublime_plugin")
	if err != nil {
		panic(err)
	}
	sys, err := py.Import("sys")
	if err != nil {
		log4go.Debug(err)
	} else {
		defer sys.Decref()
	}

	watcher, err = fsnotify.NewWatcher()
	if err != nil {
		log4go.Error("Could not create watcher due to: %v", err)
	}
	watchedPlugins = make(map[string]*backend.WatchedPackage)
	go observePlugins(m)

	plugins := packages.ScanPlugins(backend.LIME_USER_PACKAGES_PATH, ".py")
	for _, p := range plugins {
		// TODO: add all plugins after supporting all commands
		if p.Name() == path.Join("..", "..", "3rdparty", "bundles", "Vintageous") {
			loadPlugin(p, m)
		}
	}
}
<commit_msg>Fix a reported data race<commit_after>// Copyright 2013 The lime Authors.
// Use of this source code is governed by a 2-clause
// BSD-style license that can be found in the LICENSE file.

package sublime

import (
	"code.google.com/p/log4go"
	"fmt"
	"github.com/howeyc/fsnotify"
	"github.com/limetext/gopy/lib"
	"github.com/limetext/lime/backend"
	"github.com/limetext/lime/backend/packages"
	"github.com/limetext/lime/backend/render"
	"github.com/limetext/lime/backend/util"
	"os"
	"path"
	"time"
)

func sublime_Console(tu *py.Tuple, kwargs *py.Dict) (py.Object, error) {
	if tu.Size() != 1 {
		return nil, fmt.Errorf("Unexpected argument count: %d", tu.Size())
	}
	if i, err := tu.GetItem(0); err != nil {
		return nil, err
	} else {
		log4go.Info("Python sez: %s", i)
	}
	return toPython(nil)
}

func sublime_set_timeout(tu *py.Tuple, kwargs *py.Dict) (py.Object, error) {
	var (
		pyarg py.Object
	)
	if tu.Size() != 2 {
		return nil, fmt.Errorf("Unexpected argument count: %d", tu.Size())
	}
	if i, err := tu.GetItem(0); err != nil {
		return nil, err
	} else {
		pyarg = i
	}
	if i, err := tu.GetItem(1); err != nil {
		return nil, err
	} else if v, err := fromPython(i); err != nil {
		return nil, err
	} else if v2, ok := v.(int); !ok {
		return nil, fmt.Errorf("Expected int not %s", i.Type())
	} else {
		pyarg.Incref()
		go func() {
			time.Sleep(time.Millisecond * time.Duration(v2))
			l := py.NewLock()
			defer l.Unlock()
			defer pyarg.Decref()
			if ret, err := pyarg.Base().CallFunctionObjArgs(); err != nil {
				log4go.Debug("Error in callback: %v", err)
			} else {
				ret.Decref()
			}
		}()
	}
	return toPython(nil)
}

func init() {
	sublime_methods = append(sublime_methods, py.Method{Name: "console", Func: sublime_Console}, py.Method{Name: "set_timeout", Func: sublime_set_timeout})
	backend.GetEditor()
	l := py.InitAndLock()
	defer l.Unlock()
	//	py.InitializeEx(false)
	m, err := py.InitModule("sublime", sublime_methods)
	if err != nil {
		panic(err)
	}

	type class struct {
		name string
		c    *py.Class
	}
	classes := []class{
		{"Region", &_regionClass},
		{"RegionSet", &_region_setClass},
		{"View", &_viewClass},
		{"Window", &_windowClass},
		{"Edit", &_editClass},
		{"Settings", &_settingsClass},
		{"WindowCommandGlue", &_windowCommandGlueClass},
		{"TextCommandGlue", &_textCommandGlueClass},
		{"ApplicationCommandGlue", &_applicationCommandGlueClass},
		{"OnQueryContextGlue", &_onQueryContextGlueClass},
		{"ViewEventGlue", &_viewEventGlueClass},
	}
	type constant struct {
		name     string
		constant int
	}
	constants := []constant{
		{"OP_EQUAL", int(util.OpEqual)},
		{"OP_NOT_EQUAL", int(util.OpNotEqual)},
		{"OP_REGEX_MATCH", int(util.OpRegexMatch)},
		{"OP_NOT_REGEX_MATCH", int(util.OpNotRegexMatch)},
		{"OP_REGEX_CONTAINS", int(util.OpRegexContains)},
		{"OP_NOT_REGEX_CONTAINS", int(util.OpNotRegexContains)},
		{"INHIBIT_WORD_COMPLETIONS", 0},
		{"INHIBIT_EXPLICIT_COMPLETIONS", 0},
		{"LITERAL", 0},
		{"IGNORECASE", 0},
		{"CLASS_WORD_START", int(backend.CLASS_WORD_START)},
		{"CLASS_WORD_END", int(backend.CLASS_WORD_END)},
		{"CLASS_PUNCTUATION_START", int(backend.CLASS_PUNCTUATION_START)},
		{"CLASS_PUNCTUATION_END", int(backend.CLASS_PUNCTUATION_END)},
		{"CLASS_SUB_WORD_START", int(backend.CLASS_SUB_WORD_START)},
		{"CLASS_SUB_WORD_END", int(backend.CLASS_SUB_WORD_END)},
		{"CLASS_LINE_START", int(backend.CLASS_LINE_START)},
		{"CLASS_LINE_END", int(backend.CLASS_LINE_END)},
		{"CLASS_EMPTY_LINE", int(backend.CLASS_EMPTY_LINE)},
		{"CLASS_MIDDLE_WORD", int(backend.CLASS_MIDDLE_WORD)},
		{"CLASS_WORD_START_WITH_PUNCTUATION", int(backend.CLASS_WORD_START_WITH_PUNCTUATION)},
		{"CLASS_WORD_END_WITH_PUNCTUATION", int(backend.CLASS_WORD_END_WITH_PUNCTUATION)},
		{"CLASS_OPENING_PARENTHESIS", int(backend.CLASS_OPENING_PARENTHESIS)},
		{"CLASS_CLOSING_PARENTHESIS", int(backend.CLASS_CLOSING_PARENTHESIS)},
		{"DRAW_EMPTY", int(render.DRAW_EMPTY)},
		{"HIDE_ON_MINIMAP", int(render.HIDE_ON_MINIMAP)},
		{"DRAW_EMPTY_AS_OVERWRITE", int(render.DRAW_EMPTY_AS_OVERWRITE)},
		{"DRAW_NO_FILL", int(render.DRAW_NO_FILL)},
		{"DRAW_NO_OUTLINE", int(render.DRAW_NO_OUTLINE)},
		{"DRAW_SOLID_UNDERLINE", int(render.DRAW_SOLID_UNDERLINE)},
		{"DRAW_STIPPLED_UNDERLINE", int(render.DRAW_STIPPLED_UNDERLINE)},
		{"DRAW_SQUIGGLY_UNDERLINE", int(render.DRAW_SQUIGGLY_UNDERLINE)},
		{"PERSISTENT", int(render.PERSISTENT)},
		{"HIDDEN", int(render.HIDDEN)},
	}

	for _, cl := range classes {
		c, err := cl.c.Create()
		if err != nil {
			panic(err)
		}
		if err := m.AddObject(cl.name, c); err != nil {
			panic(err)
		}
	}
	for _, c := range constants {
		if err := m.AddIntConstant(c.name, c.constant); err != nil {
			panic(err)
		}
	}
	py.AddToPath(backend.LIME_PACKAGES_PATH)
	py.AddToPath(backend.LIME_USER_PACKAGES_PATH)
	py.AddToPath(path.Join("..", "..", "backend", "sublime"))
}

func loadPlugin(p *packages.Plugin, m *py.Module) {
	fi := p.Get().([]os.FileInfo)
	for _, f := range fi {
		fn := f.Name()
		s, err := py.NewUnicode(path.Base(p.Name()) + "." + fn[:len(fn)-3])
		if err != nil {
			log4go.Error(err)
			return
		}
		if r, err := m.Base().CallMethodObjArgs("reload_plugin", s); err != nil {
			log4go.Error(err)
		} else if r != nil {
			r.Decref()
		}
	}
	p.LoadPackets()
	watch(backend.NewWatchedPackage(p))
}

var (
	watcher        *fsnotify.Watcher
	watchedPlugins map[string]*backend.WatchedPackage
)

func watch(plugin *backend.WatchedPackage) {
	log4go.Finest("Watch(%v)", plugin)
	if err := watcher.Watch(plugin.Name()); err != nil {
		log4go.Error("Could not watch plugin: %v", err)
	} else {
		watchedPlugins[plugin.Name()] = plugin
	}
}

func unWatch(name string) {
	if err := watcher.RemoveWatch(name); err != nil {
		log4go.Error("Couldn't unwatch file: %v", err)
	}
	log4go.Finest("UnWatch(%s)", name)
	delete(watchedPlugins, name)
}

func observePlugins(m *py.Module) {
	for {
		select {
		case ev := <-watcher.Event:
			if !(ev.IsModify() || ev.IsCreate()) {
				continue
			}
			if p, exist := watchedPlugins[path.Dir(ev.Name)]; exist {
				p.Reload()
				loadPlugin(p.Package().(*packages.Plugin), m)
			}
		case err := <-watcher.Error:
			log4go.Error("error:", err)
		}
	}
}

// TODO
func Init() {
	l := py.NewLock()
	defer l.Unlock()
	m, err := py.Import("sublime_plugin")
	if err != nil {
		panic(err)
	}
	sys, err := py.Import("sys")
	if err != nil {
		log4go.Debug(err)
	} else {
		defer sys.Decref()
	}

	watcher, err = fsnotify.NewWatcher()
	if err != nil {
		log4go.Error("Could not create watcher due to: %v", err)
	}
	watchedPlugins = make(map[string]*backend.WatchedPackage)

	plugins := packages.ScanPlugins(backend.LIME_USER_PACKAGES_PATH, ".py")
	for _, p := range plugins {
		// TODO: add all plugins after supporting all commands
		if p.Name() == path.Join("..", "..", "3rdparty", "bundles", "Vintageous") {
			loadPlugin(p, m)
		}
	}

	go observePlugins(m)
}
<|endoftext|>


<commit_before>// Copyright 2015 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ui

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/square/metrics/api"
	"github.com/square/metrics/query"
)

type QueryHandler struct {
	API     api.API
	Backend api.Backend
}

type Response struct {
	Success bool        `json:"success"`
	Message string      `json:"message,omitempty"`
	Body    interface{} `json:"body,omitempty"`
}

func errorResponse(writer http.ResponseWriter, code int, err error) {
	writer.WriteHeader(code)
	encoded, err := json.MarshalIndent(Response{Success: false, Message: err.Error()}, "", "  ")
	if err != nil {
		writer.Write([]byte("{\"success\":false, \"message\":'failed to encode error message'}"))
		return
	}
	writer.Write(encoded)
}

func bodyResponse(writer http.ResponseWriter, body interface{}) {
	encoded, err := json.MarshalIndent(Response{Success: true, Body: body}, "", "  ")
	if err != nil {
		writer.Write([]byte("{\"success\":false, \"message\":'failed to encode result message'"))
		return
	}
	writer.Write(encoded)
}

func (q QueryHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	err := request.ParseForm()
	if err != nil {
		errorResponse(writer, http.StatusBadRequest, err)
		return
	}
	input := request.Form.Get("query")

	cmd, err := query.Parse(input)
	if err != nil {
		errorResponse(writer, http.StatusBadRequest, err)
		return
	}

	n, ok := cmd.(query.Node)
	if !ok {
		errorResponse(writer, http.StatusInternalServerError, err)
		return
	}
	fmt.Println(query.PrintNode(n))

	result, err := cmd.Execute(q.Backend, q.API)
	if err != nil {
		errorResponse(writer, http.StatusInternalServerError, err)
		return
	}
	bodyResponse(writer, result)
}

func Main(apiInstance api.API, backend api.Backend) {
	handler := QueryHandler{
		API:     apiInstance,
		Backend: backend,
	}

	httpMux := http.NewServeMux()
	httpMux.Handle("/query", handler)

	server := &http.Server{
		Addr:           ":8080",
		Handler:        httpMux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	err := server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
<commit_msg>remove printing from server<commit_after>// Copyright 2015 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ui

import (
	"encoding/json"
	"log"
	"net/http"
	"time"

	"github.com/square/metrics/api"
	"github.com/square/metrics/query"
)

type QueryHandler struct {
	API     api.API
	Backend api.Backend
}

type Response struct {
	Success bool        `json:"success"`
	Message string      `json:"message,omitempty"`
	Body    interface{} `json:"body,omitempty"`
}

func errorResponse(writer http.ResponseWriter, code int, err error) {
	writer.WriteHeader(code)
	encoded, err := json.MarshalIndent(Response{Success: false, Message: err.Error()}, "", "  ")
	if err != nil {
		writer.Write([]byte("{\"success\":false, \"message\":'failed to encode error message'}"))
		return
	}
	writer.Write(encoded)
}

func bodyResponse(writer http.ResponseWriter, body interface{}) {
	encoded, err := json.MarshalIndent(Response{Success: true, Body: body}, "", "  ")
	if err != nil {
		writer.Write([]byte("{\"success\":false, \"message\":'failed to encode result message'"))
		return
	}
	writer.Write(encoded)
}

func (q QueryHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	err := request.ParseForm()
	if err != nil {
		errorResponse(writer, http.StatusBadRequest, err)
		return
	}
	input := request.Form.Get("query")

	cmd, err := query.Parse(input)
	if err != nil {
		errorResponse(writer, http.StatusBadRequest, err)
		return
	}

	result, err := cmd.Execute(q.Backend, q.API)
	if err != nil {
		errorResponse(writer, http.StatusInternalServerError, err)
		return
	}
	bodyResponse(writer, result)
}

func Main(apiInstance api.API, backend api.Backend) {
	handler := QueryHandler{
		API:     apiInstance,
		Backend: backend,
	}

	httpMux := http.NewServeMux()
	httpMux.Handle("/query", handler)

	server := &http.Server{
		Addr:           ":8080",
		Handler:        httpMux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	err := server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package deps

import (
	"fmt"
	"go/build"
	"log"
	"os"
	"os/exec"
	"path"
	"sort"
	"strings"

	"github.com/fatih/set"
)

type Deps struct {
	// if multiple, revision will be always pointing to HEAD
	// Packages is written as the importPath of a given package.
	Packages     []string
	Dependencies []string
}

func LoadDeps(pkgs ...string) (*Deps, error) {
	packages, err := listPackages(pkgs...)
	if err != nil {
		fmt.Println(err)
	}

	// get all dependencies for applications defined above
	dependencies := set.New()
	for _, pkg := range packages {
		for _, imp := range pkg.Deps {
			dependencies.Add(imp)
		}
	}

	// clean up deps
	// 1. remove std lib paths
	// 2. remove libs beginning with "koding...", because they already
	context := build.Default
	thirdPartyDeps := make([]string, 0)

	for _, importPath := range dependencies.StringSlice() {
		p, err := context.Import(importPath, ".", build.AllowBinary)
		if err != nil {
			log.Println(err)
		}

		// do not include std lib
		if p.Goroot {
			continue
		}

		// do not include koding packages
		if strings.HasPrefix(importPath, "koding") {
			continue
		}

		thirdPartyDeps = append(thirdPartyDeps, importPath)
	}

	sort.Strings(thirdPartyDeps)

	deps := &Deps{
		Packages:     pkgs,
		Dependencies: thirdPartyDeps,
	}

	return deps, nil
}

func (d *Deps) GetDeps() error {
	pwd, err := os.Getwd()
	if err != nil {
		return err
	}

	godir := "gonew"
	gopathDir := path.Join(pwd, godir)
	os.MkdirAll(gopathDir, 0755)

	listPackages := strings.Join(d.Dependencies, " ")

	cmd := exec.Command("go", []string{"get", "-d", listPackages}...)
	cmd.Env = []string{"GOPATH=" + gopathDir}

	err = cmd.Run()
	if err != nil {
		return err
	}

	return nil
}
<commit_msg>tools/deps: implement getting deps<commit_after>package deps

import (
	"fmt"
	"go/build"
	"log"
	"os"
	"os/exec"
	"path"
	"sort"
	"strings"
	"sync"

	"github.com/fatih/set"
)

type Deps struct {
	// if multiple, revision will be always pointing to HEAD
	// Packages is written as the importPath of a given package.
	Packages     []string
	Dependencies []string
}

func LoadDeps(pkgs ...string) (*Deps, error) {
	packages, err := listPackages(pkgs...)
	if err != nil {
		fmt.Println(err)
	}

	// get all dependencies for applications defined above
	dependencies := set.New()
	for _, pkg := range packages {
		for _, imp := range pkg.Deps {
			dependencies.Add(imp)
		}
	}

	// clean up deps
	// 1. remove std lib paths
	// 2. remove libs beginning with "koding...", because they already
	context := build.Default
	thirdPartyDeps := make([]string, 0)

	for _, importPath := range dependencies.StringSlice() {
		p, err := context.Import(importPath, ".", build.AllowBinary)
		if err != nil {
			log.Println(err)
		}

		// do not include std lib
		if p.Goroot {
			continue
		}

		// do not include koding packages
		if strings.HasPrefix(importPath, "koding") {
			continue
		}

		thirdPartyDeps = append(thirdPartyDeps, importPath)
	}

	sort.Strings(thirdPartyDeps)

	deps := &Deps{
		Packages:     pkgs,
		Dependencies: thirdPartyDeps,
	}

	return deps, nil
}

func (d *Deps) GetDeps() error {
	pwd, err := os.Getwd()
	if err != nil {
		return err
	}

	godir := "gonew"
	gopathDir := path.Join(pwd, godir)
	os.MkdirAll(gopathDir, 0755)
	os.Setenv("GOPATH", gopathDir)

	var wg sync.WaitGroup

	results := make(chan string, 0)

	for _, pkg := range d.Dependencies {
		wg.Add(1)

		go func(pkg string) {
			defer wg.Done()
			cmd := exec.Command("go", []string{"get", "-d", pkg}...)
			cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr

			var res string
			err := cmd.Run()
			if err != nil {
				res = fmt.Sprintf("fetching error %s", err)
			} else {
				res = pkg
			}

			results <- res
		}(pkg)
	}

	go func() {
		for res := range results {
			fmt.Println(res)
		}
	}()

	wg.Wait()

	return nil
}
<|endoftext|>


<commit_before>package models

// IsIn checks if the first param is in the following ones
func IsIn(s string, ts ...string) bool {
	for _, t := range ts {
		if t == s {
			return true
		}
	}

	return false
}

// StringSliceUnique removes duplicates from a string slice
func StringSliceUnique(ss []string) []string {
	mss := make(map[string]struct{})

	for _, s := range ss {
		mss[s] = struct{}{}
	}

	// convert it to string slice
	res := make([]string, 0)
	for ms := range mss {
		res = append(res, ms)
	}

	return res
}
<commit_msg>Socialapi: allocate enough empty capacity for slice<commit_after>package models

// IsIn checks if the first param is in the following ones
func IsIn(s string, ts ...string) bool {
	for _, t := range ts {
		if t == s {
			return true
		}
	}

	return false
}

// StringSliceUnique removes duplicates from a string slice
func StringSliceUnique(ss []string) []string {
	mss := make(map[string]struct{})

	for _, s := range ss {
		mss[s] = struct{}{}
	}

	// convert it to string slice
	res := make([]string, 0, len(mss))
	for ms := range mss {
		res = append(res, ms)
	}

	return res
}
<|endoftext|>


<commit_before>package rest

import (
	"encoding/json"
	"fmt"
	kodingmodels "koding/db/models"
	"koding/db/mongodb/modelhelper"
	"socialapi/models"
	"socialapi/request"

	"github.com/google/go-querystring/query"
)

func CreateAccount(a *models.Account) (*models.Account, error) {
	a.Nick = a.OldId
	acc, err := sendModel("POST", "/account", a)
	if err != nil {
		return nil, err
	}

	return acc.(*models.Account), nil
}

func CreateAccountWithDailyDigest() (*models.Account, error) {
	acc, err := models.CreateAccountInBothDbs()
	if err != nil {
		return nil, err
	}

	eFreq := kodingmodels.EmailFrequency{
		Global:  true,
		Daily:   true,
		Comment: true,
	}

	err = modelhelper.UpdateEmailFrequency(acc.OldId, eFreq)
	if err != nil {
		return nil, err
	}

	return acc, nil
}

func sendOwnershipRequest(accountId int64, q *request.Query) (bool, error) {
	v, err := query.Values(q)
	if err != nil {
		return false, err
	}

	url := fmt.Sprintf("/account/%d/owns?%s", accountId, v.Encode())
	res, err := sendRequest("GET", url, nil)
	if err != nil {
		return false, err
	}

	var response struct{ Success bool }

	if err := json.Unmarshal(res, &response); err != nil {
		return false, err
	}

	return response.Success, nil

}

func CheckPostOwnership(acc *models.Account, post *models.ChannelMessage) (bool, error) {
	return sendOwnershipRequest(acc.Id, &request.Query{
		ObjectId: post.Id,
		Type:     "channel-message",
	})
}

func CheckChannelOwnership(acc *models.Account, channel *models.Channel) (bool, error) {
	return sendOwnershipRequest(acc.Id, &request.Query{
		ObjectId: channel.Id,
		Type:     "channel",
	})
}

func FetchAccountActivities(acc *models.Account, channel *models.Channel) ([]*models.ChannelMessageContainer, error) {
	url := fmt.Sprintf("/account/%d/posts?groupName=%s&accountId=%d", acc.Id, channel.GroupName, acc.Id)

	res, err := sendRequest("GET", url, nil)
	if err != nil {
		return make([]*models.ChannelMessageContainer, 0), err
	}

	var arr []*models.ChannelMessageContainer

	if err := json.Unmarshal(res, &arr); err != nil {
		return make([]*models.ChannelMessageContainer, 0), err
	}

	return arr, nil
}

func FetchAccountActivityCount(acc *models.Account, channel *models.Channel) (*models.CountResponse, error) {
	url := fmt.Sprintf("/account/%d/posts/count?groupName=%s&accountId=%d", acc.Id, channel.GroupName, acc.Id)

	res, err := sendRequest("GET", url, nil)
	if err != nil {
		return new(models.CountResponse), err
	}

	var cr *models.CountResponse
	if err := json.Unmarshal(res, &cr); err != nil {
		return new(models.CountResponse), err
	}

	return cr, nil
}

func FetchAccountChannels(token string) (*models.ChannelContainers, error) {
	cc := models.NewChannelContainers()
	res, err := marshallAndSendRequestWithAuth("GET", "/account/channels", cc, token)
	if err != nil {
		return nil, err
	}

	if err := json.Unmarshal(res, cc); err != nil {
		return nil, err
	}

	return cc, nil
}
<commit_msg>socialapi/rest: add token for account activities<commit_after>package rest

import (
	"encoding/json"
	"fmt"
	kodingmodels "koding/db/models"
	"koding/db/mongodb/modelhelper"
	"socialapi/models"
	"socialapi/request"

	"github.com/google/go-querystring/query"
)

func CreateAccount(a *models.Account) (*models.Account, error) {
	a.Nick = a.OldId
	acc, err := sendModel("POST", "/account", a)
	if err != nil {
		return nil, err
	}

	return acc.(*models.Account), nil
}

func CreateAccountWithDailyDigest() (*models.Account, error) {
	acc, err := models.CreateAccountInBothDbs()
	if err != nil {
		return nil, err
	}

	eFreq := kodingmodels.EmailFrequency{
		Global:  true,
		Daily:   true,
		Comment: true,
	}

	err = modelhelper.UpdateEmailFrequency(acc.OldId, eFreq)
	if err != nil {
		return nil, err
	}

	return acc, nil
}

func sendOwnershipRequest(accountId int64, q *request.Query) (bool, error) {
	v, err := query.Values(q)
	if err != nil {
		return false, err
	}

	url := fmt.Sprintf("/account/%d/owns?%s", accountId, v.Encode())
	res, err := sendRequest("GET", url, nil)
	if err != nil {
		return false, err
	}

	var response struct{ Success bool }

	if err := json.Unmarshal(res, &response); err != nil {
		return false, err
	}

	return response.Success, nil

}

func CheckPostOwnership(acc *models.Account, post *models.ChannelMessage) (bool, error) {
	return sendOwnershipRequest(acc.Id, &request.Query{
		ObjectId: post.Id,
		Type:     "channel-message",
	})
}

func CheckChannelOwnership(acc *models.Account, channel *models.Channel) (bool, error) {
	return sendOwnershipRequest(acc.Id, &request.Query{
		ObjectId: channel.Id,
		Type:     "channel",
	})
}

func FetchAccountActivities(acc *models.Account, channel *models.Channel, token string) ([]*models.ChannelMessageContainer, error) {
	url := fmt.Sprintf("/account/%d/posts?groupName=%s&accountId=%d", acc.Id, channel.GroupName, acc.Id)

	// res, err := sendRequest("GET", url, nil)
	res, err := sendRequestWithAuth("GET", url, nil, token)
	if err != nil {
		return make([]*models.ChannelMessageContainer, 0), err
	}

	var arr []*models.ChannelMessageContainer

	if err := json.Unmarshal(res, &arr); err != nil {
		return make([]*models.ChannelMessageContainer, 0), err
	}

	return arr, nil
}

func FetchAccountActivityCount(acc *models.Account, channel *models.Channel, token string) (*models.CountResponse, error) {
	url := fmt.Sprintf("/account/%d/posts/count?groupName=%s&accountId=%d", acc.Id, channel.GroupName, acc.Id)

	// res, err := sendRequest("GET", url, nil)
	res, err := sendRequestWithAuth("GET", url, nil, token)
	if err != nil {
		return new(models.CountResponse), err
	}

	var cr *models.CountResponse
	if err := json.Unmarshal(res, &cr); err != nil {
		return new(models.CountResponse), err
	}

	return cr, nil
}

func FetchAccountChannels(token string) (*models.ChannelContainers, error) {
	cc := models.NewChannelContainers()
	res, err := marshallAndSendRequestWithAuth("GET", "/account/channels", cc, token)
	if err != nil {
		return nil, err
	}

	if err := json.Unmarshal(res, cc); err != nil {
		return nil, err
	}

	return cc, nil
}
<|endoftext|>


<commit_before>package command

import (
	"io/ioutil"
	"os"

	"github.com/caarlos0/antibody"
	"github.com/caarlos0/antibody/bundle"
	"github.com/codegangsta/cli"
)

var Bundle = cli.Command{
	Name:   "bundle",
	Usage:  "bundle one or more bundles",
	Action: doBundle,
}

func doBundle(ctx *cli.Context) {
	if readFromStdin() {
		entries, _ := ioutil.ReadAll(os.Stdin)
		antibody.New(
			bundle.Parse(string(entries), antibody.Home()),
		).Download()
	} else {
		antibody.New(
			[]bundle.Bundle{bundle.New(ctx.Args().First(), antibody.Home())},
		).Download()
	}
}

func readFromStdin() bool {
	stat, _ := os.Stdin.Stat()
	return (stat.Mode() & os.ModeCharDevice) == 0
}
<commit_msg>improved bundle help<commit_after>package command

import (
	"io/ioutil"
	"os"

	"github.com/caarlos0/antibody"
	"github.com/caarlos0/antibody/bundle"
	"github.com/codegangsta/cli"
)

// Bundle downloads (if needed) and then sources a given repo
var Bundle = cli.Command{
	Name:   "bundle",
	Usage:  "downloads (if needed) and then sources a given repo",
	Action: doBundle,
}

func doBundle(ctx *cli.Context) {
	if readFromStdin() {
		entries, _ := ioutil.ReadAll(os.Stdin)
		antibody.New(
			bundle.Parse(string(entries), antibody.Home()),
		).Download()
	} else {
		antibody.New(
			[]bundle.Bundle{bundle.New(ctx.Args().First(), antibody.Home())},
		).Download()
	}
}

func readFromStdin() bool {
	stat, _ := os.Stdin.Stat()
	return (stat.Mode() & os.ModeCharDevice) == 0
}
<|endoftext|>