<commit_before>package rdio

type Album struct {
	Name        string   // the name of the album
	Type        string   // the type of the object, always "a"
	Icon        string   // the URL to the cover art for the album
	BaseIcon    string   // the URL to the cover art for the album
	Url         string   // the URL of the album on the Rdio site
	Artist      string   // the name of the artist that released the album
	ArtistUrl   string   // the URL of the artist that released the album on the Rdio site
	IsExplicit  bool     // is the album explicit?
	IsClean     bool     // is the album clean?
	Length      int      // number of tracks on the album
	ArtistKey   string   // the key of the artist that released the album
	TrackKeys   []string // the keys of the tracks on the album
	Price       string   // the price of the album in the requesting user's currency, if available for download
	CanStream   bool     // the album can be streamed
	CanSample   bool     // the album can be previewed
	CanTether   bool     // the album can be sync to mobile devices
	ShortUrl    string   // a short URL for the album
	EmbedUrl    string   // the URL of a SWF to embed the album
	DisplayDate string   // the release date of the album, human readable
	Key         string   // the key of the album
	ReleaseDate string   // the release date of the album
	Duration    int      // the duration of the album in seconds
}
<commit_msg>Stubbing out the rest of the types<commit_after>//
// A collection of Rdio API object types:
// http://developer.rdio.com/docs/read/rest/types
//

package rdio

type Album struct {
	Name        string   // the name of the album
	Type        string   // the type of the object, always "a"
	Icon        string   // the URL to the cover art for the album
	BaseIcon    string   // the URL to the cover art for the album
	Url         string   // the URL of the album on the Rdio site
	Artist      string   // the name of the artist that released the album
	ArtistUrl   string   // the URL of the artist that released the album on the Rdio site
	IsExplicit  bool     // is the album explicit?
	IsClean     bool     // is the album clean?
	Length      int      // number of tracks on the album
	ArtistKey   string   // the key of the artist that released the album
	TrackKeys   []string // the keys of the tracks on the album
	Price       string   // the price of the album in the requesting user's currency, if available for download
	CanStream   bool     // the album can be streamed
	CanSample   bool     // the album can be previewed
	CanTether   bool     // the album can be sync to mobile devices
	ShortUrl    string   // a short URL for the album
	EmbedUrl    string   // the URL of a SWF to embed the album
	DisplayDate string   // the release date of the album, human readable
	Key         string   // the key of the album
	ReleaseDate string   // the release date of the album
	Duration    int      // the duration of the album in seconds
}

type Artist struct {
	Name        string // the name of the artist
	Key         string // the artist's key
	Type        string // the object type, always "r"
	Url         string // the URL of the artist on the Rdio web site
	Length      string // the number of tracks that the artist has on Rdio
	Icon        string // an image for the artist
	BaseIcon    string // an image for the artist, partial URL
	HasRadio    string // is a station available for the artist?
	ShortUrl    string // a short URL for the artist page
	RadioKey    string // the key of the station for artist recommendations
	TopSongsKey string // the key of the station for the artist's top songs
}

type Label struct {
	Name     string // the name of the label
	Key      string // the key of the label
	Yype     string // the object type, always "l"
	Url      string // the url of the label on teh Rdio web site
	ShortUrl string // a short URL for the label page
	HasRadio string // is a station available for the label
	RadioKey string // the key of the station for label recommendations
}

type Track struct {
	Name                 string // the name of the track
	Artist               string // the name of the artist who performed the track
	Album                string // the name of the album that the track appears on
	AlbumKey             string // the key of the album that the track appears on
	AlbumUrl             string // the URL of the album that the track appears on, on the Rdio web site
	ArtistKey            string // the key of the track's artist
	ArtistUrl            string // the URL of the track's artist on the Rdio web site
	Type                 string // the object type, always "t"
	Length               string // the number of tracks in the track, ie: 1
	Duration             string // the duration of the track in seconds
	IsExplicit           string // is the track explicit?
	IsClean              string // is the track clean?
	Url                  string // the URL of the track on the Rdio web site
	BaseIcon             string // the partial URL of the album-art for the track
	AlbumArtist          string // the name of the artist whose album the track appears on
	AlbumArtistKey       string // the key of the artist whose album the track appears on
	CanDownload          string // the track can be downloaded
	CanDownloadAlbumOnly string // the track can only be downloaded as part of an album download
	CanStream            string // the track can be streamed
	CanTether            string // the track can be synced to mobile devices
	CanSample            string // the track can be previewed
	Price                string // the price of the album in the requesting user's currency, if available for download
	ShortUrl             string // a short URL for the track
	EmbedUrl             string // the URL of a SWF to embed the track
	Key                  string // the object key of the track
	Icon                 string // the URL of the album-art for the track
	RrackNum             string // the order within its album that this track appears
}

type Playlist struct {
	Name        string // the name of the playlist
	Length      string // the number of tracks in the playlist
	Type        string // the object type, always "p"
	Url         string // the URL of the playlist on the Rdio site
	Icon        string // the URL of an icon for the playlist
	BaseIcon    string // the URL of an icon for the playlist
	Owner       string // the name of the user who created the playlist
	OwnerUrl    string // the URL on the Rdio site of the user who created the playlist
	OwnerKey    string // the key of the user who created the playlist
	OwnerIcon   string // the icon of the user who created the playlist
	LastUpdated string // when the playlist was last modified
	ShortUrl    string // a short URL for the playlist
	EmbedUrl    string // the URL of a SWF to embed the playlist
	Key         string // the key of the playlist
}

type User struct {
	Key            string // the object key of the user
	FirstName      string // the first name of the user
	LastName       string // the last name of the user
	Icon           string // the URL of an image of the user
	BaseIcon       string // the URL of an image of the user
	LibraryVersion string // the library version of the user, used to determine if a user's collection has changed
	Url            string // the URL of the user on the Rdio site
	Gender         string // "m" or "f"
	Type           string // the object type, always "s"
}

type CollectionAlbum struct {
	Name          string // the name of the album
	Type          string // the object type of this object, always "al"
	Icon          string // the URL to the cover art for the album
	BaseIcon      string // the URL to the cover art for the album
	Url           string // the URL of the album on the Rdio site
	Artist        string // the name of the artist that released the album
	ArtistUrl     string // the URL of the artist that released the album on the Rdio site
	IsExplicit    string // is the album explicit?
	IsClean       string // is the album clean?
	Length        string // number of tracks on the album
	ArtistKey     string // the key of the artist that released the album
	TrackKeys     string // the keys of the tracks on the album
	Price         string // the price of the album in the requesting user's currency, if available for download
	CanStream     string // the album can be streamed
	CanSample     string // the album can be previewed
	CanTether     string // the album can be sync to mobile devices
	ShortUrl      string // a short URL for the album
	EmbedUrl      string // the URL of a SWF to embed the album
	DisplayDate   string // the release date of the album, human readable
	Key           string // the key of the album
	ReleaseDate   string // the release date of the album
	Duration      string // the duration of the album in seconds
	UserKey       string // the key of the user whose collection this album is in
	UserName      string // the username of the user whose collection this album is in
	AlbumKey      string // the key of the album
	AlbumUrl      string // the url of the album
	CollectionUrl string // the url to the collection
	ItemTrackKeys string // track keys for all tracks on the album
}

type CollectionArtist struct {
	Name          string // the name of the artist
	Key           string // the artist's key
	Type          string // the object type of this object, always "rl"
	Url           string // the URL of the artist on the Rdio web site
	Length        string // the number of tracks that the artist has on Rdio
	Icon          string // an image for the artist
	BaseIcon      string // an image for the artist, partial URL
	HasRadio      string // is a station available for the artist?
	ShortUrl      string // a short URL for the artist page
	RadioKey      string // the key of the station for artist recommendations
	TopSongsKey   string // the key of the station for the artist's top songs
	UserKey       string // the key of the user whose collection this artist is in
	UserName      string // the username of the user whose collection this artist is in
	ArtistKey     string // the key of the artist
	ArtistUrl     string // the url for the artist
	CollectionUrl string // the url to the collection
}

type LabelStation struct {
	Count          string // the number of tracks in the station
	LabelName      string // the name of the label
	Name           string // the name of the label station
	HasRadio       string // is a station available for the label
	Tracks         string // the tracks for the station
	LabelUrl       string // the URL of the label on the Rdio site
	ShortUrl       string // a short URL for the label page
	Length         string // the number of tracks in the station
	Url            string // the url of the label on teh Rdio web site
	Key            string // the key of the label
	RadioKey       string // the key of the station for label recommendations
	ReloadOnRepeat string // the station should be reloaded when it completes playing and repeat is enabled
	Type           string // the object type, always "lr"
}

type ArtistStation struct {
	RadioKey       string // the key of the station for artist recommendations
	TopSongsKey    string // the key of the station for the artist's top songs
	BaseIcon       string // an image for the artist, partial URL
	Tracks         string // the tracks for the station
	ArtistUrl      string // the URL of the artist on the Rdio site
	Key            string // the key of the station
	ReloadOnRepeat string // the station should be reloaded when it completes playing and repeat is enabled
	Icon           string // an image for the artist
	Count          string // the number of tracks in the station
	Name           string // the name of the station
	HasRadio       string // is a station available for the artist?
	Url            string // the URL of the artist on the Rdio web site
	ArtistName     string // the name of the artist
	ShortUrl       string // a short URL for the artist page
	Length         string // the number of tracks in the station
	Type           string // the object type, always "rr"
}

type HeavyRotationStation struct {
	Type           string // the object type, always "h"
	Key            string // the key of the station
	Length         string // the number of tracks in the station
	Tracks         string // the tracks for the station
	ReloadOnRepeat string // the station should be reloaded when it completes playing and repeat is enabled
	Count          string // the number of tracks in the station
	User           string // the user
	BaseIcon       string // the icon of the user
	Icon           string // the icon of the user
	Name           string //the name of the station
}

type HeavyRotationUserStation struct {
	Type           string // the object type, always "e"
	Key            string // the key of the station
	Length         string // the number of tracks in the station
	Tracks         string // the tracks for the station
	ReloadOnRepeat string // the station should be reloaded when it completes playing and repeat is enabled
	Count          string // the number of tracks in the station
	User           string // the user
	BaseIcon       string // the icon of the user
	Icon           string // the icon of the user
	Name           string //the name of the station
}

type ArtistTopSongsStation struct {
	RadioKey       string // the key of the station for artist recommendations
	TopSongsKey    string // the key of the station for the artist's top songs
	BaseIcon       string // an image for the artist, partial URL
	Tracks         string // the tracks for the station
	ArtistUrl      string // the URL of the artist on the Rdio site
	Key            string // the key of the station
	ReloadOnRepeat string // the station should be reloaded when it completes playing and repeat is enabled
	Icon           string // an image for the artist
	Count          string // the number of tracks in the station
	Name           string // the name of the station
	HasRadio       string // is a station available for the artist?
	Url            string // the URL of the artist on the Rdio web site
	ArtistName     string // the name of the artist
	ShortUrl       string // a short URL for the artist page
	Length         string // the number of tracks in the station
	Type           string // the object type, always "tr"
}

type UserCollectionStation struct {
	Type           string // the object type, always "c"
	Key            string // the key of the station
	Length         string // the number of tracks in the station
	Tracks         string // the tracks for the station
	ReloadOnRepeat string // the station should be reloaded when it completes playing and repeat is enabled
	Count          string // the number of tracks in the station
	User           string // the user
	BaseIcon       string // the icon of the user
	Icon           string // the icon of the user
	Name           string // the name of the station
	Url            string // the URL of the collection
}
<|endoftext|>


<commit_before>package gocsv

import (
	"encoding"
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

// --------------------------------------------------------------------------
// Conversion interfaces

// TypeMarshaller is implemented by any value that has a MarshalCSV method
// This converter is used to convert the value to it string representation
type TypeMarshaller interface {
	MarshalCSV() (string, error)
}

// Stringer is implemented by any value that has a String method
// This converter is used to convert the value to it string representation
// This converter will be used if your value does not implement TypeMarshaller
type Stringer interface {
	String() string
}

// TypeUnmarshaller is implemented by any value that has an UnmarshalCSV method
// This converter is used to convert a string to your value representation of that string
type TypeUnmarshaller interface {
	UnmarshalCSV(string) error
}

var (
	stringerType        = reflect.TypeOf((*Stringer)(nil)).Elem()
	marshallerType      = reflect.TypeOf((*TypeMarshaller)(nil)).Elem()
	unMarshallerType    = reflect.TypeOf((*TypeUnmarshaller)(nil)).Elem()
	textMarshalerType   = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
	textUnMarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
)

// --------------------------------------------------------------------------
// Conversion helpers

func toString(in interface{}) (string, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		return inValue.String(), nil
	case reflect.Bool:
		b := inValue.Bool()
		if b {
			return "true", nil
		}
		return "false", nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return fmt.Sprintf("%v", inValue.Int()), nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return fmt.Sprintf("%v", inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return strconv.FormatFloat(inValue.Float(), byte('f'), 64, 64), nil
	}
	return "", fmt.Errorf("No known conversion from " + inValue.Type().String() + " to string")
}

func toBool(in interface{}) (bool, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := inValue.String()
		if s == "true" || s == "yes" || s == "1" {
			return true, nil
		} else if s == "false" || s == "no" || s == "0" {
			return false, nil
		}
	case reflect.Bool:
		return inValue.Bool(), nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i := inValue.Int()
		if i != 0 {
			return true, nil
		}
		return false, nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		i := inValue.Uint()
		if i != 0 {
			return true, nil
		}
		return false, nil
	case reflect.Float32, reflect.Float64:
		f := inValue.Float()
		if f != 0 {
			return true, nil
		}
		return false, nil
	}
	return false, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to bool")
}

func toInt(in interface{}) (int64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		return strconv.ParseInt(inValue.String(), 0, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return inValue.Int(), nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return int64(inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return int64(inValue.Float()), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to int")
}

func toUint(in interface{}) (uint64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		return strconv.ParseUint(inValue.String(), 0, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return uint64(inValue.Int()), nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return inValue.Uint(), nil
	case reflect.Float32, reflect.Float64:
		return uint64(inValue.Float()), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to uint")
}

func toFloat(in interface{}) (float64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}
		return strconv.ParseFloat(s, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return float64(inValue.Int()), nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return float64(inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return inValue.Float(), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to float")
}

func setField(field reflect.Value, value string) error {
	switch field.Kind() {
	case reflect.String:
		s, err := toString(value)
		if err != nil {
			return err
		}
		field.SetString(s)
	case reflect.Bool:
		b, err := toBool(value)
		if err != nil {
			return err
		}
		field.SetBool(b)
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i, err := toInt(value)
		if err != nil {
			return err
		}
		field.SetInt(i)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		ui, err := toUint(value)
		if err != nil {
			return err
		}
		field.SetUint(ui)
	case reflect.Float32, reflect.Float64:
		f, err := toFloat(value)
		if err != nil {
			return err
		}
		field.SetFloat(f)
	default:
		return unmarshall(field, value)
	}
	return nil
}

func getFieldAsString(field reflect.Value) (str string, err error) {
	switch field.Kind() {
	case reflect.String:
		return field.String(), nil
	case reflect.Bool:
		str, err = toString(field.Bool())
		if err != nil {
			return str, err
		}
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		str, err = toString(field.Int())
		if err != nil {
			return str, err
		}
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		str, err = toString(field.Uint())
		if err != nil {
			return str, err
		}
	case reflect.Float32, reflect.Float64:
		str, err = toString(field.Float())
		if err != nil {
			return str, err
		}
	default:
		return marshall(field)
	}
	return str, nil
}

// --------------------------------------------------------------------------
// Un/serializations helpers

func unmarshall(field reflect.Value, value string) error {
	dupField := field
	unMarshallIt := func(finalField reflect.Value) error {
		if finalField.CanInterface() && finalField.Type().Implements(unMarshallerType) {
			if err := finalField.Interface().(TypeUnmarshaller).UnmarshalCSV(value); err != nil {
				return err
			}
			return nil
		} else if finalField.CanInterface() && finalField.Type().Implements(textUnMarshalerType) { // Otherwise try to use TextMarshaller
			if err := finalField.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)); err != nil {
				return err
			}
		}

		return fmt.Errorf("No known conversion from string to " + field.Type().String() + ", " + field.Type().String() + " does not implements TypeUnmarshaller")
	}
	for dupField.Kind() == reflect.Interface || dupField.Kind() == reflect.Ptr {
		if dupField.IsNil() {
			dupField = reflect.New(field.Type().Elem())
			field.Set(dupField)
			return unMarshallIt(dupField)
			break
		}
		dupField = dupField.Elem()
	}
	if dupField.CanAddr() {
		return unMarshallIt(dupField.Addr())
	}
	return fmt.Errorf("No known conversion from string to " + field.Type().String() + ", " + field.Type().String() + " does not implements TypeUnmarshaller")
}

func marshall(field reflect.Value) (value string, err error) {
	dupField := field
	marshallIt := func(finalField reflect.Value) (string, error) {
		if finalField.CanInterface() && finalField.Type().Implements(marshallerType) { // Use TypeMarshaller when possible
			return finalField.Interface().(TypeMarshaller).MarshalCSV()
		} else if finalField.CanInterface() && finalField.Type().Implements(stringerType) { // Otherwise try to use Stringer
			return finalField.Interface().(Stringer).String(), nil
		} else if finalField.CanInterface() && finalField.Type().Implements(textMarshalerType) { // Otherwise try to use TextMarshaller
			text, err := finalField.Interface().(encoding.TextMarshaler).MarshalText()
			return string(text), err
		}

		return value, fmt.Errorf("No known conversion from " + field.Type().String() + " to string, " + field.Type().String() + " does not implements TypeMarshaller nor Stringer")
	}
	for dupField.Kind() == reflect.Interface || dupField.Kind() == reflect.Ptr {
		if dupField.IsNil() {
			return value, nil
		}
		dupField = dupField.Elem()
	}
	if dupField.CanAddr() {
		return marshallIt(dupField.Addr())
	}
	return value, fmt.Errorf("No known conversion from " + field.Type().String() + " to string, " + field.Type().String() + " does not implements TypeMarshaller nor Stringer")
}
<commit_msg>Fix conversion from empty space to uint<commit_after>package gocsv

import (
	"encoding"
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

// --------------------------------------------------------------------------
// Conversion interfaces

// TypeMarshaller is implemented by any value that has a MarshalCSV method
// This converter is used to convert the value to it string representation
type TypeMarshaller interface {
	MarshalCSV() (string, error)
}

// Stringer is implemented by any value that has a String method
// This converter is used to convert the value to it string representation
// This converter will be used if your value does not implement TypeMarshaller
type Stringer interface {
	String() string
}

// TypeUnmarshaller is implemented by any value that has an UnmarshalCSV method
// This converter is used to convert a string to your value representation of that string
type TypeUnmarshaller interface {
	UnmarshalCSV(string) error
}

var (
	stringerType        = reflect.TypeOf((*Stringer)(nil)).Elem()
	marshallerType      = reflect.TypeOf((*TypeMarshaller)(nil)).Elem()
	unMarshallerType    = reflect.TypeOf((*TypeUnmarshaller)(nil)).Elem()
	textMarshalerType   = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
	textUnMarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
)

// --------------------------------------------------------------------------
// Conversion helpers

func toString(in interface{}) (string, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		return inValue.String(), nil
	case reflect.Bool:
		b := inValue.Bool()
		if b {
			return "true", nil
		}
		return "false", nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return fmt.Sprintf("%v", inValue.Int()), nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return fmt.Sprintf("%v", inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return strconv.FormatFloat(inValue.Float(), byte('f'), 64, 64), nil
	}
	return "", fmt.Errorf("No known conversion from " + inValue.Type().String() + " to string")
}

func toBool(in interface{}) (bool, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := inValue.String()
		if s == "true" || s == "yes" || s == "1" {
			return true, nil
		} else if s == "false" || s == "no" || s == "0" {
			return false, nil
		}
	case reflect.Bool:
		return inValue.Bool(), nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i := inValue.Int()
		if i != 0 {
			return true, nil
		}
		return false, nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		i := inValue.Uint()
		if i != 0 {
			return true, nil
		}
		return false, nil
	case reflect.Float32, reflect.Float64:
		f := inValue.Float()
		if f != 0 {
			return true, nil
		}
		return false, nil
	}
	return false, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to bool")
}

func toInt(in interface{}) (int64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		return strconv.ParseInt(inValue.String(), 0, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return inValue.Int(), nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return int64(inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return int64(inValue.Float()), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to int")
}

func toUint(in interface{}) (uint64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}
		return strconv.ParseUint(s, 0, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return uint64(inValue.Int()), nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return inValue.Uint(), nil
	case reflect.Float32, reflect.Float64:
		return uint64(inValue.Float()), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to uint")
}

func toFloat(in interface{}) (float64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}
		return strconv.ParseFloat(s, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return float64(inValue.Int()), nil
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return float64(inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return inValue.Float(), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to float")
}

func setField(field reflect.Value, value string) error {
	switch field.Kind() {
	case reflect.String:
		s, err := toString(value)
		if err != nil {
			return err
		}
		field.SetString(s)
	case reflect.Bool:
		b, err := toBool(value)
		if err != nil {
			return err
		}
		field.SetBool(b)
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i, err := toInt(value)
		if err != nil {
			return err
		}
		field.SetInt(i)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		ui, err := toUint(value)
		if err != nil {
			return err
		}
		field.SetUint(ui)
	case reflect.Float32, reflect.Float64:
		f, err := toFloat(value)
		if err != nil {
			return err
		}
		field.SetFloat(f)
	default:
		return unmarshall(field, value)
	}
	return nil
}

func getFieldAsString(field reflect.Value) (str string, err error) {
	switch field.Kind() {
	case reflect.String:
		return field.String(), nil
	case reflect.Bool:
		str, err = toString(field.Bool())
		if err != nil {
			return str, err
		}
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		str, err = toString(field.Int())
		if err != nil {
			return str, err
		}
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		str, err = toString(field.Uint())
		if err != nil {
			return str, err
		}
	case reflect.Float32, reflect.Float64:
		str, err = toString(field.Float())
		if err != nil {
			return str, err
		}
	default:
		return marshall(field)
	}
	return str, nil
}

// --------------------------------------------------------------------------
// Un/serializations helpers

func unmarshall(field reflect.Value, value string) error {
	dupField := field
	unMarshallIt := func(finalField reflect.Value) error {
		if finalField.CanInterface() && finalField.Type().Implements(unMarshallerType) {
			if err := finalField.Interface().(TypeUnmarshaller).UnmarshalCSV(value); err != nil {
				return err
			}
			return nil
		} else if finalField.CanInterface() && finalField.Type().Implements(textUnMarshalerType) { // Otherwise try to use TextMarshaller
			if err := finalField.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)); err != nil {
				return err
			}
		}

		return fmt.Errorf("No known conversion from string to " + field.Type().String() + ", " + field.Type().String() + " does not implements TypeUnmarshaller")
	}
	for dupField.Kind() == reflect.Interface || dupField.Kind() == reflect.Ptr {
		if dupField.IsNil() {
			dupField = reflect.New(field.Type().Elem())
			field.Set(dupField)
			return unMarshallIt(dupField)
			break
		}
		dupField = dupField.Elem()
	}
	if dupField.CanAddr() {
		return unMarshallIt(dupField.Addr())
	}
	return fmt.Errorf("No known conversion from string to " + field.Type().String() + ", " + field.Type().String() + " does not implements TypeUnmarshaller")
}

func marshall(field reflect.Value) (value string, err error) {
	dupField := field
	marshallIt := func(finalField reflect.Value) (string, error) {
		if finalField.CanInterface() && finalField.Type().Implements(marshallerType) { // Use TypeMarshaller when possible
			return finalField.Interface().(TypeMarshaller).MarshalCSV()
		} else if finalField.CanInterface() && finalField.Type().Implements(stringerType) { // Otherwise try to use Stringer
			return finalField.Interface().(Stringer).String(), nil
		} else if finalField.CanInterface() && finalField.Type().Implements(textMarshalerType) { // Otherwise try to use TextMarshaller
			text, err := finalField.Interface().(encoding.TextMarshaler).MarshalText()
			return string(text), err
		}

		return value, fmt.Errorf("No known conversion from " + field.Type().String() + " to string, " + field.Type().String() + " does not implements TypeMarshaller nor Stringer")
	}
	for dupField.Kind() == reflect.Interface || dupField.Kind() == reflect.Ptr {
		if dupField.IsNil() {
			return value, nil
		}
		dupField = dupField.Elem()
	}
	if dupField.CanAddr() {
		return marshallIt(dupField.Addr())
	}
	return value, fmt.Errorf("No known conversion from " + field.Type().String() + " to string, " + field.Type().String() + " does not implements TypeMarshaller nor Stringer")
}
<|endoftext|>


<commit_before>package certcenter

import (
	"fmt"
	"net/http"
	"time"
)

var Bearer string

const (
	CC_PARAM_TYPE_QS = 1 << iota
	CC_PARAM_TYPE_PATH
	CC_PARAM_TYPE_BODY
)

func checkErr(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

/* Represents an API request
 */
type apiRequest struct {
	method     string
	httpMethod string
	url        string
	result     interface{}
	request    interface{}
	client     *http.Client
	statusCode int
}

/* Represents a GET /Profile response
 */
type ProfileResult struct {
	AuthType        string
	AuthorizationID int64
	Country         string
	Currency        string
	CustomerID      int64
	Locale          string
	OAuth2_Token    string
	Scope           string
	Timezone        string
}

/* Represents a GET /Limit response
 */
type LimitResult struct {
	Success   bool `json:"success"`
	LimitInfo struct {
		Limit float64
		Used  float64
	}
}

/* Represents a GET /Products response
 */
type ProductsResult struct {
	Success  bool `json:"success"`
	Products []string
}

/* Represents a GET /ProductDetails response
 */
type ProductDetailsResult struct {
	Success        bool `json:"success"`
	ProductDetails struct {
		CA                string
		Currency          string
		Features          []string
		Licenses          int
		MaxValidityPeriod int
		Price             float64
		ProductCode       string
		ProductName       string
		RefundPeriod      int
		RenewPeriod       int
		SANFeatures       []string
		SANHostPrice      float64
		SANMaxHosts       int
		SANPackagePrice   float64
		SANPackageSize    int
	}
}

/* Represents a GET /ProductDetails request
 */
type ProductDetailsRequest struct {
	ProductCode string
}

/* Represents a GET /Quote response
 */
type QuoteResult struct {
	Success         bool `json:"success"`
	Currency        string
	OrderParameters struct {
		ProductCode         string
		ServerCount         int
		SubjectAltNameCount int
		ValidityPeriod      int
	}
	Price float64
}

/* Represents a GET /Quote request
 */
type QuoteRequest struct {
	ProductCode         string
	SubjectAltNameCount int
	ValidityPeriod      int
	ServerCount         int
}

/* Represents a POST /ValidateCSR response
 */
type ValidateCSRResult struct {
	Success   bool `json:"success"`
	ParsedCSR struct {
		CommonName             string
		Organization           string
		OrganizationUnit       string
		Email                  string
		State                  string
		Locality               string
		Country                string
		KeyLength              int
		SignaturAlgorithm      string
		KeyEncryptionAlgorithm string
	}
}

/* Represents a POST /ValidateCSR request
 */
type ValidateCSRRequest struct {
	CSR string // PEM-encoded PKCS#10
}

/* Represents a GET /ProductDetails response
 */
type UserAgreementRequest struct {
	ProductCode string
}

/* Represents a GET /ProductDetails request
 */
type UserAgreementResult struct {
	Success       bool `json:"success"`
	ProductCode   string
	UserAgreement string
}

/* Represents a GET /ApproverList response
 */
type ApproverListRequest struct {
	CommonName  string
	ProductCode string
}

/* Represents a GET /ApproverList request
 */
type ApproverListResult struct {
	Success      bool `json:"success"`
	ApproverList []struct {
		ApproverEmail string
		ApproverType  string // Domain, Generic
	}
}

/* Represents a POST /Order response
 */
type OrderResult struct {
	Success           bool `json:"success"`
	Timestamp         time.Time
	CertCenterOrderID int
	OrderParameters   struct {
		CSR                    string // PEM-encoded PKCS#10
		IsCompetitiveUpgrade   bool
		IsRenewal              bool
		PartnerOrderID         string
		ProductCode            string
		ServerCount            int
		SignatureHashAlgorithm string
		SubjectAltNameCount    int
		SubjectAltNames        []string
		ValidityPeriod         int // 12 or 24 month (days for AlwaysOnSSL, min. 180, max. 365)
		// AlwaysOnSSL (Symantec Encryption Everywhere) only:
		DVAuthMethod string // DNS, EMAIL

	}
	// AlwaysOnSSL (Symantec Encryption Everywhere) only:
	Fulfillment struct {
		Certificate       string
		Certificate_PKCS7 string
		Intermediate      string
	}
}

type OrderParameters struct {
	CSR                    string   // PEM-encoded PKCS#10
	IsCompetitiveUpgrade   bool     `json:",omitempty"`
	IsRenewal              bool     `json:",omitempty"`
	PartnerOrderID         string   `json:",omitempty"`
	ProductCode            string   `json:",omitempty"`
	ServerCount            int      `json:",omitempty"`
	SignatureHashAlgorithm string   `json:",omitempty"`
	SubjectAltNameCount    int      `json:",omitempty"`
	SubjectAltNames        []string `json:",omitempty"`
	ValidityPeriod         int      `json:",omitempty"` // 12 or 24 month (days for AlwaysOnSSL, min. 180, max. 365)
	// AlwaysOnSSL (Symantec Encryption Everywhere) only:
	DVAuthMethod  string `json:",omitempty"` // DNS, EMAIL
	ApproverEmail string `json:",omitempty"`
}

type Contact struct {
	Title               string              `json:",omitempty"`
	FirstName           string              `json:",omitempty"`
	LastName            string              `json:",omitempty"`
	OrganizationName    string              `json:",omitempty"`
	OrganizationAddress OrganizationAddress `json:",omitempty"`
	Phone               string              `json:",omitempty"`
	Fax                 string              `json:",omitempty"`
	Email               string              `json:",omitempty"`
}

type OrganizationAddress struct {
	AddressLine1 string `json:",omitempty"`
	PostalCode   string `json:",omitempty"`
	City         string `json:",omitempty"`
	Region       string `json:",omitempty"`
	Country      string `json:",omitempty"`
	Phone        string `json:",omitempty"`
	Fax          string `json:",omitempty"`
}

/* Represents a POST /Order request
 */
type OrderRequest struct {
	OrganizationInfo struct {
		OrganizationName    string              `json:",omitempty"`
		OrganizationAddress OrganizationAddress `json:",omitempty"`
	} `json:",omitempty"`
	OrderParameters OrderParameters `json:",omitempty"`
	AdminContact    Contact         `json:",omitempty"`
	TechContact     Contact         `json:",omitempty"`
}
<commit_msg>Few changes<commit_after>package certcenter

import (
	"fmt"
	"net/http"
	"time"
)

var Bearer string

const (
	// Param type is QueryString (eg. ?CertCenterOrderId=123)
	CC_PARAM_TYPE_QS = 1 << iota
	// Param type is Path (eg. /:CertCenterOrderId/)
	CC_PARAM_TYPE_PATH
	// Param type is Body (JSON POST)
	CC_PARAM_TYPE_BODY
)

func checkErr(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

/* Represents an API request
 */
type apiRequest struct {
	method     string
	httpMethod string
	url        string
	result     interface{}
	request    interface{}
	client     *http.Client
	statusCode int
}

/* ProfileResult represents a GET /Profile response
 */
type ProfileResult struct {
	AuthType        string
	AuthorizationID int64
	Country         string
	Currency        string
	CustomerID      int64
	Locale          string
	OAuth2_Token    string
	Scope           string
	Timezone        string
}

/* LimitResult represents a GET /Limit response
 */
type LimitResult struct {
	Success   bool `json:"success"`
	LimitInfo struct {
		Limit float64
		Used  float64
	}
}

/* ProductsResult represents a GET /Products response
 */
type ProductsResult struct {
	Success  bool `json:"success"`
	Products []string
}

/* ProductDetailsResult represents a GET /ProductDetails response
 */
type ProductDetailsResult struct {
	Success        bool `json:"success"`
	ProductDetails struct {
		CA                string
		Currency          string
		Features          []string
		Licenses          int
		MaxValidityPeriod int
		Price             float64
		ProductCode       string
		ProductName       string
		RefundPeriod      int
		RenewPeriod       int
		SANFeatures       []string
		SANHostPrice      float64
		SANMaxHosts       int
		SANPackagePrice   float64
		SANPackageSize    int
	}
}

/* ProductDetailsRequest represents a GET /ProductDetails request
 */
type ProductDetailsRequest struct {
	ProductCode string
}

/* QuoteResult represents a GET /Quote response
 */
type QuoteResult struct {
	Success         bool `json:"success"`
	Currency        string
	OrderParameters struct {
		ProductCode         string
		ServerCount         int
		SubjectAltNameCount int
		ValidityPeriod      int
	}
	Price float64
}

/* QuoteRequest represents a GET /Quote request
 */
type QuoteRequest struct {
	ProductCode         string
	SubjectAltNameCount int
	ValidityPeriod      int
	ServerCount         int
}

/* ValidateCSRResult represents a POST /ValidateCSR response
 */
type ValidateCSRResult struct {
	Success   bool `json:"success"`
	ParsedCSR struct {
		CommonName             string
		Organization           string
		OrganizationUnit       string
		Email                  string
		State                  string
		Locality               string
		Country                string
		KeyLength              int
		SignaturAlgorithm      string
		KeyEncryptionAlgorithm string
	}
}

/* ValidateCSRRequest represents a POST /ValidateCSR request
 */
type ValidateCSRRequest struct {
	CSR string // PEM-encoded PKCS#10
}

/* UserAgreementRequest represents a GET /ProductDetails response
 */
type UserAgreementRequest struct {
	ProductCode string
}

/* UserAgreementResult represents a GET /ProductDetails request
 */
type UserAgreementResult struct {
	Success       bool `json:"success"`
	ProductCode   string
	UserAgreement string
}

/* ApproverListRequest represents a GET /ApproverList response
 */
type ApproverListRequest struct {
	CommonName  string
	ProductCode string
}

/* ApproverListResult represents a GET /ApproverList request
 */
type ApproverListResult struct {
	Success      bool `json:"success"`
	ApproverList []struct {
		ApproverEmail string
		ApproverType  string // Domain, Generic
	}
}

/* OrderResult represents a POST /Order response
 */
type OrderResult struct {
	Success           bool `json:"success"`
	Timestamp         time.Time
	CertCenterOrderID int
	OrderParameters   struct {
		CSR                    string // PEM-encoded PKCS#10
		IsCompetitiveUpgrade   bool
		IsRenewal              bool
		PartnerOrderID         string
		ProductCode            string
		ServerCount            int
		SignatureHashAlgorithm string
		SubjectAltNameCount    int
		SubjectAltNames        []string
		ValidityPeriod         int // 12 or 24 month (days for AlwaysOnSSL, min. 180, max. 365)
		// AlwaysOnSSL (Symantec Encryption Everywhere) only:
		DVAuthMethod string // DNS, EMAIL

	}
	// AlwaysOnSSL (Symantec Encryption Everywhere) only:
	Fulfillment struct {
		Certificate       string
		Certificate_PKCS7 string
		Intermediate      string
	}
}

// OrderParameters represents generic Order Parameters
type OrderParameters struct {
	CSR                    string   // PEM-encoded PKCS#10
	IsCompetitiveUpgrade   bool     `json:",omitempty"`
	IsRenewal              bool     `json:",omitempty"`
	PartnerOrderID         string   `json:",omitempty"`
	ProductCode            string   `json:",omitempty"`
	ServerCount            int      `json:",omitempty"`
	SignatureHashAlgorithm string   `json:",omitempty"`
	SubjectAltNameCount    int      `json:",omitempty"`
	SubjectAltNames        []string `json:",omitempty"`
	ValidityPeriod         int      `json:",omitempty"` // 12 or 24 month (days for AlwaysOnSSL, min. 180, max. 365)
	// AlwaysOnSSL (Symantec Encryption Everywhere) only:
	DVAuthMethod  string `json:",omitempty"` // DNS, EMAIL
	ApproverEmail string `json:",omitempty"`
}

// Contact represents a generic Contact type (for AdminContact and TechContact)
type Contact struct {
	Title               string              `json:",omitempty"`
	FirstName           string              `json:",omitempty"`
	LastName            string              `json:",omitempty"`
	OrganizationName    string              `json:",omitempty"`
	OrganizationAddress OrganizationAddress `json:",omitempty"`
	Phone               string              `json:",omitempty"`
	Fax                 string              `json:",omitempty"`
	Email               string              `json:",omitempty"`
}

// OrganizationAddress holds general information about a organization
type OrganizationAddress struct {
	AddressLine1 string `json:",omitempty"`
	PostalCode   string `json:",omitempty"`
	City         string `json:",omitempty"`
	Region       string `json:",omitempty"`
	Country      string `json:",omitempty"`
	Phone        string `json:",omitempty"`
	Fax          string `json:",omitempty"`
}

/* OrderRequest represents a POST /Order request
 */
type OrderRequest struct {
	OrganizationInfo struct {
		OrganizationName    string              `json:",omitempty"`
		OrganizationAddress OrganizationAddress `json:",omitempty"`
	} `json:",omitempty"`
	OrderParameters OrderParameters `json:",omitempty"`
	AdminContact    Contact         `json:",omitempty"`
	TechContact     Contact         `json:",omitempty"`
}
<|endoftext|>


<commit_before>package ui

import (
	"fmt"
	"log"

	"github.com/jroimartin/gocui"
)

// UI contains the UI data.
type UI struct {
	gui   *gocui.Gui
	sh    shutdownHandler
	msgCh chan string
}

type shutdownHandler func()

const (
	// UsersView defines a view containing a list of users.
	UsersView string = "users"
	// ChatView defines a view containing the main chat.
	ChatView string = "chat"
	// TextView defines a view containing an input text.
	TextView string = "text"
)

// DeployGUI deploys the GUI.
func DeployGUI(sh shutdownHandler, msgCh chan string) (ui *UI, err error) {
	// Initializing a new GUI.
	g := gocui.NewGui()
	err = g.Init()
	if err != nil {
		return
	}

	ui = &UI{
		gui:   g,
		sh:    sh,
		msgCh: msgCh,
	}

	// Setting the desired layout by passing the corresponding handler to the GUI method.
	g.SetLayout(ui.layout)

	// Setting Ctr+C binding.
	err = g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit)
	if err != nil {
		return
	}

	// Setting Ctr+S binding.
	err = g.SetKeybinding(TextView, gocui.KeyCtrlS, gocui.ModNone, ui.processText)
	if err != nil {
		return
	}

	// We want the cursor to be visible.
	g.Cursor = true

	// Executing the main loop within the routine in order to perform
	// further actions.
	go func() {
		// This loop is going to run while the GUI is active (the same logic as in GTK+).
		err := g.MainLoop()
		if err != nil && err != gocui.ErrQuit {
			log.Fatal(err)
		}
		// Getting to this part only after the "quit" handler has been called and closed.
		g.Close()
		ui.sh()
	}()

	return
}

// WriteToView writes the message into the requested view.
func (u *UI) WriteToView(view, msg string) {
	u.gui.Execute(func(g *gocui.Gui) error {
		v, err := g.View(view)
		if err != nil {
			return err
		}
		fmt.Fprintln(v, msg)
		return nil
	})
}

func (u *UI) layout(g *gocui.Gui) (err error) {
	// Retrieving the terminal's size.
	maxX, maxY := g.Size()

	// Setting the users list view.
	_, err = g.SetView(UsersView, 0, 0, maxX/5, maxY-1)
	if err != nil && err != gocui.ErrUnknownView {
		return
	}

	// Setting the chat history view.
	_, err = g.SetView(ChatView, maxX/5+1, 0, maxX-1, maxY*4/5)
	if err != nil && err != gocui.ErrUnknownView {
		return
	}

	// Setting the text editor view.
	var tView *gocui.View
	tView, err = g.SetView(TextView, maxX/5+1, maxY*4/5+1, maxX-1, maxY-1)
	if err != nil && err != gocui.ErrUnknownView {
		return
	}
	// The text ditor view must be editable.
	tView.Editable = true
	// Also it's better to start the execution with the focus given to the text view.
	err = g.SetCurrentView(TextView)
	if err != nil {
		return
	}

	return
}

func (u *UI) processText(g *gocui.Gui, v *gocui.View) (err error) {
	bufferStr := v.ViewBuffer()
	if bufferStr == "" {
		return
	}
	u.msgCh <- bufferStr[:len(bufferStr)-1]
	v.Clear()
	v.SetCursor(0, 0)
	return
}

// the quit handler is being called as we press the Ctr+C combination and returns
// the corresponding error to the running GUI.
func quit(g *gocui.Gui, v *gocui.View) error {
	return gocui.ErrQuit
}
<commit_msg>added chat view autoscroll<commit_after>package ui

import (
	"fmt"
	"log"

	"github.com/jroimartin/gocui"
)

// UI contains the UI data.
type UI struct {
	gui   *gocui.Gui
	sh    shutdownHandler
	msgCh chan string
}

type shutdownHandler func()

const (
	// UsersView defines a view containing a list of users.
	UsersView string = "users"
	// ChatView defines a view containing the main chat.
	ChatView string = "chat"
	// TextView defines a view containing an input text.
	TextView string = "text"
)

// DeployGUI deploys the GUI.
func DeployGUI(sh shutdownHandler, msgCh chan string) (ui *UI, err error) {
	// Initializing a new GUI.
	g := gocui.NewGui()
	err = g.Init()
	if err != nil {
		return
	}

	ui = &UI{
		gui:   g,
		sh:    sh,
		msgCh: msgCh,
	}

	// Setting the desired layout by passing the corresponding handler to the GUI method.
	g.SetLayout(ui.layout)

	// Setting Ctr+C binding.
	err = g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit)
	if err != nil {
		return
	}

	// Setting Ctr+S binding.
	err = g.SetKeybinding(TextView, gocui.KeyCtrlS, gocui.ModNone, ui.processText)
	if err != nil {
		return
	}

	// We want the cursor to be visible.
	g.Cursor = true

	// Executing the main loop within the routine in order to perform
	// further actions.
	go func() {
		// This loop is going to run while the GUI is active (the same logic as in GTK+).
		err := g.MainLoop()
		if err != nil && err != gocui.ErrQuit {
			log.Fatal(err)
		}
		// Getting to this part only after the "quit" handler has been called and closed.
		g.Close()
		ui.sh()
	}()

	return
}

// WriteToView writes the message into the requested view.
func (u *UI) WriteToView(view, msg string) {
	u.gui.Execute(func(g *gocui.Gui) error {
		v, err := g.View(view)
		if err != nil {
			return err
		}
		fmt.Fprintln(v, msg)
		return nil
	})
}

func (u *UI) layout(g *gocui.Gui) (err error) {
	// Retrieving the terminal's size.
	maxX, maxY := g.Size()

	// Setting the users list view.
	_, err = g.SetView(UsersView, 0, 0, maxX/5, maxY-1)
	if err != nil && err != gocui.ErrUnknownView {
		return
	}

	// Setting the chat history view.
	var cView *gocui.View
	cView, err = g.SetView(ChatView, maxX/5+1, 0, maxX-1, maxY*4/5)
	if err != nil && err != gocui.ErrUnknownView {
		return
	}
	cView.Autoscroll = true

	// Setting the text editor view.
	var tView *gocui.View
	tView, err = g.SetView(TextView, maxX/5+1, maxY*4/5+1, maxX-1, maxY-1)
	if err != nil && err != gocui.ErrUnknownView {
		return
	}
	// The text ditor view must be editable.
	tView.Editable = true
	// Also it's better to start the execution with the focus given to the text view.
	err = g.SetCurrentView(TextView)
	if err != nil {
		return
	}

	return
}

func (u *UI) processText(g *gocui.Gui, v *gocui.View) (err error) {
	bufferStr := v.ViewBuffer()
	if bufferStr == "" {
		return
	}
	u.msgCh <- bufferStr[:len(bufferStr)-1]
	v.Clear()
	v.SetCursor(0, 0)
	return
}

// the quit handler is being called as we press the Ctr+C combination and returns
// the corresponding error to the running GUI.
func quit(g *gocui.Gui, v *gocui.View) error {
	return gocui.ErrQuit
}
<|endoftext|>


<commit_before>// +build test

package consensus

import (
	"math/big"
	"time"
)

const (
	DEBUG = true

	BlockSizeLimit        = 1e6         // Blocks cannot be more than 1MB.
	BlockFrequency        = 1           // In seconds.
	TargetWindow          = 1e3         // Number of blocks to use when calculating the target.
	MedianTimestampWindow = 11          // Number of blocks that get considered when determining if a timestamp is valid - should be an odd number.
	FutureThreshold       = 3 * 60 * 60 // Seconds into the future block timestamps are valid.
	SiafundCount          = 10e3        // The total (static) number of siafunds.
	MaturityDelay         = 3           // The number of blocks that need to be waited before certain types of outputs come to maturity.
	SiafundPortion        = 0.039       // Percent of all contract payouts that go to the siafund pool.

	InitialCoinbase = 300e3
	MinimumCoinbase = 299990
)

var (
	RootTarget = Target{64}
	RootDepth  = Target{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}

	MaxAdjustmentUp   = big.NewRat(10001, 10000)
	MaxAdjustmentDown = big.NewRat(9999, 10000)

	CoinbaseAugment = new(big.Int).Lsh(big.NewInt(1), 80)

	GenesisTimestamp         = Timestamp(time.Now().Unix())
	GenesisSiafundUnlockHash = ZeroUnlockHash
	GenesisClaimUnlockHash   = ZeroUnlockHash
)
<commit_msg>add comment to test constant<commit_after>// +build test

package consensus

import (
	"math/big"
	"time"
)

const (
	DEBUG = true

	BlockSizeLimit        = 1e6         // Blocks cannot be more than 1MB.
	BlockFrequency        = 1           // In seconds.
	TargetWindow          = 1e3         // Number of blocks to use when calculating the target.
	MedianTimestampWindow = 11          // Number of blocks that get considered when determining if a timestamp is valid - should be an odd number.
	FutureThreshold       = 3 * 60 * 60 // Seconds into the future block timestamps are valid.
	SiafundCount          = 10e3        // The total (static) number of siafunds.
	MaturityDelay         = 3           // The number of blocks that need to be waited before certain types of outputs come to maturity.
	SiafundPortion        = 0.039       // Percent of all contract payouts that go to the siafund pool.

	InitialCoinbase = 300e3
	MinimumCoinbase = 299990 // Only takes 10 blocks to hit the max - useful for testing.
)

var (
	RootTarget = Target{64}
	RootDepth  = Target{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}

	MaxAdjustmentUp   = big.NewRat(10001, 10000)
	MaxAdjustmentDown = big.NewRat(9999, 10000)

	CoinbaseAugment = new(big.Int).Lsh(big.NewInt(1), 80)

	GenesisTimestamp         = Timestamp(time.Now().Unix())
	GenesisSiafundUnlockHash = ZeroUnlockHash
	GenesisClaimUnlockHash   = ZeroUnlockHash
)
<|endoftext|>


<commit_before>// Copyright 2016 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.

package version

var (
	// Major is the current major version of master branch.
	Major = 0
	// Minor is the current minor version of master branch.
	Minor = 4
	// Patch is the current patched version of the master branch.
	Patch = 3
	// Release is the current release level of the master branch. Valid values
	// are dev (development unreleased), rcX (release candidate with current
	// iteration), stable (indicates a final released version).
	Release = "dev"
)
<commit_msg>Promote 0.4.3-dev to 0.5.0-stable<commit_after>// Copyright 2016 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.

package version

var (
	// Major is the current major version of master branch.
	Major = 0
	// Minor is the current minor version of master branch.
	Minor = 5
	// Patch is the current patched version of the master branch.
	Patch = 0
	// Release is the current release level of the master branch. Valid values
	// are dev (development unreleased), rcX (release candidate with current
	// iteration), stable (indicates a final released version).
	Release = "stable"
)
<|endoftext|>


<commit_before>package gopymarshal

import (
	"bytes"
	"encoding/binary"
	"errors"
	"math"
)

const (
	CODE_NONE      = 'N' //None
	CODE_INT       = 'i' //integer
	CODE_INT2      = 'c' //integer2
	CODE_FLOAT     = 'g' //float
	CODE_STRING    = 's' //string
	CODE_UNICODE   = 'u' //unicode string
	CODE_TSTRING   = 't' //tstring?
	CODE_TUPLE     = '(' //tuple
	CODE_LIST      = '[' //list
	CODE_DICT      = '{' //dict
	CODE_STOP      = '0'
	DICT_INIT_SIZE = 64
)

var (
	ERR_PARSE        = errors.New("invalid data")
	ERR_UNKNOWN_CODE = errors.New("unknown code")
)

// Unmarshal data serialized by python
func Unmarshal(buffer *bytes.Buffer) (ret interface{}, retErr error) {
	ret, _, retErr = Unmarshal2(data)
	return
}

// Unmarshal data serialized by python, returning the unused portion.
func Unmarshal2(buffer *bytes.Buffer) (ret interface{}, remainder []byte, retErr error) {
	code, err := buffer.ReadByte()
	if nil != err {
		retErr = err
	}

	ret, retErr = unmarshal(code, buffer)
	remainder = buffer.Bytes()
	return
}

func unmarshal(code byte, buffer *bytes.Buffer) (ret interface{}, retErr error) {
	switch code {
	case CODE_NONE:
		ret = nil
	case CODE_INT:
		fallthrough
	case CODE_INT2:
		ret, retErr = readInt32(buffer)
	case CODE_FLOAT:
		ret, retErr = readFloat64(buffer)
	case CODE_STRING:
		fallthrough
	case CODE_UNICODE:
		fallthrough
	case CODE_TSTRING:
		ret, retErr = readString(buffer)
	case CODE_TUPLE:
		fallthrough
	case CODE_LIST:
		ret, retErr = readList(buffer)
	case CODE_DICT:
		ret, retErr = readDict(buffer)
	default:
		retErr = ERR_UNKNOWN_CODE
	}

	return
}

func readInt32(buffer *bytes.Buffer) (ret int32, retErr error) {
	var tmp int32
	retErr = ERR_PARSE
	if retErr = binary.Read(buffer, binary.LittleEndian, &tmp); nil == retErr {
		ret = tmp
	}

	return
}

func readFloat64(buffer *bytes.Buffer) (ret float64, retErr error) {
	retErr = ERR_PARSE
	tmp := make([]byte, 8)
	if num, err := buffer.Read(tmp); nil == err && 8 == num {
		bits := binary.LittleEndian.Uint64(tmp)
		ret = math.Float64frombits(bits)
		retErr = nil
	}

	return
}

func readString(buffer *bytes.Buffer) (ret string, retErr error) {
	var strLen int32
	strLen = 0
	retErr = ERR_PARSE
	if err := binary.Read(buffer, binary.LittleEndian, &strLen); nil != err {
		retErr = err
		return
	}

	retErr = nil
	buf := make([]byte, strLen)
	buffer.Read(buf)
	ret = string(buf)
	return
}

func readList(buffer *bytes.Buffer) (ret []interface{}, retErr error) {
	var listSize int32
	if retErr = binary.Read(buffer, binary.LittleEndian, &listSize); nil != retErr {
		return
	}

	var code byte
	var err error
	var val interface{}
	ret = make([]interface{}, int(listSize))
	for idx := 0; idx < int(listSize); idx++ {
		code, err = buffer.ReadByte()
		if nil != err {
			break
		}

		val, err = unmarshal(code, buffer)
		if nil != err {
			retErr = err
			break
		}
		ret = append(ret, val)
	} //end of read loop

	return
}

func readDict(buffer *bytes.Buffer) (ret map[interface{}]interface{}, retErr error) {
	var code byte
	var err error
	var key interface{}
	var val interface{}
	ret = make(map[interface{}]interface{})
	for {
		code, err = buffer.ReadByte()
		if nil != err {
			break
		}

		if CODE_STOP == code {
			break
		}

		key, err = unmarshal(code, buffer)
		if nil != err {
			retErr = err
			break
		}

		code, err = buffer.ReadByte()
		if nil != err {
			break
		}

		val, err = unmarshal(code, buffer)
		if nil != err {
			retErr = err
			break
		}
		ret[key] = val
	} //end of read loop

	return
}
<commit_msg>fix unmatched function argument<commit_after>package gopymarshal

import (
	"bytes"
	"encoding/binary"
	"errors"
	"math"
)

const (
	CODE_NONE      = 'N' //None
	CODE_INT       = 'i' //integer
	CODE_INT2      = 'c' //integer2
	CODE_FLOAT     = 'g' //float
	CODE_STRING    = 's' //string
	CODE_UNICODE   = 'u' //unicode string
	CODE_TSTRING   = 't' //tstring?
	CODE_TUPLE     = '(' //tuple
	CODE_LIST      = '[' //list
	CODE_DICT      = '{' //dict
	CODE_STOP      = '0'
	DICT_INIT_SIZE = 64
)

var (
	ERR_PARSE        = errors.New("invalid data")
	ERR_UNKNOWN_CODE = errors.New("unknown code")
)

// Unmarshal data serialized by python
func Unmarshal(buffer *bytes.Buffer) (ret interface{}, retErr error) {
	ret, _, retErr = Unmarshal2(buffer)
	return
}

// Unmarshal data serialized by python, returning the unused portion.
func Unmarshal2(buffer *bytes.Buffer) (ret interface{}, remainder []byte, retErr error) {
	code, err := buffer.ReadByte()
	if nil != err {
		retErr = err
	}

	ret, retErr = unmarshal(code, buffer)
	remainder = buffer.Bytes()
	return
}

func unmarshal(code byte, buffer *bytes.Buffer) (ret interface{}, retErr error) {
	switch code {
	case CODE_NONE:
		ret = nil
	case CODE_INT:
		fallthrough
	case CODE_INT2:
		ret, retErr = readInt32(buffer)
	case CODE_FLOAT:
		ret, retErr = readFloat64(buffer)
	case CODE_STRING:
		fallthrough
	case CODE_UNICODE:
		fallthrough
	case CODE_TSTRING:
		ret, retErr = readString(buffer)
	case CODE_TUPLE:
		fallthrough
	case CODE_LIST:
		ret, retErr = readList(buffer)
	case CODE_DICT:
		ret, retErr = readDict(buffer)
	default:
		retErr = ERR_UNKNOWN_CODE
	}

	return
}

func readInt32(buffer *bytes.Buffer) (ret int32, retErr error) {
	var tmp int32
	retErr = ERR_PARSE
	if retErr = binary.Read(buffer, binary.LittleEndian, &tmp); nil == retErr {
		ret = tmp
	}

	return
}

func readFloat64(buffer *bytes.Buffer) (ret float64, retErr error) {
	retErr = ERR_PARSE
	tmp := make([]byte, 8)
	if num, err := buffer.Read(tmp); nil == err && 8 == num {
		bits := binary.LittleEndian.Uint64(tmp)
		ret = math.Float64frombits(bits)
		retErr = nil
	}

	return
}

func readString(buffer *bytes.Buffer) (ret string, retErr error) {
	var strLen int32
	strLen = 0
	retErr = ERR_PARSE
	if err := binary.Read(buffer, binary.LittleEndian, &strLen); nil != err {
		retErr = err
		return
	}

	retErr = nil
	buf := make([]byte, strLen)
	buffer.Read(buf)
	ret = string(buf)
	return
}

func readList(buffer *bytes.Buffer) (ret []interface{}, retErr error) {
	var listSize int32
	if retErr = binary.Read(buffer, binary.LittleEndian, &listSize); nil != retErr {
		return
	}

	var code byte
	var err error
	var val interface{}
	ret = make([]interface{}, int(listSize))
	for idx := 0; idx < int(listSize); idx++ {
		code, err = buffer.ReadByte()
		if nil != err {
			break
		}

		val, err = unmarshal(code, buffer)
		if nil != err {
			retErr = err
			break
		}
		ret = append(ret, val)
	} //end of read loop

	return
}

func readDict(buffer *bytes.Buffer) (ret map[interface{}]interface{}, retErr error) {
	var code byte
	var err error
	var key interface{}
	var val interface{}
	ret = make(map[interface{}]interface{})
	for {
		code, err = buffer.ReadByte()
		if nil != err {
			break
		}

		if CODE_STOP == code {
			break
		}

		key, err = unmarshal(code, buffer)
		if nil != err {
			retErr = err
			break
		}

		code, err = buffer.ReadByte()
		if nil != err {
			break
		}

		val, err = unmarshal(code, buffer)
		if nil != err {
			retErr = err
			break
		}
		ret[key] = val
	} //end of read loop

	return
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	. "github.com/rthornton128/goncurses"
	"os"
	"strings"
	"time"
	"github.com/ChimeraCoder/anaconda"
)

func main() {

	// check to see if the config file exists
	// if it doesn't, create it and ask for API keys

	if _, err := os.Stat("$HOME/.config/spoon/config"); err != nil {
		fmt.Println(`Hello there! It looks like this is your first time running spoon
			or you've misplaced your configuration file. We're gonna need those Twitter keys
			again - actually, do you even use Twitter?`)
	}
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("y/n: ")
	text, _ := reader.ReadString('\n')
	var tweets []anaconda.Tweet
	if strings.TrimSpace(text) == "y" {
		fmt.Println(`Alright, now hand over your keys.
			Consumer key first, then the secret consumer key.`)
		ck, _ := reader.ReadString('\n')
		csk, _ := reader.ReadString('\n')
		fmt.Println(`Okay, great. Now we'll also need your Access Token and
			Access Token Secret to fire up the reader.`)
		at, _ := reader.ReadString('\n')
		ats, _ := reader.ReadString('\n')
		ck = strings.TrimSpace(ck)
		csk = strings.TrimSpace(csk)
		at = strings.TrimSpace(at)
		ats = strings.TrimSpace(ats)
		api, tweets = createAPI(ck, csk, at, ats)
	}

	stdscr, err := Init()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	defer End()

	stdscr.MovePrint(3, 0, "q to quit")
	stdscr.Refresh()
	rows, cols := stdscr.MaxYX()
	window, _ := NewWindow(1, cols, rows-1, 0)
	mx, my := window.MaxYX()
	StartColor()
	InitPair(1, C_BLACK, C_YELLOW)
	InitPair(2, C_WHITE, C_BLACK)
	InitPair(3, C_BLUE, C_BLACK)
	window.ColorOn(int16(1))
	// TODO: change time format so it's better
	barinfo := time.Now().Format(time.RFC822)

	window.MovePrint(mx/2, my-len(barinfo)-2, barinfo)
	window.ColorOff(int16(1))
	bgc := ColorPair(int16(1))
	window.SetBackground(bgc)
	NewPanel(window)

main:
	for {
		UpdatePanels()
		Update()
		updateTimeline(api)

		for i:=0; i<len(tweets); i++ {
			stdscr.ColorOn(2)
			stdscr.Print(tweets[i].CreatedAt + " ")
			stdscr.ColorOff(2)
			stdscr.ColorOn(3)
			stdscr.AttrOn(A_BOLD)
			stdscr.Print(tweets[i].User.ScreenName + "   ")
			stdscr.AttrOff(A_BOLD)
			stdscr.ColorOff(3)
			stdscr.Println(tweets[i].Text)
		}

		nrows, ncols := stdscr.MaxYX()
		if nrows != mx || ncols != my {
//			goto redraw
		}
		ch := stdscr.GetChar()
		switch Key(ch) {
		case 'q':
			break main
		case KEY_TAB:
			// rotate focus between feed, expanded feed (if present), and bbar
		case KEY_RIGHT:
			// if focus is on bbar, scrolls through feeds
		case KEY_LEFT:
			// same shit
		case KEY_UP:
			// scroll through feed or expanded feed
		case KEY_DOWN:
			// same shit
		case KEY_ENTER:
			// expands feed if feed is focused, selects feed if bbar is focused

		}
	}
}
<commit_msg>cleaned up timestamps and etc<commit_after>package main

import (
	"bufio"
	"fmt"
	. "github.com/rthornton128/goncurses"
	"os"
	"strings"
	"time"
	"github.com/ChimeraCoder/anaconda"
)

func main() {

	// check to see if the config file exists
	// if it doesn't, create it and ask for API keys

	if _, err := os.Stat("$HOME/.config/spoon/config"); err != nil {
		fmt.Println(`Hello there! It looks like this is your first time running spoon
			or you've misplaced your configuration file. We're gonna need those Twitter keys
			again - actually, do you even use Twitter?`)
	}
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("y/n: ")
	text, _ := reader.ReadString('\n')
	var tweets []anaconda.Tweet
	if strings.TrimSpace(text) == "y" {
		fmt.Println(`Alright, now hand over your keys.
			Consumer key first, then the secret consumer key.`)
		ck, _ := reader.ReadString('\n')
		csk, _ := reader.ReadString('\n')
		fmt.Println(`Okay, great. Now we'll also need your Access Token and
			Access Token Secret to fire up the reader.`)
		at, _ := reader.ReadString('\n')
		ats, _ := reader.ReadString('\n')
		ck = strings.TrimSpace(ck)
		csk = strings.TrimSpace(csk)
		at = strings.TrimSpace(at)
		ats = strings.TrimSpace(ats)
		api, tweets = createAPI(ck, csk, at, ats)
	}

	stdscr, err := Init()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	defer End()

	stdscr.Refresh()
	rows, cols := stdscr.MaxYX()
	window, _ := NewWindow(1, cols, rows-1, 0)
	mx, my := window.MaxYX()
	StartColor()
	InitPair(1, C_BLACK, C_YELLOW)
	InitPair(2, C_WHITE, C_BLACK)
	InitPair(3, C_BLUE, C_BLACK)
	window.ColorOn(int16(1))
	// TODO: change time format so it's better
	barinfo := time.Now().Format(time.RFC822)

	window.MovePrint(mx/2, my-len(barinfo)-2, barinfo)
	window.ColorOff(int16(1))
	bgc := ColorPair(int16(1))
	window.SetBackground(bgc)
	NewPanel(window)

main:
	for {
		UpdatePanels()
		Update()
		updateTimeline(api)

		for i:=0; i<len(tweets); i++ {
			t, _ := time.Parse(time.RubyDate, tweets[i].CreatedAt)
			stdscr.ColorOn(2)
			stdscr.Print(t.Format("15:04:05") + " ")
			stdscr.ColorOff(2)
			stdscr.ColorOn(3)
			stdscr.AttrOn(A_BOLD)
			stdscr.Print(tweets[i].User.ScreenName)
			stdscr.AttrOff(A_BOLD)
			stdscr.ColorOff(3)
			stdscr.Print("  ")
			UseDefaultColors()
			stdscr.Println(tweets[i].Text)
		}

		nrows, ncols := stdscr.MaxYX()
		if nrows != mx || ncols != my {
//			goto redraw
		}
		ch := stdscr.GetChar()
		switch Key(ch) {
		case 'q':
			break main
		case KEY_TAB:
			// rotate focus between feed, expanded feed (if present), and bbar
		case KEY_RIGHT:
			// if focus is on bbar, scrolls through feeds
		case KEY_LEFT:
			// same shit
		case KEY_UP:
			// scroll through feed or expanded feed
		case KEY_DOWN:
			// same shit
		case KEY_ENTER:
			// expands feed if feed is focused, selects feed if bbar is focused

		}
	}
}
<|endoftext|>


<commit_before>// (C) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// 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 oneview

import (
	"fmt"
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/HewlettPackard/oneview-golang/utils"
	"github.com/hashicorp/terraform/helper/schema"
	"strconv"
)

func resourceServerProfileTemplate() *schema.Resource {
	return &schema.Resource{
		Create: resourceServerProfileTemplateCreate,
		Read:   resourceServerProfileTemplateRead,
		Update: resourceServerProfileTemplateUpdate,
		Delete: resourceServerProfileTemplateDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"boot_order": {
				Type:     schema.TypeSet,
				Optional: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Set:      schema.HashString,
			},
			"network": {
				Optional: true,
				Type:     schema.TypeList,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"name": {
							Type:     schema.TypeString,
							Required: true,
						},
						"function_type": {
							Type:     schema.TypeString,
							Required: true,
						},
						"network_uri": {
							Type:     schema.TypeString,
							Required: true,
						},
						"port_id": {
							Type:     schema.TypeString,
							Optional: true,
							Default:  "Lom 1:1-a",
						},
						"requested_mbps": {
							Type:     schema.TypeString,
							Optional: true,
							Default:  "2500",
						},
						"id": {
							Type:     schema.TypeInt,
							Computed: true,
						},
					},
				},
			},
			"type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "ServerProfileTemplateV1",
			},
			"server_hardware_type": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"enclosure_group": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"affinity": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Bay",
			},
			"hide_unused_flex_nics": {
				Type:     schema.TypeBool,
				Optional: true,
				Default:  true,
			},
			"uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"etag": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"serial_number_type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Virtual",
				ForceNew: true,
			},
			"wwn_type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Virtual",
				ForceNew: true,
			},
			"mac_type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Virtual",
				ForceNew: true,
			},
		},
	}
}

func resourceServerProfileTemplateCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	serverProfileTemplate := ov.ServerProfile{
		Name:               d.Get("name").(string),
		Type:               d.Get("type").(string),
		Affinity:           d.Get("affinity").(string),
		SerialNumberType:   d.Get("serial_number_type").(string),
		WWNType:            d.Get("wwn_type").(string),
		MACType:            d.Get("mac_type").(string),
		HideUnusedFlexNics: d.Get("hide_unused_flex_nics").(bool),
	}

	enclosureGroup, err := config.ovClient.GetEnclosureGroupByName(d.Get("enclosure_group").(string))
	if err != nil {
		return err
	}
	serverProfileTemplate.EnclosureGroupURI = enclosureGroup.URI

	serverHardwareType, err := config.ovClient.GetServerHardwareTypeByName(d.Get("server_hardware_type").(string))
	if err != nil {
		return err
	}
	serverProfileTemplate.ServerHardwareTypeURI = serverHardwareType.URI

	networkCount := d.Get("network.#").(int)
	networks := make([]ov.Connection, 0)
	for i := 0; i < networkCount; i++ {
		networkPrefix := fmt.Sprintf("network.%d", i)
		networks = append(networks, ov.Connection{
			Name:          d.Get(networkPrefix + ".name").(string),
			FunctionType:  d.Get(networkPrefix + ".function_type").(string),
			NetworkURI:    utils.NewNstring(d.Get(networkPrefix + ".network_uri").(string)),
			PortID:        d.Get(networkPrefix + ".port_id").(string),
			RequestedMbps: d.Get(networkPrefix + ".requested_mbps").(string),
			ID:            i + 1,
		})
	}
	serverProfileTemplate.Connections = networks

	if val, ok := d.GetOk("boot_order"); ok {
		rawBootOrder := val.(*schema.Set).List()
		bootOrder := make([]string, len(rawBootOrder))
		for i, raw := range rawBootOrder {
			bootOrder[i] = raw.(string)
		}
		serverProfileTemplate.Boot.ManageBoot = true
		serverProfileTemplate.Boot.Order = bootOrder
	}

	sptError := config.ovClient.CreateProfileTemplate(serverProfileTemplate)
	d.SetId(d.Get("name").(string))
	if sptError != nil {
		d.SetId("")
		return sptError
	}
	return resourceServerProfileTemplateRead(d, meta)
}

func resourceServerProfileTemplateRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	spt, err := config.ovClient.GetProfileTemplateByName(d.Id())
	if err != nil || spt.URI.IsNil() {
		d.SetId("")
		return nil
	}

	d.Set("name", spt.Name)
	d.Set("type", spt.Type)

	enclosureGroup, err := config.ovClient.GetEnclosureGroupByUri(spt.EnclosureGroupURI)
	if err != nil {
		return err
	}
	d.Set("enclosure_group_uri", enclosureGroup.Name)

	serverHardwareType, err := config.ovClient.GetServerHardwareTypeByUri(spt.ServerHardwareTypeURI)
	if err != nil {
		return err
	}
	d.Set("server_hardware_type_uri", serverHardwareType.Name)
	d.Set("affinity", spt.Affinity)
	d.Set("uri", spt.URI.String())
	d.Set("etag", spt.ETAG)
	d.Set("serial_number_type", spt.SerialNumberType)
	d.Set("wwn_type", spt.WWNType)
	d.Set("mac_type", spt.MACType)
	d.Set("hide_unused_flex_nics", spt.HideUnusedFlexNics)

	networks := make([]map[string]interface{}, 0, len(spt.Connections))
	for _, network := range spt.Connections {

		networks = append(networks, map[string]interface{}{
			"name":           network.Name,
			"function_type":  network.FunctionType,
			"network_uri":    network.NetworkURI,
			"port_id":        network.PortID,
			"requested_mbps": network.RequestedMbps,
			"id":             network.ID,
		})
	}

	networkCount := d.Get("network.#").(int)
	if networkCount > 0 {
		for i := 0; i < networkCount; i++ {
			currNetworkId := d.Get("network." + strconv.Itoa(i) + ".id")
			for j := 0; j < len(spt.Connections); j++ {
				if spt.Connections[j].ID == currNetworkId && i <= len(spt.Connections)-1 {
					networks[i], networks[j] = networks[j], networks[i]
				}
			}
		}
		d.Set("network", networks)
	}

	if spt.Boot.ManageBoot {
		bootOrder := make([]interface{}, 0)
		for _, currBoot := range spt.Boot.Order {
			rawBootOrder := d.Get("boot_order").(*schema.Set).List()
			for _, raw := range rawBootOrder {
				if raw == currBoot {
					bootOrder = append(bootOrder, currBoot)
				}
			}
		}
		d.Set("boot_order", bootOrder)
	}
	return nil
}

func resourceServerProfileTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	serverProfileTemplate := ov.ServerProfile{
		Name:               d.Get("name").(string),
		Type:               d.Get("type").(string),
		Affinity:           d.Get("affinity").(string),
		URI:                utils.NewNstring(d.Get("uri").(string)),
		ETAG:               d.Get("etag").(string),
		SerialNumberType:   d.Get("serial_number_type").(string),
		WWNType:            d.Get("wwn_type").(string),
		MACType:            d.Get("mac_type").(string),
		HideUnusedFlexNics: d.Get("hide_unused_flex_nics").(bool),
	}

	enclosureGroup, err := config.ovClient.GetEnclosureGroupByName(d.Get("enclosure_group").(string))
	if err != nil {
		return err
	}
	serverProfileTemplate.EnclosureGroupURI = enclosureGroup.URI

	serverHardwareType, err := config.ovClient.GetServerHardwareTypeByName(d.Get("server_hardware_type").(string))
	if err != nil {
		return err
	}
	serverProfileTemplate.ServerHardwareTypeURI = serverHardwareType.URI

	networkCount := d.Get("network.#").(int)
	networks := make([]ov.Connection, 0)
	for i := 0; i < networkCount; i++ {
		networkPrefix := fmt.Sprintf("network.%d", i)
		networks = append(networks, ov.Connection{
			Name:          d.Get(networkPrefix + ".name").(string),
			FunctionType:  d.Get(networkPrefix + ".function_type").(string),
			NetworkURI:    utils.NewNstring(d.Get(networkPrefix + ".network_uri").(string)),
			PortID:        d.Get(networkPrefix + ".port_id").(string),
			RequestedMbps: d.Get(networkPrefix + ".requested_mbps").(string),
			ID:            d.Get(networkPrefix + ".id").(int),
		})
	}
	serverProfileTemplate.Connections = networks

	if val, ok := d.GetOk("boot_order"); ok {
		rawBootOrder := val.(*schema.Set).List()
		bootOrder := make([]string, len(rawBootOrder))
		for i, raw := range rawBootOrder {
			bootOrder[i] = raw.(string)
		}
		serverProfileTemplate.Boot.ManageBoot = true
		serverProfileTemplate.Boot.Order = bootOrder
	}

	err = config.ovClient.UpdateProfileTemplate(serverProfileTemplate)
	if err != nil {
		return err
	}
	d.SetId(d.Get("name").(string))

	return resourceServerProfileTemplateRead(d, meta)
	return nil
}

func resourceServerProfileTemplateDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	error := config.ovClient.DeleteProfileTemplate(d.Get("name").(string))
	if error != nil {
		return error
	}
	return nil
}
<commit_msg>Update resource_server_profile_template.go<commit_after>// (C) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// 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 oneview

import (
	"fmt"
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/HewlettPackard/oneview-golang/utils"
	"github.com/hashicorp/terraform/helper/schema"
	"strconv"
)

func resourceServerProfileTemplate() *schema.Resource {
	return &schema.Resource{
		Create: resourceServerProfileTemplateCreate,
		Read:   resourceServerProfileTemplateRead,
		Update: resourceServerProfileTemplateUpdate,
		Delete: resourceServerProfileTemplateDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"boot_order": {
				Type:     schema.TypeSet,
				Optional: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Set:      schema.HashString,
			},
			"network": {
				Optional: true,
				Type:     schema.TypeList,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"name": {
							Type:     schema.TypeString,
							Required: true,
						},
						"function_type": {
							Type:     schema.TypeString,
							Required: true,
							ForceNew: true,
						},
						"network_uri": {
							Type:     schema.TypeString,
							Required: true,
						},
						"port_id": {
							Type:     schema.TypeString,
							Optional: true,
							Default:  "Lom 1:1-a",
						},
						"requested_mbps": {
							Type:     schema.TypeString,
							Optional: true,
							Default:  "2500",
						},
						"id": {
							Type:     schema.TypeInt,
							Computed: true,
						},
					},
				},
			},
			"type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "ServerProfileTemplateV1",
			},
			"server_hardware_type": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"enclosure_group": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"affinity": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Bay",
			},
			"hide_unused_flex_nics": {
				Type:     schema.TypeBool,
				Optional: true,
				Default:  true,
			},
			"uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"etag": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"serial_number_type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Virtual",
				ForceNew: true,
			},
			"wwn_type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Virtual",
				ForceNew: true,
			},
			"mac_type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Virtual",
				ForceNew: true,
			},
		},
	}
}

func resourceServerProfileTemplateCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	serverProfileTemplate := ov.ServerProfile{
		Name:               d.Get("name").(string),
		Type:               d.Get("type").(string),
		Affinity:           d.Get("affinity").(string),
		SerialNumberType:   d.Get("serial_number_type").(string),
		WWNType:            d.Get("wwn_type").(string),
		MACType:            d.Get("mac_type").(string),
		HideUnusedFlexNics: d.Get("hide_unused_flex_nics").(bool),
	}

	enclosureGroup, err := config.ovClient.GetEnclosureGroupByName(d.Get("enclosure_group").(string))
	if err != nil {
		return err
	}
	serverProfileTemplate.EnclosureGroupURI = enclosureGroup.URI

	serverHardwareType, err := config.ovClient.GetServerHardwareTypeByName(d.Get("server_hardware_type").(string))
	if err != nil {
		return err
	}
	serverProfileTemplate.ServerHardwareTypeURI = serverHardwareType.URI

	networkCount := d.Get("network.#").(int)
	networks := make([]ov.Connection, 0)
	for i := 0; i < networkCount; i++ {
		networkPrefix := fmt.Sprintf("network.%d", i)
		networks = append(networks, ov.Connection{
			Name:          d.Get(networkPrefix + ".name").(string),
			FunctionType:  d.Get(networkPrefix + ".function_type").(string),
			NetworkURI:    utils.NewNstring(d.Get(networkPrefix + ".network_uri").(string)),
			PortID:        d.Get(networkPrefix + ".port_id").(string),
			RequestedMbps: d.Get(networkPrefix + ".requested_mbps").(string),
			ID:            i + 1,
		})
	}
	serverProfileTemplate.Connections = networks

	if val, ok := d.GetOk("boot_order"); ok {
		rawBootOrder := val.(*schema.Set).List()
		bootOrder := make([]string, len(rawBootOrder))
		for i, raw := range rawBootOrder {
			bootOrder[i] = raw.(string)
		}
		serverProfileTemplate.Boot.ManageBoot = true
		serverProfileTemplate.Boot.Order = bootOrder
	}

	sptError := config.ovClient.CreateProfileTemplate(serverProfileTemplate)
	d.SetId(d.Get("name").(string))
	if sptError != nil {
		d.SetId("")
		return sptError
	}
	return resourceServerProfileTemplateRead(d, meta)
}

func resourceServerProfileTemplateRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	spt, err := config.ovClient.GetProfileTemplateByName(d.Id())
	if err != nil || spt.URI.IsNil() {
		d.SetId("")
		return nil
	}

	d.Set("name", spt.Name)
	d.Set("type", spt.Type)

	enclosureGroup, err := config.ovClient.GetEnclosureGroupByUri(spt.EnclosureGroupURI)
	if err != nil {
		return err
	}
	d.Set("enclosure_group_uri", enclosureGroup.Name)

	serverHardwareType, err := config.ovClient.GetServerHardwareTypeByUri(spt.ServerHardwareTypeURI)
	if err != nil {
		return err
	}
	d.Set("server_hardware_type_uri", serverHardwareType.Name)
	d.Set("affinity", spt.Affinity)
	d.Set("uri", spt.URI.String())
	d.Set("etag", spt.ETAG)
	d.Set("serial_number_type", spt.SerialNumberType)
	d.Set("wwn_type", spt.WWNType)
	d.Set("mac_type", spt.MACType)
	d.Set("hide_unused_flex_nics", spt.HideUnusedFlexNics)

	networks := make([]map[string]interface{}, 0, len(spt.Connections))
	for _, network := range spt.Connections {

		networks = append(networks, map[string]interface{}{
			"name":           network.Name,
			"function_type":  network.FunctionType,
			"network_uri":    network.NetworkURI,
			"port_id":        network.PortID,
			"requested_mbps": network.RequestedMbps,
			"id":             network.ID,
		})
	}

	networkCount := d.Get("network.#").(int)
	if networkCount > 0 {
		for i := 0; i < networkCount; i++ {
			currNetworkId := d.Get("network." + strconv.Itoa(i) + ".id")
			for j := 0; j < len(spt.Connections); j++ {
				if spt.Connections[j].ID == currNetworkId && i <= len(spt.Connections)-1 {
					networks[i], networks[j] = networks[j], networks[i]
				}
			}
		}
		d.Set("network", networks)
	}

	if spt.Boot.ManageBoot {
		bootOrder := make([]interface{}, 0)
		for _, currBoot := range spt.Boot.Order {
			rawBootOrder := d.Get("boot_order").(*schema.Set).List()
			for _, raw := range rawBootOrder {
				if raw == currBoot {
					bootOrder = append(bootOrder, currBoot)
				}
			}
		}
		d.Set("boot_order", bootOrder)
	}
	return nil
}

func resourceServerProfileTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	serverProfileTemplate := ov.ServerProfile{
		Name:               d.Get("name").(string),
		Type:               d.Get("type").(string),
		Affinity:           d.Get("affinity").(string),
		URI:                utils.NewNstring(d.Get("uri").(string)),
		ETAG:               d.Get("etag").(string),
		SerialNumberType:   d.Get("serial_number_type").(string),
		WWNType:            d.Get("wwn_type").(string),
		MACType:            d.Get("mac_type").(string),
		HideUnusedFlexNics: d.Get("hide_unused_flex_nics").(bool),
	}

	enclosureGroup, err := config.ovClient.GetEnclosureGroupByName(d.Get("enclosure_group").(string))
	if err != nil {
		return err
	}
	serverProfileTemplate.EnclosureGroupURI = enclosureGroup.URI

	serverHardwareType, err := config.ovClient.GetServerHardwareTypeByName(d.Get("server_hardware_type").(string))
	if err != nil {
		return err
	}
	serverProfileTemplate.ServerHardwareTypeURI = serverHardwareType.URI

	networkCount := d.Get("network.#").(int)
	networks := make([]ov.Connection, 0)
	for i := 0; i < networkCount; i++ {
		networkPrefix := fmt.Sprintf("network.%d", i)
		networks = append(networks, ov.Connection{
			Name:          d.Get(networkPrefix + ".name").(string),
			FunctionType:  d.Get(networkPrefix + ".function_type").(string),
			NetworkURI:    utils.NewNstring(d.Get(networkPrefix + ".network_uri").(string)),
			PortID:        d.Get(networkPrefix + ".port_id").(string),
			RequestedMbps: d.Get(networkPrefix + ".requested_mbps").(string),
			ID:            d.Get(networkPrefix + ".id").(int),
		})
	}
	serverProfileTemplate.Connections = networks

	if val, ok := d.GetOk("boot_order"); ok {
		rawBootOrder := val.(*schema.Set).List()
		bootOrder := make([]string, len(rawBootOrder))
		for i, raw := range rawBootOrder {
			bootOrder[i] = raw.(string)
		}
		serverProfileTemplate.Boot.ManageBoot = true
		serverProfileTemplate.Boot.Order = bootOrder
	}

	err = config.ovClient.UpdateProfileTemplate(serverProfileTemplate)
	if err != nil {
		return err
	}
	d.SetId(d.Get("name").(string))

	return resourceServerProfileTemplateRead(d, meta)
	return nil
}

func resourceServerProfileTemplateDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	error := config.ovClient.DeleteProfileTemplate(d.Get("name").(string))
	if error != nil {
		return error
	}
	return nil
}
<|endoftext|>