<commit_before>package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
)

type Commit struct {
	num    int    // mercurial revision number
	node   string // mercurial hash
	parent string // hash of commit's parent
	user   string // author's Name <email>
	date   string // date of commit
	desc   string // description
}

// getCommit returns details about the Commit specified by the revision hash
func getCommit(rev string) (c Commit, err os.Error) {
	defer func() {
		if err != nil {
			err = fmt.Errorf("getCommit: %s: %s", rev, err)
		}
	}()
	parts, err := getCommitParts(rev)
	if err != nil {
		return
	}
	num, err := strconv.Atoi(parts[0])
	if err != nil {
		return
	}
	parent := ""
	if num > 0 {
		prev := strconv.Itoa(num - 1)
		if pparts, err := getCommitParts(prev); err == nil {
			parent = pparts[1]
		}
	}
	user := strings.Replace(parts[2], "<", "<", -1)
	user = strings.Replace(user, ">", ">", -1)
	return Commit{num, parts[1], parent, user, parts[3], parts[4]}, nil
}

func getCommitParts(rev string) (parts []string, err os.Error) {
	const format = "{rev}>{node}>{author|escape}>{date}>{desc}"
	s, _, err := runLog(nil, "", goroot,
		"hg", "log", "-r", rev, "-l", "1", "--template", format)
	if err != nil {
		return
	}
	return strings.Split(s, ">", 5), nil
}
<commit_msg>misc/dashboard/builder: talk to hg with utf-8 encoding always.<commit_after>package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
)

type Commit struct {
	num    int    // mercurial revision number
	node   string // mercurial hash
	parent string // hash of commit's parent
	user   string // author's Name <email>
	date   string // date of commit
	desc   string // description
}

// getCommit returns details about the Commit specified by the revision hash
func getCommit(rev string) (c Commit, err os.Error) {
	defer func() {
		if err != nil {
			err = fmt.Errorf("getCommit: %s: %s", rev, err)
		}
	}()
	parts, err := getCommitParts(rev)
	if err != nil {
		return
	}
	num, err := strconv.Atoi(parts[0])
	if err != nil {
		return
	}
	parent := ""
	if num > 0 {
		prev := strconv.Itoa(num - 1)
		if pparts, err := getCommitParts(prev); err == nil {
			parent = pparts[1]
		}
	}
	user := strings.Replace(parts[2], "<", "<", -1)
	user = strings.Replace(user, ">", ">", -1)
	return Commit{num, parts[1], parent, user, parts[3], parts[4]}, nil
}

func getCommitParts(rev string) (parts []string, err os.Error) {
	const format = "{rev}>{node}>{author|escape}>{date}>{desc}"
	s, _, err := runLog(nil, "", goroot,
		"hg", "log",
		"--encoding", "utf-8",
		"--rev", rev,
		"--limit", "1",
		"--template", format,
	)
	if err != nil {
		return
	}
	return strings.Split(s, ">", 5), nil
}
<|endoftext|>


<commit_before>package password

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"errors"
	"net/http"
	"time"

	"github.com/boltdb/bolt"
	jwt "github.com/dgrijalva/jwt-go"
	"golang.org/x/crypto/bcrypt"
	"golang.org/x/net/context"
)

var (
	// ErrInvalidSigningMethod is the error returned when a token's signature
	// does match the signature used to sign the token header.
	ErrInvalidSigningMethod = errors.New("Invalid signing method")
	// ErrTokenInvalid means the signature didn't match.
	ErrTokenInvalid = errors.New("Token isn't valid")

	signingKey = genRandBytes()

	//
	cost = bcrypt.DefaultCost
)

var store = newDB()

// Authenticator is the interface that implements the methods for storing and
// retrieving passwords.
type Authenticator interface {
	Store(id string, secret string) string
	Retrieve(id string, secret string) string
}

// DefaultSore contains a reference to the default store for Password, and
// satiesfies the Authenticator interface.
type DefaultStore struct {
	DB *bolt.DB
}

func (s *DefaultStore) Store(id string, secret string) string {
	return "" // setup
}

func (s *DefaultStore) Retrieve(id string, secret string) string {
	return "" // I should implement these
}

func newDB() *bolt.DB {
	db, err := bolt.Open("password.db", 0600, &bolt.Options{
		Timeout: 1 * time.Second,
	})
	if err != nil {
		panic(err)
	}
	return db
}

// Hash hashes and salts a plaintext secret using bcrypt.
func Hash(id string, secret string) (string, error) {
	hashedSecret, err := bcrypt.GenerateFromPassword([]byte(secret), cost)
	if err != nil {
		return "", err // couldn't run bcrypt
	}
	return string(hashedSecret), nil
}

// Compare compares a hashed secret with a plaintext secret to see if they
// match. If they do, a JSON web token is generated with the given id.
func Compare(id string, secret string, hashedSecret string) (string, error) {
	err := bcrypt.CompareHashAndPassword([]byte(hashedSecret), []byte(secret))
	if err != nil {
		return "", err // passwords didn't match
	}
	return genToken(id)
}

// Authenticate runs `Compare`, and writes the generated JSON web token to the
// response writer.
func Authenticate(w http.ResponseWriter, id string, secret string, hashedSecret string) {
	tokStr, err := Compare(id, secret, hashedSecret)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(map[string]string{"token": tokStr})
}

// Protect is middleware that checks to see if the incoming request has a
// valid JSON web token. If it does, it executes the next `http.HandlerFunc`,
// and passes it a `context.Context` with the field "id" assigned to the
// current user id.
type Protect func(ctx context.Context, w http.ResponseWriter, r *http.Request)

func (fn Protect) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	tok, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		_, ok := token.Method.(*jwt.SigningMethodHMAC)
		if ok == false {
			return nil, ErrInvalidSigningMethod
		}
		return signingKey, nil
	})
	if err != nil {
		// might wanna use switch statement
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if tok.Valid != true {
		http.Error(w, ErrTokenInvalid.Error(), http.StatusUnauthorized)
	}

	id := tok.Claims["sub"]
	ctx := context.WithValue(context.Background(), "id", id)

	fn(ctx, w, r)
}

// SetSigningKey allows you to override the default HMAC signing key with one
// of your own. Every time this package is imported, a signing key is set
// randomly. That means that in between restarts, a new key is set, so you'd
// no longer be able to verify JSON web tokens created with that key. In order
// to reuse the signing key, you must set it yourself. Just call this function
// before creating any tokens, and you'll be good to go.
func SetSigningKey(key []byte) {
	signingKey = key
}

func genToken(id string) (string, error) {
	jwt := jwt.New(jwt.SigningMethodHS256)
	expTime := time.Now().Add(time.Hour * 72).Unix()

	jwt.Claims["sub"] = id
	jwt.Claims["exp"] = expTime
	jwt.Claims["iat"] = time.Now().Unix()

	tokStr, err := jwt.SignedString(signingKey)
	if err != nil {
		return "", err // failed to sign token
	}

	return tokStr, nil
}

func genRandBytes() []byte {
	// Use 32 bytes (256 bits) to satisfy the requirement for the HMAC key
	// length.
	b := make([]byte, 32)
	_, err := rand.Read(b)
	if err != nil {
		// If this errors, it means that something is wrong the system's
		// CSPRNG, which indicates a critical operating system failure. Panic
		// and crash here
		panic(err)
	}
	return []byte(base64.URLEncoding.EncodeToString(b))
}
<commit_msg>Add BoltDB read/write functions in default interface<commit_after>package password

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"errors"
	"net/http"
	"time"

	"github.com/boltdb/bolt"
	jwt "github.com/dgrijalva/jwt-go"
	"golang.org/x/crypto/bcrypt"
	"golang.org/x/net/context"
)

var (
	// ErrInvalidSigningMethod is the error returned when a token's signature
	// does match the signature used to sign the token header.
	ErrInvalidSigningMethod = errors.New("Invalid signing method")
	// ErrTokenInvalid means the signature didn't match.
	ErrTokenInvalid = errors.New("Token isn't valid")

	signingKey = genRandBytes()

	//
	cost = bcrypt.DefaultCost
)

var store = newDB()

// Authenticator is the interface that implements the methods for storing and
// retrieving passwords.
type Authenticator interface {
	Store(id string, secret string) string
	Retrieve(id string, secret string) string
}

// DefaultSore contains a reference to the default store for Password, and
// satiesfies the Authenticator interface.
type DefaultStore struct {
	DB *bolt.DB
}

func (s *DefaultStore) Store(id string, secret string) string {
	err := s.DB.Update(func(tx *bolt.Tx) error {
		//
		return nil
	})
	if err != nil {
		// handle error
	}
	return ""
}

func (s *DefaultStore) Retrieve(id string, secret string) string {
	err := s.DB.View(func(tx *bolt.Tx) error {
		//
		return nil
	})
	if err != nil {
		// handle error
	}
	return "" // I should implement these
}

func newDB() *bolt.DB {
	db, err := bolt.Open("password.db", 0600, &bolt.Options{
		Timeout: 1 * time.Second,
	})
	if err != nil {
		panic(err)
	}
	return db
}

// Hash hashes and salts a plaintext secret using bcrypt.
func Hash(id string, secret string) (string, error) {
	hashedSecret, err := bcrypt.GenerateFromPassword([]byte(secret), cost)
	if err != nil {
		return "", err // couldn't run bcrypt
	}
	return string(hashedSecret), nil
}

// Compare compares a hashed secret with a plaintext secret to see if they
// match. If they do, a JSON web token is generated with the given id.
func Compare(id string, secret string, hashedSecret string) (string, error) {
	err := bcrypt.CompareHashAndPassword([]byte(hashedSecret), []byte(secret))
	if err != nil {
		return "", err // passwords didn't match
	}
	return genToken(id)
}

// Authenticate runs `Compare`, and writes the generated JSON web token to the
// response writer.
func Authenticate(w http.ResponseWriter, id string, secret string, hashedSecret string) {
	tokStr, err := Compare(id, secret, hashedSecret)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(map[string]string{"token": tokStr})
}

// Protect is middleware that checks to see if the incoming request has a
// valid JSON web token. If it does, it executes the next `http.HandlerFunc`,
// and passes it a `context.Context` with the field "id" assigned to the
// current user id.
type Protect func(ctx context.Context, w http.ResponseWriter, r *http.Request)

func (fn Protect) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	tok, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		_, ok := token.Method.(*jwt.SigningMethodHMAC)
		if ok == false {
			return nil, ErrInvalidSigningMethod
		}
		return signingKey, nil
	})
	if err != nil {
		// might wanna use switch statement
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if tok.Valid != true {
		http.Error(w, ErrTokenInvalid.Error(), http.StatusUnauthorized)
	}

	id := tok.Claims["sub"]
	ctx := context.WithValue(context.Background(), "id", id)

	fn(ctx, w, r)
}

// SetSigningKey allows you to override the default HMAC signing key with one
// of your own. Every time this package is imported, a signing key is set
// randomly. That means that in between restarts, a new key is set, so you'd
// no longer be able to verify JSON web tokens created with that key. In order
// to reuse the signing key, you must set it yourself. Just call this function
// before creating any tokens, and you'll be good to go.
func SetSigningKey(key []byte) {
	signingKey = key
}

func genToken(id string) (string, error) {
	jwt := jwt.New(jwt.SigningMethodHS256)
	expTime := time.Now().Add(time.Hour * 72).Unix()

	jwt.Claims["sub"] = id
	jwt.Claims["exp"] = expTime
	jwt.Claims["iat"] = time.Now().Unix()

	tokStr, err := jwt.SignedString(signingKey)
	if err != nil {
		return "", err // failed to sign token
	}

	return tokStr, nil
}

func genRandBytes() []byte {
	// Use 32 bytes (256 bits) to satisfy the requirement for the HMAC key
	// length.
	b := make([]byte, 32)
	_, err := rand.Read(b)
	if err != nil {
		// If this errors, it means that something is wrong the system's
		// CSPRNG, which indicates a critical operating system failure. Panic
		// and crash here
		panic(err)
	}
	return []byte(base64.URLEncoding.EncodeToString(b))
}
<|endoftext|>


<commit_before>// (C) Copyright 2021 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 (
	"errors"
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func resourceServerHardware() *schema.Resource {
	return &schema.Resource{
		Create: resourceServerHardwareCreate,
		Read:   resourceServerHardwareRead,
		Update: resourceServerHardwareUpdate,
		Delete: resourceServerHardwareDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"configuration_state": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"force": {
				Type:     schema.TypeBool,
				Computed: true,
				Optional: true,
			},
			"licensing_intent": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"hostname": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"location_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"maintenance_mode": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},
			"name": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"one_time_boot": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},
			"password": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"power_state": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"type": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"server_group_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"server_hardware_type_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"server_power_state": {
				Optional: true,
				Computed: true,
				Type:     schema.TypeList,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"power_state": {
							Type:     schema.TypeString,
							Optional: true,
						},
						"power_control": {
							Type:     schema.TypeString,
							Optional: true,
						},
					},
				},
			},
			"server_profile_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"uuid": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"virtual_serial_number": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"virtual_uuid": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"mp_hosts_and_ranges": {
				Optional: true,
				Computed: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
			},
			"mp_ip_address": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"mp_firmware_version": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"mp_dns_name": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"uid_state": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},
			"username": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
		},
	}
}

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

	hardware := ov.ServerHardware{
		Hostname:           d.Get("hostname").(string),
		Username:           d.Get("username").(string),
		Password:           d.Get("password").(string),
		Force:              d.Get("force").(bool),
		LicensingIntent:    d.Get("licensing_intent").(string),
		ConfigurationState: d.Get("configuration_state").(string),
	}
	err := config.ovClient.AddRackServer(hardware)
	if err != nil {
		d.SetId("")
		return err
	}

	sh, _ := config.ovClient.GetServerHardwareByName(d.Get("hostname").(string))

	d.SetId(sh.UUID.String())
	return resourceServerHardwareRead(d, meta)
}

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

	servHard, err := config.ovClient.GetServerHardwareByName(d.Get("hostname").(string))
	if err != nil || servHard.URI.IsNil() {
		d.SetId("")
		return nil
	}
	d.SetId(d.Id())
	d.Set("configuration_state", d.Get("configuration_state").(string))
	d.Set("host_name", d.Get("configuration_state").(string))
	d.Set("force", servHard.Force)
	d.Set("licensing_intent", servHard.LicensingIntent)
	d.Set("maintenance_mode", servHard.MaintenanceMode)
	d.Set("name", servHard.Name)
	d.Set("one_time_boot", servHard.OneTimeBoot)
	d.Set("location_uri", servHard.LocationURI.String())
	d.Set("password", d.Get("password").(string))
	d.Set("power_state", servHard.PowerState)
	d.Set("type", servHard.Type)
	d.Set("uri", servHard.URI.String())
	d.Set("server_group_uri", servHard.ServerGroupURI.String())
	d.Set("server_hardware_type_uri", servHard.ServerHardwareTypeURI.String())
	d.Set("server_profile_uri", servHard.ServerProfileURI.String())
	d.Set("uuid", servHard.UUID.String())
	d.Set("virtual_serial_number", servHard.VirtualSerialNumber.String())
	d.Set("virtual_uuid", servHard.VirtualUUID)
	d.Set("mp_ip_address", servHard.MpIpAddress)
	d.Set("mp_firmware_version", servHard.MpFirwareVersion)
	d.Set("mp_dns_name", servHard.MpDnsName)
	d.Set("uid_state", servHard.UidState)
	d.Set("username", d.Get("username").(string))

	return nil
}

func resourceServerHardwareUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	if d.HasChange("one_time_boot") {
		err := config.ovClient.SetOneTimeBoot(d.Id(), d.Get("one_time_boot").(string))

		if err != nil {
			d.SetId("")
			return err
		}

	}
	if d.HasChange("maintenance_mode") {
		err := config.ovClient.SetMaintenanceMode(d.Id(), d.Get("maintenance_mode").(string))
		if err != nil {
			d.SetId("")
			return err
		}

	}
	if d.HasChange("uid_state") {
		err := config.ovClient.SetUidState(d.Id(), d.Get("uid_state").(string))
		if err != nil {
			d.SetId("")
			return err
		}
	}
	if d.HasChange("server_power_state") {
		powerMap := make(map[string]interface{})
		powerStates := d.Get("server_power_state").([]interface{})
		for _, powerState := range powerStates {
			powerMap = powerState.(map[string]interface{})
		}

		powerInput := map[string]interface{}{
			"powerState":   powerMap["power_state"],
			"powerControl": powerMap["power_control"],
		}

		err := config.ovClient.SetPowerState(d.Id(), powerInput)
		if err != nil {
			d.SetId("")
			return err
		}
	}
	if d.HasChange("username") || d.HasChange("password") || d.HasChange("configuration_state") {
		return errors.New("Fields like username, password and configuration_state cannot be changed")
	}
	d.SetId(d.Id())

	return resourceServerHardwareRead(d, meta)
}

func resourceServerHardwareDelete(d *schema.ResourceData, meta interface{}) error {
	return errors.New("Server hardware delete Operation is not supported.")
}
<commit_msg>Typo fix<commit_after>// (C) Copyright 2021 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 (
	"errors"
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func resourceServerHardware() *schema.Resource {
	return &schema.Resource{
		Create: resourceServerHardwareCreate,
		Read:   resourceServerHardwareRead,
		Update: resourceServerHardwareUpdate,
		Delete: resourceServerHardwareDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"configuration_state": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"force": {
				Type:     schema.TypeBool,
				Computed: true,
				Optional: true,
			},
			"licensing_intent": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"hostname": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"location_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"maintenance_mode": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},
			"name": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"one_time_boot": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},
			"password": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"power_state": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"type": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"server_group_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"server_hardware_type_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"server_power_state": {
				Optional: true,
				Computed: true,
				Type:     schema.TypeList,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"power_state": {
							Type:     schema.TypeString,
							Optional: true,
						},
						"power_control": {
							Type:     schema.TypeString,
							Optional: true,
						},
					},
				},
			},
			"server_profile_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"uuid": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"virtual_serial_number": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"virtual_uuid": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"mp_hosts_and_ranges": {
				Optional: true,
				Computed: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
			},
			"mp_ip_address": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"mp_firmware_version": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"mp_dns_name": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"uid_state": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},
			"username": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
		},
	}
}

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

	hardware := ov.ServerHardware{
		Hostname:           d.Get("hostname").(string),
		Username:           d.Get("username").(string),
		Password:           d.Get("password").(string),
		Force:              d.Get("force").(bool),
		LicensingIntent:    d.Get("licensing_intent").(string),
		ConfigurationState: d.Get("configuration_state").(string),
	}
	err := config.ovClient.AddRackServer(hardware)
	if err != nil {
		d.SetId("")
		return err
	}

	sh, _ := config.ovClient.GetServerHardwareByName(d.Get("hostname").(string))

	d.SetId(sh.UUID.String())
	return resourceServerHardwareRead(d, meta)
}

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

	servHard, err := config.ovClient.GetServerHardwareByName(d.Get("hostname").(string))
	if err != nil || servHard.URI.IsNil() {
		d.SetId("")
		return nil
	}
	d.SetId(d.Id())
	d.Set("configuration_state", d.Get("configuration_state").(string))
	d.Set("hostname", d.Get("hostname").(string))
	d.Set("force", servHard.Force)
	d.Set("licensing_intent", servHard.LicensingIntent)
	d.Set("maintenance_mode", servHard.MaintenanceMode)
	d.Set("name", servHard.Name)
	d.Set("one_time_boot", servHard.OneTimeBoot)
	d.Set("location_uri", servHard.LocationURI.String())
	d.Set("password", d.Get("password").(string))
	d.Set("power_state", servHard.PowerState)
	d.Set("type", servHard.Type)
	d.Set("uri", servHard.URI.String())
	d.Set("server_group_uri", servHard.ServerGroupURI.String())
	d.Set("server_hardware_type_uri", servHard.ServerHardwareTypeURI.String())
	d.Set("server_profile_uri", servHard.ServerProfileURI.String())
	d.Set("uuid", servHard.UUID.String())
	d.Set("virtual_serial_number", servHard.VirtualSerialNumber.String())
	d.Set("virtual_uuid", servHard.VirtualUUID)
	d.Set("mp_ip_address", servHard.MpIpAddress)
	d.Set("mp_firmware_version", servHard.MpFirwareVersion)
	d.Set("mp_dns_name", servHard.MpDnsName)
	d.Set("uid_state", servHard.UidState)
	d.Set("username", d.Get("username").(string))

	return nil
}

func resourceServerHardwareUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	if d.HasChange("one_time_boot") {
		err := config.ovClient.SetOneTimeBoot(d.Id(), d.Get("one_time_boot").(string))

		if err != nil {
			d.SetId("")
			return err
		}

	}
	if d.HasChange("maintenance_mode") {
		err := config.ovClient.SetMaintenanceMode(d.Id(), d.Get("maintenance_mode").(string))
		if err != nil {
			d.SetId("")
			return err
		}

	}
	if d.HasChange("uid_state") {
		err := config.ovClient.SetUidState(d.Id(), d.Get("uid_state").(string))
		if err != nil {
			d.SetId("")
			return err
		}
	}
	if d.HasChange("server_power_state") {
		powerMap := make(map[string]interface{})
		powerStates := d.Get("server_power_state").([]interface{})
		for _, powerState := range powerStates {
			powerMap = powerState.(map[string]interface{})
		}

		powerInput := map[string]interface{}{
			"powerState":   powerMap["power_state"],
			"powerControl": powerMap["power_control"],
		}

		err := config.ovClient.SetPowerState(d.Id(), powerInput)
		if err != nil {
			d.SetId("")
			return err
		}
	}
	if d.HasChange("username") || d.HasChange("password") || d.HasChange("configuration_state") {
		return errors.New("Fields like username, password and configuration_state cannot be changed")
	}
	d.SetId(d.Id())

	return resourceServerHardwareRead(d, meta)
}

func resourceServerHardwareDelete(d *schema.ResourceData, meta interface{}) error {
	return errors.New("Server hardware delete Operation is not supported.")
}
<|endoftext|>


<commit_before>// cgo -godefs types_solaris.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.

// +build amd64,solaris

package unix

const (
	sizeofPtr      = 0x8
	sizeofShort    = 0x2
	sizeofInt      = 0x4
	sizeofLong     = 0x8
	sizeofLongLong = 0x8
	PathMax        = 0x400
	MaxHostNameLen = 0x100
)

type (
	_C_short     int16
	_C_int       int32
	_C_long      int64
	_C_long_long int64
)

type Timespec struct {
	Sec  int64
	Nsec int64
}

type Timeval struct {
	Sec  int64
	Usec int64
}

type Timeval32 struct {
	Sec  int32
	Usec int32
}

type Tms struct {
	Utime  int64
	Stime  int64
	Cutime int64
	Cstime int64
}

type Utimbuf struct {
	Actime  int64
	Modtime int64
}

type Rusage struct {
	Utime    Timeval
	Stime    Timeval
	Maxrss   int64
	Ixrss    int64
	Idrss    int64
	Isrss    int64
	Minflt   int64
	Majflt   int64
	Nswap    int64
	Inblock  int64
	Oublock  int64
	Msgsnd   int64
	Msgrcv   int64
	Nsignals int64
	Nvcsw    int64
	Nivcsw   int64
}

type Rlimit struct {
	Cur uint64
	Max uint64
}

type _Gid_t uint32

const (
	S_IFMT   = 0xf000
	S_IFIFO  = 0x1000
	S_IFCHR  = 0x2000
	S_IFDIR  = 0x4000
	S_IFBLK  = 0x6000
	S_IFREG  = 0x8000
	S_IFLNK  = 0xa000
	S_IFSOCK = 0xc000
	S_ISUID  = 0x800
	S_ISGID  = 0x400
	S_ISVTX  = 0x200
	S_IRUSR  = 0x100
	S_IWUSR  = 0x80
	S_IXUSR  = 0x40
)

type Stat_t struct {
	Dev       uint64
	Ino       uint64
	Mode      uint32
	Nlink     uint32
	Uid       uint32
	Gid       uint32
	Rdev      uint64
	Size      int64
	Atim      Timespec
	Mtim      Timespec
	Ctim      Timespec
	Blksize   int32
	Pad_cgo_0 [4]byte
	Blocks    int64
	Fstype    [16]int8
}

type Flock_t struct {
	Type      int16
	Whence    int16
	Pad_cgo_0 [4]byte
	Start     int64
	Len       int64
	Sysid     int32
	Pid       int32
	Pad       [4]int64
}

type Dirent struct {
	Ino       uint64
	Off       int64
	Reclen    uint16
	Name      [1]int8
	Pad_cgo_0 [5]byte
}

type _Fsblkcnt_t uint64

type Statvfs_t struct {
	Bsize    uint64
	Frsize   uint64
	Blocks   uint64
	Bfree    uint64
	Bavail   uint64
	Files    uint64
	Ffree    uint64
	Favail   uint64
	Fsid     uint64
	Basetype [16]int8
	Flag     uint64
	Namemax  uint64
	Fstr     [32]int8
}

type RawSockaddrInet4 struct {
	Family uint16
	Port   uint16
	Addr   [4]byte /* in_addr */
	Zero   [8]int8
}

type RawSockaddrInet6 struct {
	Family         uint16
	Port           uint16
	Flowinfo       uint32
	Addr           [16]byte /* in6_addr */
	Scope_id       uint32
	X__sin6_src_id uint32
}

type RawSockaddrUnix struct {
	Family uint16
	Path   [108]int8
}

type RawSockaddrDatalink struct {
	Family uint16
	Index  uint16
	Type   uint8
	Nlen   uint8
	Alen   uint8
	Slen   uint8
	Data   [244]int8
}

type RawSockaddr struct {
	Family uint16
	Data   [14]int8
}

type RawSockaddrAny struct {
	Addr RawSockaddr
	Pad  [236]int8
}

type _Socklen uint32

type Linger struct {
	Onoff  int32
	Linger int32
}

type Iovec struct {
	Base *int8
	Len  uint64
}

type IPMreq struct {
	Multiaddr [4]byte /* in_addr */
	Interface [4]byte /* in_addr */
}

type IPv6Mreq struct {
	Multiaddr [16]byte /* in6_addr */
	Interface uint32
}

type Msghdr struct {
	Name         *byte
	Namelen      uint32
	Pad_cgo_0    [4]byte
	Iov          *Iovec
	Iovlen       int32
	Pad_cgo_1    [4]byte
	Accrights    *int8
	Accrightslen int32
	Pad_cgo_2    [4]byte
}

type Cmsghdr struct {
	Len   uint32
	Level int32
	Type  int32
}

type Inet6Pktinfo struct {
	Addr    [16]byte /* in6_addr */
	Ifindex uint32
}

type IPv6MTUInfo struct {
	Addr RawSockaddrInet6
	Mtu  uint32
}

type ICMPv6Filter struct {
	X__icmp6_filt [8]uint32
}

const (
	SizeofSockaddrInet4    = 0x10
	SizeofSockaddrInet6    = 0x20
	SizeofSockaddrAny      = 0xfc
	SizeofSockaddrUnix     = 0x6e
	SizeofSockaddrDatalink = 0xfc
	SizeofLinger           = 0x8
	SizeofIPMreq           = 0x8
	SizeofIPv6Mreq         = 0x14
	SizeofMsghdr           = 0x30
	SizeofCmsghdr          = 0xc
	SizeofInet6Pktinfo     = 0x14
	SizeofIPv6MTUInfo      = 0x24
	SizeofICMPv6Filter     = 0x20
)

type FdSet struct {
	Bits [1024]int64
}

type Utsname struct {
	Sysname  [257]byte
	Nodename [257]byte
	Release  [257]byte
	Version  [257]byte
	Machine  [257]byte
}

type Ustat_t struct {
	Tfree     int64
	Tinode    uint64
	Fname     [6]int8
	Fpack     [6]int8
	Pad_cgo_0 [4]byte
}

const (
	AT_FDCWD            = 0xffd19553
	AT_SYMLINK_NOFOLLOW = 0x1000
	AT_SYMLINK_FOLLOW   = 0x2000
	AT_REMOVEDIR        = 0x1
	AT_EACCESS          = 0x4
)

const (
	SizeofIfMsghdr  = 0x54
	SizeofIfData    = 0x44
	SizeofIfaMsghdr = 0x14
	SizeofRtMsghdr  = 0x4c
	SizeofRtMetrics = 0x28
)

type IfMsghdr struct {
	Msglen    uint16
	Version   uint8
	Type      uint8
	Addrs     int32
	Flags     int32
	Index     uint16
	Pad_cgo_0 [2]byte
	Data      IfData
}

type IfData struct {
	Type       uint8
	Addrlen    uint8
	Hdrlen     uint8
	Pad_cgo_0  [1]byte
	Mtu        uint32
	Metric     uint32
	Baudrate   uint32
	Ipackets   uint32
	Ierrors    uint32
	Opackets   uint32
	Oerrors    uint32
	Collisions uint32
	Ibytes     uint32
	Obytes     uint32
	Imcasts    uint32
	Omcasts    uint32
	Iqdrops    uint32
	Noproto    uint32
	Lastchange Timeval32
}

type IfaMsghdr struct {
	Msglen    uint16
	Version   uint8
	Type      uint8
	Addrs     int32
	Flags     int32
	Index     uint16
	Pad_cgo_0 [2]byte
	Metric    int32
}

type RtMsghdr struct {
	Msglen    uint16
	Version   uint8
	Type      uint8
	Index     uint16
	Pad_cgo_0 [2]byte
	Flags     int32
	Addrs     int32
	Pid       int32
	Seq       int32
	Errno     int32
	Use       int32
	Inits     uint32
	Rmx       RtMetrics
}

type RtMetrics struct {
	Locks    uint32
	Mtu      uint32
	Hopcount uint32
	Expire   uint32
	Recvpipe uint32
	Sendpipe uint32
	Ssthresh uint32
	Rtt      uint32
	Rttvar   uint32
	Pksent   uint32
}

const (
	SizeofBpfVersion = 0x4
	SizeofBpfStat    = 0x80
	SizeofBpfProgram = 0x10
	SizeofBpfInsn    = 0x8
	SizeofBpfHdr     = 0x14
)

type BpfVersion struct {
	Major uint16
	Minor uint16
}

type BpfStat struct {
	Recv    uint64
	Drop    uint64
	Capt    uint64
	Padding [13]uint64
}

type BpfProgram struct {
	Len       uint32
	Pad_cgo_0 [4]byte
	Insns     *BpfInsn
}

type BpfInsn struct {
	Code uint16
	Jt   uint8
	Jf   uint8
	K    uint32
}

type BpfTimeval struct {
	Sec  int32
	Usec int32
}

type BpfHdr struct {
	Tstamp    BpfTimeval
	Caplen    uint32
	Datalen   uint32
	Hdrlen    uint16
	Pad_cgo_0 [2]byte
}

type Termios struct {
	Iflag     uint32
	Oflag     uint32
	Cflag     uint32
	Lflag     uint32
	Cc        [19]uint8
	Pad_cgo_0 [1]byte
}

type Termio struct {
	Iflag     uint16
	Oflag     uint16
	Cflag     uint16
	Lflag     uint16
	Line      int8
	Cc        [8]uint8
	Pad_cgo_0 [1]byte
}

type Winsize struct {
	Row    uint16
	Col    uint16
	Xpixel uint16
	Ypixel uint16
}

type PollFd struct {
	Fd      int32
	Events  int16
	Revents int16
}

const (
	POLLERR    = 0x8
	POLLHUP    = 0x10
	POLLIN     = 0x1
	POLLNVAL   = 0x20
	POLLOUT    = 0x4
	POLLPRI    = 0x2
	POLLRDBAND = 0x80
	POLLRDNORM = 0x40
	POLLWRBAND = 0x100
	POLLWRNORM = 0x4
)
<commit_msg>unix: don't export padding fields on Solaris<commit_after>// cgo -godefs types_solaris.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.

// +build amd64,solaris

package unix

const (
	sizeofPtr      = 0x8
	sizeofShort    = 0x2
	sizeofInt      = 0x4
	sizeofLong     = 0x8
	sizeofLongLong = 0x8
	PathMax        = 0x400
	MaxHostNameLen = 0x100
)

type (
	_C_short     int16
	_C_int       int32
	_C_long      int64
	_C_long_long int64
)

type Timespec struct {
	Sec  int64
	Nsec int64
}

type Timeval struct {
	Sec  int64
	Usec int64
}

type Timeval32 struct {
	Sec  int32
	Usec int32
}

type Tms struct {
	Utime  int64
	Stime  int64
	Cutime int64
	Cstime int64
}

type Utimbuf struct {
	Actime  int64
	Modtime int64
}

type Rusage struct {
	Utime    Timeval
	Stime    Timeval
	Maxrss   int64
	Ixrss    int64
	Idrss    int64
	Isrss    int64
	Minflt   int64
	Majflt   int64
	Nswap    int64
	Inblock  int64
	Oublock  int64
	Msgsnd   int64
	Msgrcv   int64
	Nsignals int64
	Nvcsw    int64
	Nivcsw   int64
}

type Rlimit struct {
	Cur uint64
	Max uint64
}

type _Gid_t uint32

const (
	S_IFMT   = 0xf000
	S_IFIFO  = 0x1000
	S_IFCHR  = 0x2000
	S_IFDIR  = 0x4000
	S_IFBLK  = 0x6000
	S_IFREG  = 0x8000
	S_IFLNK  = 0xa000
	S_IFSOCK = 0xc000
	S_ISUID  = 0x800
	S_ISGID  = 0x400
	S_ISVTX  = 0x200
	S_IRUSR  = 0x100
	S_IWUSR  = 0x80
	S_IXUSR  = 0x40
)

type Stat_t struct {
	Dev     uint64
	Ino     uint64
	Mode    uint32
	Nlink   uint32
	Uid     uint32
	Gid     uint32
	Rdev    uint64
	Size    int64
	Atim    Timespec
	Mtim    Timespec
	Ctim    Timespec
	Blksize int32
	_       [4]byte
	Blocks  int64
	Fstype  [16]int8
}

type Flock_t struct {
	Type   int16
	Whence int16
	_      [4]byte
	Start  int64
	Len    int64
	Sysid  int32
	Pid    int32
	Pad    [4]int64
}

type Dirent struct {
	Ino    uint64
	Off    int64
	Reclen uint16
	Name   [1]int8
	_      [5]byte
}

type _Fsblkcnt_t uint64

type Statvfs_t struct {
	Bsize    uint64
	Frsize   uint64
	Blocks   uint64
	Bfree    uint64
	Bavail   uint64
	Files    uint64
	Ffree    uint64
	Favail   uint64
	Fsid     uint64
	Basetype [16]int8
	Flag     uint64
	Namemax  uint64
	Fstr     [32]int8
}

type RawSockaddrInet4 struct {
	Family uint16
	Port   uint16
	Addr   [4]byte /* in_addr */
	Zero   [8]int8
}

type RawSockaddrInet6 struct {
	Family         uint16
	Port           uint16
	Flowinfo       uint32
	Addr           [16]byte /* in6_addr */
	Scope_id       uint32
	X__sin6_src_id uint32
}

type RawSockaddrUnix struct {
	Family uint16
	Path   [108]int8
}

type RawSockaddrDatalink struct {
	Family uint16
	Index  uint16
	Type   uint8
	Nlen   uint8
	Alen   uint8
	Slen   uint8
	Data   [244]int8
}

type RawSockaddr struct {
	Family uint16
	Data   [14]int8
}

type RawSockaddrAny struct {
	Addr RawSockaddr
	Pad  [236]int8
}

type _Socklen uint32

type Linger struct {
	Onoff  int32
	Linger int32
}

type Iovec struct {
	Base *int8
	Len  uint64
}

type IPMreq struct {
	Multiaddr [4]byte /* in_addr */
	Interface [4]byte /* in_addr */
}

type IPv6Mreq struct {
	Multiaddr [16]byte /* in6_addr */
	Interface uint32
}

type Msghdr struct {
	Name         *byte
	Namelen      uint32
	_            [4]byte
	Iov          *Iovec
	Iovlen       int32
	_            [4]byte
	Accrights    *int8
	Accrightslen int32
	_            [4]byte
}

type Cmsghdr struct {
	Len   uint32
	Level int32
	Type  int32
}

type Inet6Pktinfo struct {
	Addr    [16]byte /* in6_addr */
	Ifindex uint32
}

type IPv6MTUInfo struct {
	Addr RawSockaddrInet6
	Mtu  uint32
}

type ICMPv6Filter struct {
	X__icmp6_filt [8]uint32
}

const (
	SizeofSockaddrInet4    = 0x10
	SizeofSockaddrInet6    = 0x20
	SizeofSockaddrAny      = 0xfc
	SizeofSockaddrUnix     = 0x6e
	SizeofSockaddrDatalink = 0xfc
	SizeofLinger           = 0x8
	SizeofIPMreq           = 0x8
	SizeofIPv6Mreq         = 0x14
	SizeofMsghdr           = 0x30
	SizeofCmsghdr          = 0xc
	SizeofInet6Pktinfo     = 0x14
	SizeofIPv6MTUInfo      = 0x24
	SizeofICMPv6Filter     = 0x20
)

type FdSet struct {
	Bits [1024]int64
}

type Utsname struct {
	Sysname  [257]byte
	Nodename [257]byte
	Release  [257]byte
	Version  [257]byte
	Machine  [257]byte
}

type Ustat_t struct {
	Tfree  int64
	Tinode uint64
	Fname  [6]int8
	Fpack  [6]int8
	_      [4]byte
}

const (
	AT_FDCWD            = 0xffd19553
	AT_SYMLINK_NOFOLLOW = 0x1000
	AT_SYMLINK_FOLLOW   = 0x2000
	AT_REMOVEDIR        = 0x1
	AT_EACCESS          = 0x4
)

const (
	SizeofIfMsghdr  = 0x54
	SizeofIfData    = 0x44
	SizeofIfaMsghdr = 0x14
	SizeofRtMsghdr  = 0x4c
	SizeofRtMetrics = 0x28
)

type IfMsghdr struct {
	Msglen  uint16
	Version uint8
	Type    uint8
	Addrs   int32
	Flags   int32
	Index   uint16
	_       [2]byte
	Data    IfData
}

type IfData struct {
	Type       uint8
	Addrlen    uint8
	Hdrlen     uint8
	_          [1]byte
	Mtu        uint32
	Metric     uint32
	Baudrate   uint32
	Ipackets   uint32
	Ierrors    uint32
	Opackets   uint32
	Oerrors    uint32
	Collisions uint32
	Ibytes     uint32
	Obytes     uint32
	Imcasts    uint32
	Omcasts    uint32
	Iqdrops    uint32
	Noproto    uint32
	Lastchange Timeval32
}

type IfaMsghdr struct {
	Msglen  uint16
	Version uint8
	Type    uint8
	Addrs   int32
	Flags   int32
	Index   uint16
	_       [2]byte
	Metric  int32
}

type RtMsghdr struct {
	Msglen  uint16
	Version uint8
	Type    uint8
	Index   uint16
	_       [2]byte
	Flags   int32
	Addrs   int32
	Pid     int32
	Seq     int32
	Errno   int32
	Use     int32
	Inits   uint32
	Rmx     RtMetrics
}

type RtMetrics struct {
	Locks    uint32
	Mtu      uint32
	Hopcount uint32
	Expire   uint32
	Recvpipe uint32
	Sendpipe uint32
	Ssthresh uint32
	Rtt      uint32
	Rttvar   uint32
	Pksent   uint32
}

const (
	SizeofBpfVersion = 0x4
	SizeofBpfStat    = 0x80
	SizeofBpfProgram = 0x10
	SizeofBpfInsn    = 0x8
	SizeofBpfHdr     = 0x14
)

type BpfVersion struct {
	Major uint16
	Minor uint16
}

type BpfStat struct {
	Recv    uint64
	Drop    uint64
	Capt    uint64
	Padding [13]uint64
}

type BpfProgram struct {
	Len   uint32
	_     [4]byte
	Insns *BpfInsn
}

type BpfInsn struct {
	Code uint16
	Jt   uint8
	Jf   uint8
	K    uint32
}

type BpfTimeval struct {
	Sec  int32
	Usec int32
}

type BpfHdr struct {
	Tstamp  BpfTimeval
	Caplen  uint32
	Datalen uint32
	Hdrlen  uint16
	_       [2]byte
}

type Termios struct {
	Iflag uint32
	Oflag uint32
	Cflag uint32
	Lflag uint32
	Cc    [19]uint8
	_     [1]byte
}

type Termio struct {
	Iflag uint16
	Oflag uint16
	Cflag uint16
	Lflag uint16
	Line  int8
	Cc    [8]uint8
	_     [1]byte
}

type Winsize struct {
	Row    uint16
	Col    uint16
	Xpixel uint16
	Ypixel uint16
}

type PollFd struct {
	Fd      int32
	Events  int16
	Revents int16
}

const (
	POLLERR    = 0x8
	POLLHUP    = 0x10
	POLLIN     = 0x1
	POLLNVAL   = 0x20
	POLLOUT    = 0x4
	POLLPRI    = 0x2
	POLLRDBAND = 0x80
	POLLRDNORM = 0x40
	POLLWRBAND = 0x100
	POLLWRNORM = 0x4
)
<|endoftext|>


<commit_before>package json

import (
	"errors"
	"io"
)

type Encoder struct {
	w   io.Writer
	err error
}

func NewEncoder(w io.Writer) *Encoder {
	return &Encoder{w: w}
}

func (e *Encoder) Encode(v interface{}) error {
	b, err := Marshal(v)
	if err != nil {
		return err
	}
	_, err = e.w.Write(b)
	e.err = err
	return err
}

type Decoder struct {
	p   parser
	err error
}

type byteReader struct {
	io.Reader
}

func (br byteReader) ReadByte() (byte, error) {
	b := make([]byte, 1)
	_, err := br.Read(b)
	if err != nil {
		return 0, err
	}
	return b[0], nil
}

type parser struct {
	io.ByteReader
	err  error
	buf  byte
	read []byte
}

func (p *parser) Next() byte {
	var b byte
	if p.buf >= 0 {
		b = p.buf
		p.buf = 0
	} else {
		var err error
		b, err = p.ByteReader.ReadByte()
		if err != nil {
			p.err = err
			return 0
		}
	}
	p.read = append(p.read, b)
	return b
}

func (p *parser) Backup() {
	p.buf = p.read[len(p.read)-1]
	p.read = p.read[:len(p.read)-1]
}

func (p *parser) Accept(s string) bool {
	b := p.Next()
	for _, c := range s {
		if c == b {
			return true
		}
	}
	b.Backup()
	return false
}

func (p *parser) AcceptRun(s string) {
	for {
		b := p.Next()
		for _, c := range s {
			if c != b {
				b.Backup()
				return
			}
		}
	}
}

func (p *parser) Peek() byte {
	b := p.Next()
	p.Backup()
	return b
}

func NewDecoder(r io.Reader) *Decoder {
	b, ok := r.(io.ByteReader)
	if !ok {
		b = byteReader{r}
	}
	return &Decoder{p: parser{b}}
}

func (d *Decoder) Decode(v interface{}) error {
	bytes, err := d.readValue()
	if err != nil {
		return err
	}
	if !d.readValue() {
		if d.p.err != nil {
			return d.p.err
		}
		return errInvalidJSON
	}
	s := string(d.p.buf)
	d.p.buf = d.p.buf[:0]
	return UnmarshalString(s, v)
}

const whitespace = " 	\n\r"

func (d *Decoder) readValue() bool {
	d.p.AcceptRun(whitespace)
	var valid bool
	switch d.p.Peek() {
	case '"':
		valid = d.readString()
	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		valid = d.readNumber()
	case '{':
		valid = d.readObject()
	case '[':
		valid = d.readArray()
	case 't':
		valid = d.readTrue()
	case 'f':
		valid = d.readFalse()
	case 'n':
		valid = d.readNull()
	}
	return valid
}

func (d *Decoder) readString() bool {
	d.p.Accept("\"")
	for {
		switch c := d.p.Next(); c {
		case '"':
			return true
		case '\\':
			switch d.p.Next() {
			case '"', '\\', '/', 'b', 'n', 'r', 't':
			case 'u':
				if !d.p.Accept("0123456789abcdefABCDEF") || !d.p.Accept("0123456789abcdefABCDEF") || !d.p.Accept("0123456789abcdefABCDEF") || !d.p.Accept("0123456789abcdefABCDEF") {
					return false
				}
			default:
				return false
			}
		case 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x7f:
			return false
		}
	}
}

func (d *Decoder) readNumber(c byte) bool {
	d.p.Accept("-")
	if !d.p.Accept("0") {
		d.p.Accept("123456789")
		d.p.AcceptRun("0123456789")
	}
	if d.p.Accept(".") {
		d.p.AcceptRun("0123456789")
	}
	if d.p.Accept("eE") {
		d.p.Accept("+-")
		d.p.AcceptRun("0123456789")
	}
	return true
}

func (d *Decoder) readObject() bool {

}

func (d *Decoder) readArray() bool {

}

func (d *Decoder) readTrue() bool {
	return d.p.Accept("t") && d.p.Accept("r") && d.p.Accept("u") && d.p.Accept("e")
}

func (d *Decoder) readFalse() bool {
	return d.p.Accept("f") && d.p.Accept("a") && d.p.Accept("l") && d.p.Accept("s") && d.p.Accept("e")
}

func (d *Decoder) readNull() bool {
	return d.p.Accept("n") && d.p.Accept("u") && d.p.Accept("l") && d.p.Accept("l")
}

var errInvalidJSON = errors.New("invalid JSON")
<commit_msg>Added object and array reading for stream decoding<commit_after>package json

import (
	"errors"
	"io"
)

type Encoder struct {
	w   io.Writer
	err error
}

func NewEncoder(w io.Writer) *Encoder {
	return &Encoder{w: w}
}

func (e *Encoder) Encode(v interface{}) error {
	b, err := Marshal(v)
	if err != nil {
		return err
	}
	_, err = e.w.Write(b)
	e.err = err
	return err
}

type Decoder struct {
	p   parser
	err error
}

type byteReader struct {
	io.Reader
}

func (br byteReader) ReadByte() (byte, error) {
	b := make([]byte, 1)
	_, err := br.Read(b)
	if err != nil {
		return 0, err
	}
	return b[0], nil
}

type parser struct {
	io.ByteReader
	err  error
	buf  byte
	read []byte
}

func (p *parser) Next() byte {
	var b byte
	if p.buf >= 0 {
		b = p.buf
		p.buf = 0
	} else {
		var err error
		b, err = p.ByteReader.ReadByte()
		if err != nil {
			p.err = err
			return 0
		}
	}
	p.read = append(p.read, b)
	return b
}

func (p *parser) Backup() {
	p.buf = p.read[len(p.read)-1]
	p.read = p.read[:len(p.read)-1]
}

func (p *parser) Accept(s string) bool {
	b := p.Next()
	for _, c := range s {
		if c == b {
			return true
		}
	}
	b.Backup()
	return false
}

func (p *parser) AcceptRun(s string) {
	for {
		b := p.Next()
		for _, c := range s {
			if c != b {
				b.Backup()
				return
			}
		}
	}
}

func (p *parser) Peek() byte {
	b := p.Next()
	p.Backup()
	return b
}

func NewDecoder(r io.Reader) *Decoder {
	b, ok := r.(io.ByteReader)
	if !ok {
		b = byteReader{r}
	}
	return &Decoder{p: parser{b}}
}

func (d *Decoder) Decode(v interface{}) error {
	bytes, err := d.readValue()
	if err != nil {
		return err
	}
	if !d.readValue() {
		if d.p.err != nil {
			return d.p.err
		}
		return errInvalidJSON
	}
	s := string(d.p.buf)
	d.p.buf = d.p.buf[:0]
	return UnmarshalString(s, v)
}

const whitespace = " 	\n\r"

func (d *Decoder) readValue() bool {
	d.p.AcceptRun(whitespace)
	var valid bool
	switch d.p.Peek() {
	case '"':
		valid = d.readString()
	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		valid = d.readNumber()
	case '{':
		valid = d.readObject()
	case '[':
		valid = d.readArray()
	case 't':
		valid = d.readTrue()
	case 'f':
		valid = d.readFalse()
	case 'n':
		valid = d.readNull()
	}
	return valid
}

func (d *Decoder) readString() bool {
	if !d.p.Accept("\"") {
		return false
	}
	for {
		switch c := d.p.Next(); c {
		case '"':
			return true
		case '\\':
			switch d.p.Next() {
			case '"', '\\', '/', 'b', 'n', 'r', 't':
			case 'u':
				if !d.p.Accept("0123456789abcdefABCDEF") || !d.p.Accept("0123456789abcdefABCDEF") || !d.p.Accept("0123456789abcdefABCDEF") || !d.p.Accept("0123456789abcdefABCDEF") {
					return false
				}
			default:
				return false
			}
		case 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x7f:
			return false
		}
	}
}

func (d *Decoder) readNumber(c byte) bool {
	d.p.Accept("-")
	if !d.p.Accept("0") {
		d.p.Accept("123456789")
		d.p.AcceptRun("0123456789")
	}
	if d.p.Accept(".") {
		d.p.AcceptRun("0123456789")
	}
	if d.p.Accept("eE") {
		d.p.Accept("+-")
		d.p.AcceptRun("0123456789")
	}
	return true
}

func (d *Decoder) readObject() bool {
	d.p.Accept("{")
	for {
		d.p.AcceptRun(whitespace)
		if !d.readString() {
			return false
		}
		d.p.AcceptRun(whitespace)
		if !d.p.Accept(":") {
			return false
		}
		if !d.readValue() {
			return false
		}
		d.p.AcceptRun(whitespace)
		if d.p.Accept("}") {
			return true
		}
		if !d.p.Accept(",") {
			return false
		}
	}
}

func (d *Decoder) readArray() bool {
	d.p.Accept("[")
	d.p.AcceptRun(whitespace)
	if d.p.Accept("]") {
		return true
	}
	for {
		if !d.readValue() {
			return false
		}
		d.p.AcceptRun(whitespace)
		if d.p.Accept("]") {
			return true
		}
		if !d.p.Accept(",") {
			return false
		}
	}
}

func (d *Decoder) readTrue() bool {
	return d.p.Accept("t") && d.p.Accept("r") && d.p.Accept("u") && d.p.Accept("e")
}

func (d *Decoder) readFalse() bool {
	return d.p.Accept("f") && d.p.Accept("a") && d.p.Accept("l") && d.p.Accept("s") && d.p.Accept("e")
}

func (d *Decoder) readNull() bool {
	return d.p.Accept("n") && d.p.Accept("u") && d.p.Accept("l") && d.p.Accept("l")
}

var errInvalidJSON = errors.New("invalid JSON")
<|endoftext|>


<commit_before>package parser

import "github.com/defendertx/genetics/genes"

type tree struct {
	left  *tree
	token string
	right *tree
}

func Evaluate(chromosome string) int32 {

}

func buildAst(chromosome string) tree {
	values := ""
	for i := 0; i < len(chromosome); i += genes.GENE_LENGTH {
		values += genes.GeneToValue(chromosome[i : i+GENE_LENGTH])
		values += " "
	}
}

func parseFormula()
<commit_msg>Removed stale code from parser<commit_after>package parser

type tree struct {
	left  *tree
	token string
	right *tree
}
<|endoftext|>


<commit_before>package parser

import (
	"go/ast"
	"go/parser"
	"go/token"
	"strings"
)

const structComment = "easyjson:json"

type Parser struct {
	PkgPath     string
	PkgName     string
	StructNames []string
	AllStructs  bool
}

type visitor struct {
	*Parser

	name string
}

func (p *Parser) needStruct(comments string) bool {
	if p.AllStructs {
		return true
	}
	for _, v := range strings.Split(comments, "\n") {
		if strings.HasPrefix(v, structComment) {
			return true
		}
	}
	return false
}

func (v *visitor) Visit(n ast.Node) (w ast.Visitor) {
	switch n := n.(type) {
	case *ast.File:
		v.PkgName = n.Name.String()
		return v

	case *ast.GenDecl:
		if !v.needStruct(n.Doc.Text()) {
			return nil
		}
		return v
	case *ast.TypeSpec:
		v.name = n.Name.String()
		return v
	case *ast.StructType:
		v.StructNames = append(v.StructNames, v.name)
		return nil
	}
	return nil
}

func (p *Parser) Parse(fname string) error {
	var err error
	if p.PkgPath, err = getPkgPath(fname); err != nil {
		return err
	}

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, fname, nil, parser.ParseComments)
	if err != nil {
		return err
	}

	ast.Walk(&visitor{Parser: p}, f)
	return nil
}
<commit_msg>Allow generating marshalers for 'renamed' structs.<commit_after>package parser

import (
	"go/ast"
	"go/parser"
	"go/token"
	"strings"
)

const structComment = "easyjson:json"

type Parser struct {
	PkgPath     string
	PkgName     string
	StructNames []string
	AllStructs  bool
}

type visitor struct {
	*Parser

	name     string
	explicit bool
}

func (p *Parser) needType(comments string) bool {
	for _, v := range strings.Split(comments, "\n") {
		if strings.HasPrefix(v, structComment) {
			return true
		}
	}
	return false
}

func (v *visitor) Visit(n ast.Node) (w ast.Visitor) {
	switch n := n.(type) {
	case *ast.File:
		v.PkgName = n.Name.String()
		return v

	case *ast.GenDecl:
		v.explicit = v.needType(n.Doc.Text())

		if !v.explicit && !v.AllStructs {
			return nil
		}
		return v
	case *ast.TypeSpec:
		v.name = n.Name.String()

		// Allow to specify non-structs explicitly independent of '-all' flag.
		if v.explicit {
			v.StructNames = append(v.StructNames, v.name)
			return nil
		}
		return v
	case *ast.StructType:
		v.StructNames = append(v.StructNames, v.name)
		return nil
	}
	return nil
}

func (p *Parser) Parse(fname string) error {
	var err error
	if p.PkgPath, err = getPkgPath(fname); err != nil {
		return err
	}

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, fname, nil, parser.ParseComments)
	if err != nil {
		return err
	}

	ast.Walk(&visitor{Parser: p}, f)
	return nil
}
<|endoftext|>


<commit_before>/*
 * Raw transaction manipulation methods.
 * Implement "non-default" scriptSig/scriptPubkey combinations
 * (contracts).
 *
 * (c) 2013 Bernd Fix   >Y<
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *#####################################################################
 *
 * The binary encoded raw transaction looks like this:
 *
 *  ------+-------------+---------+---------------------------------
 *  Level | Field       | length  | Value/Comment
 *  ------+-------------+---------+---------------------------------
 *      0 | VERSION     |    4    | 01000000 = version 1
 *      0 | N_VOUT      |    1    | Number of VOUT defs to follow =1
 *  ------+-------------+---------+---------------------------------
 *      1 | VOUT:TXID   |   32    | Transaction ID
 *      1 | VOUT:N      |    4    | VOUT number in transaction
 *      1 | VOUT:SCRIPT |         | scriptSig (hex-encoded)
 *  ------+-------------+---------+---------------------------------
 *      2 | SCRIPT:LEN  |    1    | Length of script
 *      2 | SCRIPT:DATA |   <n>   | Script data
 *  ------+-------------+---------+---------------------------------
 *      1 | VOUT:SEQ    |         | FFFFFFFF = sequence number (-1)
 *  ------+-------------+---------+---------------------------------
 *      0 | N_VIN       |    1    | Number of VIN defs to follow =1
 *  ------+-------------+---------+---------------------------------
 *      1 | VIN:VALUE   |    4    | Number of Satoshis (1e-8 btc)
 *      1 | VIN:???     |    4    | 00000000 = ????
 *      1 | VIN:SCRIPT  |         | scriptPubkey
 *  ------+-------------+---------+---------------------------------
 *      2 | SCRIPT:LEN  |    1    | Length of script
 *      2 | SCRIPT:DATA |   <n>   | Script data
 *  ------+-------------+---------+---------------------------------
 *      0 | LOCKTIME    |    4    | 00000000 = locktime
 *  ------+-------------+---------+---------------------------------
 *
 *#####################################################################
 */

package util

///////////////////////////////////////////////////////////////////////
// Import external declarations

import (
	"encoding/hex"
	"errors"
)

///////////////////////////////////////////////////////////////////////
/*
 * Change "scriptPubKey" to "PayToScriptHash":
 * This only works if there is only one input/output slot defined in
 * the transaction. The old "scriptPubKey" is completely dropped.
 *
 * @param raw string - hex string of raw transaction
 * @param script []byte - serialized script
 * @return string - new hex-encoded raw string
 * @return error - error instance (or nil)
 */
func PayToScriptHash(raw string, script []byte) (string, error) {

	// decode raw string from hex
	in_raw, err := hex.DecodeString(raw)
	if err != nil {
		return "", err
	}

	// compute hash over data
	hash := Hash160(script)

	// create a "PayToScriptHash" script
	yscript := make([]byte, 0)
	yscript = append(yscript, 0xa9)
	yscript = append(yscript, 0x14)
	yscript = append(yscript, hash...)
	yscript = append(yscript, 0x87)

	// dissect raw transaction and change VOUT
	pos := 4
	n_vout := int(in_raw[pos])
	if n_vout != 1 {
		return "", errors.New("invalid number of vout (!= 1)")
	}
	pos += 37
	scrlen := int(in_raw[pos])
	if scrlen != 0 {
		return "", errors.New("invalid scriptSig size (!= 0)")
	}
	pos += scrlen + 5
	n_vin := int(in_raw[pos])
	if n_vin != 1 {
		return "", errors.New("invalid number of vin (!= 1)")
	}
	pos += 9
	scrlen = int(in_raw[pos])

	out_raw := make([]byte, 0)
	out_raw = append(out_raw, in_raw[:pos]...)
	out_raw = append(out_raw, 23)
	out_raw = append(out_raw, yscript...)
	out_raw = append(out_raw, in_raw[pos+scrlen+1:]...)

	// return new raw transaction
	return hex.EncodeToString(out_raw), nil
}

///////////////////////////////////////////////////////////////////////
// Helper methods:

/*
 * Create P2SH redeem script that includes data
 */
func ScriptFromData(data []byte, key []byte) []byte {
	out := make([]byte, 0)

	// push data
	size := len(data)
	out = append(out, LengthPrefix(size)...)
	out = append(out, data...)
	// OP_DROP
	out = append(out, 0x75)

	// push public key
	size = len(key)
	out = append(out, LengthPrefix(size)...)
	out = append(out, key...)
	// push OP_CHECKSIG
	return append(out, 0xac)
}

//---------------------------------------------------------------------
/*
 * Assemble the length prefix for data.
 */
func LengthPrefix(size int) []byte {
	prefix := make([]byte, 0)
	switch {
	case size < 76:
		prefix = append(prefix, byte(size))
	case size < 256:
		prefix = append(prefix, 0x4c)
		prefix = append(prefix, byte(size))
	case size < 65536:
		// size of script
		prefix = append(prefix, 0x4d)
		prefix = append(prefix, byte(size&0xFF))
		prefix = append(prefix, byte((size>>8)&0xFF))
	case size < 65536:
		prefix = append(prefix, 0x4d)
		prefix = append(prefix, byte(size&0xFF))
		prefix = append(prefix, byte((size>>8)&0xFF))
		prefix = append(prefix, byte((size>>16)&0xFF))
		prefix = append(prefix, byte((size>>24)&0xFF))
	}
	return prefix
}
<commit_msg>New scriptPubKey: TX_NULL_DATA to attach up to 80 bytes of arbitrary data to transaction.<commit_after>/*
 * Raw transaction manipulation methods.
 * Implement "non-default" scriptSig/scriptPubkey combinations
 * (contracts).
 *
 * (c) 2013 Bernd Fix   >Y<
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *#####################################################################
 *
 * The binary encoded raw transaction looks like this:
 *
 *  ------+-------------+---------+---------------------------------
 *  Level | Field       | length  | Value/Comment
 *  ------+-------------+---------+---------------------------------
 *      0 | VERSION     |    4    | 01000000 = version 1
 *      0 | N_VOUT      |    1    | Number of VOUT defs to follow =1
 *  ------+-------------+---------+---------------------------------
 *      1 | VOUT:TXID   |   32    | Transaction ID
 *      1 | VOUT:N      |    4    | VOUT number in transaction
 *      1 | VOUT:SCRIPT |         | scriptSig (hex-encoded)
 *  ------+-------------+---------+---------------------------------
 *      2 | SCRIPT:LEN  |    1    | Length of script
 *      2 | SCRIPT:DATA |   <n>   | Script data
 *  ------+-------------+---------+---------------------------------
 *      1 | VOUT:SEQ    |         | FFFFFFFF = sequence number (-1)
 *  ------+-------------+---------+---------------------------------
 *      0 | N_VIN       |    1    | Number of VIN defs to follow =1
 *  ------+-------------+---------+---------------------------------
 *      1 | VIN:VALUE   |    4    | Number of Satoshis (1e-8 btc)
 *      1 | VIN:???     |    4    | 00000000 = ????
 *      1 | VIN:SCRIPT  |         | scriptPubkey
 *  ------+-------------+---------+---------------------------------
 *      2 | SCRIPT:LEN  |    1    | Length of script
 *      2 | SCRIPT:DATA |   <n>   | Script data
 *  ------+-------------+---------+---------------------------------
 *      0 | LOCKTIME    |    4    | 00000000 = locktime
 *  ------+-------------+---------+---------------------------------
 *
 *#####################################################################
 */

package util

///////////////////////////////////////////////////////////////////////
// Import external declarations

import (
	"encoding/hex"
	"errors"
)

///////////////////////////////////////////////////////////////////////
/*
 * Assemble a TX_NULL_DATA script.
 */
func NullDataScript(data []byte) ([]byte, error) {
	size := len(data)
	if size > 75 {
		return nil, errors.New("attached data to big")
	}

	script := make([]byte, 0)
	script = append(script, 0x6a) // OP_RETURN
	script = append(script, LengthPrefix(size)...)
	script = append(script, data...)
	return script, nil
}

///////////////////////////////////////////////////////////////////////
/*
 * Change "scriptPubKey" to new script.
 * This only works if there is only one input/output slot defined in
 * the transaction. The old "scriptPubKey" is completely dropped.
 *
 * @param raw string - hex string of raw transaction
 * @param script []byte - replacement script
 * @return string - new hex-encoded raw string
 * @return error - error instance (or nil)
 */
func ReplaceScriptPubKey(raw string, script []byte) (string, error) {

	// decode raw string from hex
	in_raw, err := hex.DecodeString(raw)
	if err != nil {
		return "", err
	}

	// dissect raw transaction and change VOUT
	pos := 4
	n_vout := int(in_raw[pos])
	if n_vout != 1 {
		return "", errors.New("invalid number of vout (!= 1)")
	}
	pos += 37
	scrlen := int(in_raw[pos])
	if scrlen != 0 {
		return "", errors.New("invalid scriptSig size (!= 0)")
	}
	pos += scrlen + 5
	n_vin := int(in_raw[pos])
	if n_vin != 1 {
		return "", errors.New("invalid number of vin (!= 1)")
	}
	pos += 9
	scrlen = int(in_raw[pos])

	out_raw := make([]byte, 0)
	out_raw = append(out_raw, in_raw[:pos]...)
	out_raw = append(out_raw, LengthPrefix(len(script))...)
	out_raw = append(out_raw, script...)
	out_raw = append(out_raw, in_raw[pos+scrlen+1:]...)

	// return new raw transaction
	return hex.EncodeToString(out_raw), nil
}

///////////////////////////////////////////////////////////////////////
/*
 * Assemble the length prefix for data.
 */
func LengthPrefix(size int) []byte {
	prefix := make([]byte, 0)
	switch {
	case size < 76:
		prefix = append(prefix, byte(size))
	case size < 256:
		prefix = append(prefix, 0x4c)
		prefix = append(prefix, byte(size))
	case size < 65536:
		// size of script
		prefix = append(prefix, 0x4d)
		prefix = append(prefix, byte(size&0xFF))
		prefix = append(prefix, byte((size>>8)&0xFF))
	case size < 65536:
		prefix = append(prefix, 0x4d)
		prefix = append(prefix, byte(size&0xFF))
		prefix = append(prefix, byte((size>>8)&0xFF))
		prefix = append(prefix, byte((size>>16)&0xFF))
		prefix = append(prefix, byte((size>>24)&0xFF))
	}
	return prefix
}
<|endoftext|>


<commit_before>package main

import (
	"http"
	"log"
	"socketio"
	"sync"
	"time"
)

var (
	nicks = make(map[string]string)
	mu    sync.Mutex
)

func main() {
	// use verbose logger
	socketio.Log = socketio.VerboseLogger
	sio := socketio.NewServer(nil)

	http.Handle("/", http.FileServer(http.Dir("www/")))
	http.Handle("/socket.io/", http.StripPrefix("/socket.io/", sio.Handler(func(c *socketio.Conn) {
		var msg socketio.Message
		var nick string

		for {
			if err := c.Receive(&msg); err != nil {
				break
			}

			event, _ := msg.Event()
			switch event {
			case "nickname":
				if err := msg.ReadArguments(&nick); err != nil {
					continue
				}

				mu.Lock()
				if nicks[nick] != "" {
					c.Reply(&msg, true)
				} else {
					c.Reply(&msg, false)
					nicks[nick] = nick
					sio.EmitExcept(c, "announcement", nick+" connected")
					sio.Emit("nicknames", nicks)
				}
				mu.Unlock()

			case "user message":
				var payload string
				if err := msg.ReadArguments(&payload); err != nil {
					continue
				}
				sio.EmitExcept(c, "user message", nick, payload)
			}
		}

		if nick != "" {
			mu.Lock()
			nicks[nick] = "", false
			sio.Emit("announcement", nick+" disconnected")
			sio.Emit("nicknames", nicks)
			mu.Unlock()
		}
	})))

	go func() {
		time.Sleep(2e9)
		log.Println("Spawning echo client")
		echo()
	}()

	log.Println("Server starting. Tune your browser to http://localhost:8080/")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func echo() {
	var msg socketio.Message
	c, err := socketio.Dial("http://localhost:8080/socket.io/", "http://localhost:8080/")
	defer c.Close()
	if err != nil {
		panic(err)
	}
	c.Emit("nickname", "echo-client")
	for {
		if err := c.Receive(&msg); err != nil {
			log.Print("client received error: ", err)
			return
		}
		c.Emit("user message", msg.String())
	}
}
<commit_msg>run go fix<commit_after>package main

import (
	"log"
	"net/http"
	"socketio"
	"sync"
	"time"
)

var (
	nicks = make(map[string]string)
	mu    sync.Mutex
)

func main() {
	// use verbose logger
	socketio.Log = socketio.VerboseLogger
	sio := socketio.NewServer(nil)

	http.Handle("/", http.FileServer(http.Dir("www/")))
	http.Handle("/socket.io/", http.StripPrefix("/socket.io/", sio.Handler(func(c *socketio.Conn) {
		var msg socketio.Message
		var nick string

		for {
			if err := c.Receive(&msg); err != nil {
				break
			}

			event, _ := msg.Event()
			switch event {
			case "nickname":
				if err := msg.ReadArguments(&nick); err != nil {
					continue
				}

				mu.Lock()
				if nicks[nick] != "" {
					c.Reply(&msg, true)
				} else {
					c.Reply(&msg, false)
					nicks[nick] = nick
					sio.EmitExcept(c, "announcement", nick+" connected")
					sio.Emit("nicknames", nicks)
				}
				mu.Unlock()

			case "user message":
				var payload string
				if err := msg.ReadArguments(&payload); err != nil {
					continue
				}
				sio.EmitExcept(c, "user message", nick, payload)
			}
		}

		if nick != "" {
			mu.Lock()
			delete(nicks, nick)
			sio.Emit("announcement", nick+" disconnected")
			sio.Emit("nicknames", nicks)
			mu.Unlock()
		}
	})))

	go func() {
		time.Sleep(2e9)
		log.Println("Spawning echo client")
		echo()
	}()

	log.Println("Server starting. Tune your browser to http://localhost:8080/")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func echo() {
	var msg socketio.Message
	c, err := socketio.Dial("http://localhost:8080/socket.io/", "http://localhost:8080/")
	defer c.Close()
	if err != nil {
		panic(err)
	}
	c.Emit("nickname", "echo-client")
	for {
		if err := c.Receive(&msg); err != nil {
			log.Print("client received error: ", err)
			return
		}
		c.Emit("user message", msg.String())
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/ddo/go-crawler"
)

func main() {
	no := 0

	c := crawler.New("http://talktv.vn/", 50)

	c.Start(func(url string) {
		no++
		fmt.Println(no, "\t ", url)
	}, func(err error) {
		fmt.Println("error\t", err)
	})

	fmt.Println("done thanks god")
}
<commit_msg>update example<commit_after>package main

import (
	"fmt"
	"github.com/ddo/go-crawler"
)

func main() {
	no := 0

	c := crawler.New("http://facebook.com/", 10)

	receiver_url := func(url string) {
		no++
		fmt.Println(no, "\t ", url)
	}

	receiver_err := func(err error) {
		fmt.Println("error\t", err)
	}

	c.Start(receiver_url, receiver_err)

	fmt.Println("done thanks god")
}
<|endoftext|>


<commit_before>package annotate

import (
	// ensure all the ginkgo tests are loaded
	_ "k8s.io/kubernetes/openshift-hack/e2e"
)

var (
	TestMaps = map[string][]string{
		// alpha features that are not gated
		"[Disabled:Alpha]": {
			// ALPHA features in 1.19, disabled by default.
			// !!! Review their status as part of the 1.20 rebase.
			`\[Feature:CSIStorageCapacity\]`,
			`\[Feature:IPv6DualStack.*\]`,
			`\[Feature:ServiceAccountIssuerDiscovery\]`,
			`\[Feature:SetHostnameAsFQDN\]`,
			`\[Feature:TTLAfterFinished\]`,

			// BETA features in 1.19, enabled by default
			// Their enablement is tracked via bz's targeted at 4.6.
			`\[Feature:SCTPConnectivity\]`, // https://bugzilla.redhat.com/show_bug.cgi?id=1861606
		},
		// tests for features that are not implemented in openshift
		"[Disabled:Unimplemented]": {
			`\[Feature:Networking-IPv6\]`, // openshift-sdn doesn't support yet
			`Monitoring`,                  // Not installed, should be
			`Cluster level logging`,       // Not installed yet
			`Kibana`,                      // Not installed
			`Ubernetes`,                   // Can't set zone labels today
			`kube-ui`,                     // Not installed by default
			`Kubernetes Dashboard`,        // Not installed by default (also probably slow image pull)

			`NetworkPolicy.*egress`,     // not supported
			`NetworkPolicy.*named port`, // not yet implemented
			`enforce egress policy`,     // not support
			`should proxy to cadvisor`,  // we don't expose cAdvisor port directly for security reasons

			`NetworkPolicy.*IPBlock`,          // not supported
			`NetworkPolicy.*Egress`,           // not supported
			`NetworkPolicy.*default-deny-all`, // not supported
		},
		// tests that rely on special configuration that we do not yet support
		"[Disabled:SpecialConfig]": {
			// GPU node needs to be available
			`\[Feature:GPUDevicePlugin\]`,
			`\[sig-scheduling\] GPUDevicePluginAcrossRecreate \[Feature:Recreate\]`,

			`\[Feature:ImageQuota\]`,                    // Quota isn't turned on by default, we should do that and then reenable these tests
			`\[Feature:Audit\]`,                         // Needs special configuration
			`\[Feature:LocalStorageCapacityIsolation\]`, // relies on a separate daemonset?
			`\[sig-cloud-provider-gcp\]`,                // these test require a different configuration - note that GCE tests from the sig-cluster-lifecycle were moved to the sig-cloud-provider-gcpcluster lifecycle see https://github.com/kubernetes/kubernetes/commit/0b3d50b6dccdc4bbd0b3e411c648b092477d79ac#diff-3b1910d08fb8fd8b32956b5e264f87cb

			`kube-dns-autoscaler`, // Don't run kube-dns
			`should check if Kubernetes master services is included in cluster-info`, // Don't run kube-dns
			`DNS configMap`, // this tests dns federation configuration via configmap, which we don't support yet

			`NodeProblemDetector`,                   // requires a non-master node to run on
			`Advanced Audit should audit API calls`, // expects to be able to call /logs

			`Firewall rule should have correct firewall rules for e2e cluster`, // Upstream-install specific
		},
		// tests that are known broken and need to be fixed upstream or in openshift
		// always add an issue here
		"[Disabled:Broken]": {
			`mount an API token into pods`,                              // We add 6 secrets, not 1
			`ServiceAccounts should ensure a single API token exists`,   // We create lots of secrets
			`unchanging, static URL paths for kubernetes api services`,  // the test needs to exclude URLs that are not part of conformance (/logs)
			`Services should be able to up and down services`,           // we don't have wget installed on nodes
			`Network should set TCP CLOSE_WAIT timeout`,                 // possibly some difference between ubuntu and fedora
			`\[NodeFeature:Sysctls\]`,                                   // needs SCC support
			`should check kube-proxy urls`,                              // previously this test was skipped b/c we reported -1 as the number of nodes, now we report proper number and test fails
			`SSH`,                                                       // TRIAGE
			`should implement service.kubernetes.io/service-proxy-name`, // this is an optional test that requires SSH. sig-network
			`should allow ingress access on one named port`,             // https://bugzilla.redhat.com/show_bug.cgi?id=1711602
			`recreate nodes and ensure they function upon restart`,      // https://bugzilla.redhat.com/show_bug.cgi?id=1756428
			`\[Driver: iscsi\]`,                                         // https://bugzilla.redhat.com/show_bug.cgi?id=1711627

			"RuntimeClass should reject",

			`Services should implement service.kubernetes.io/headless`,       // requires SSH access to function, needs to be refactored
			`ClusterDns \[Feature:Example\] should create pod that uses dns`, // doesn't use bindata, not part of kube test binary
			`Simple pod should handle in-cluster config`,                     // kubectl cp doesn't work or is not preserving executable bit, we have this test already

			// TODO(node): configure the cri handler for the runtime class to make this work
			"should run a Pod requesting a RuntimeClass with a configured handler",
			"should reject a Pod requesting a RuntimeClass with conflicting node selector",
			"should run a Pod requesting a RuntimeClass with scheduling",

			// A fix is in progress: https://github.com/openshift/origin/pull/24709
			`Multi-AZ Clusters should spread the pods of a replication controller across zones`,
		},
		// tests that may work, but we don't support them
		"[Disabled:Unsupported]": {
			`\[Driver: rbd\]`,  // OpenShift 4.x does not support Ceph RBD (use CSI instead)
			`\[Driver: ceph\]`, // OpenShift 4.x does not support CephFS (use CSI instead)
		},
		// tests too slow to be part of conformance
		"[Slow]": {
			`\[sig-scalability\]`,                          // disable from the default set for now
			`should create and stop a working application`, // Inordinately slow tests

			`\[Feature:PerformanceDNS\]`, // very slow

			`validates that there exists conflict between pods with same hostPort and protocol but one using 0\.0\.0\.0 hostIP`, // 5m, really?
		},
		// tests that are known flaky
		"[Flaky]": {
			`Job should run a job to completion when tasks sometimes fail and are not locally restarted`, // seems flaky, also may require too many resources
			// TODO(node): test works when run alone, but not in the suite in CI
			`\[Feature:HPA\] Horizontal pod autoscaling \(scale resource: CPU\) \[sig-autoscaling\] ReplicationController light Should scale from 1 pod to 2 pods`,
		},
		// tests that must be run without competition
		"[Serial]": {
			`\[Disruptive\]`,
			`\[Feature:Performance\]`, // requires isolation

			`Service endpoints latency`, // requires low latency
			`Clean up pods on node`,     // schedules up to max pods per node
			`DynamicProvisioner should test that deleting a claim before the volume is provisioned deletes the volume`, // test is very disruptive to other tests

			`Multi-AZ Clusters should spread the pods of a service across zones`, // spreading is a priority, not a predicate, and if the node is temporarily full the priority will be ignored

			`Should be able to support the 1\.7 Sample API Server using the current Aggregator`, // down apiservices break other clients today https://bugzilla.redhat.com/show_bug.cgi?id=1623195

			`\[Feature:HPA\] Horizontal pod autoscaling \(scale resource: CPU\) \[sig-autoscaling\] ReplicationController light Should scale from 1 pod to 2 pods`,

			`should prevent Ingress creation if more than 1 IngressClass marked as default`, // https://bugzilla.redhat.com/show_bug.cgi?id=1822286

			`\[sig-network\] IngressClass \[Feature:Ingress\] should set default value on new IngressClass`, //https://bugzilla.redhat.com/show_bug.cgi?id=1833583
		},
		"[Skipped:azure]": {
			"Networking should provide Internet connection for containers", // Azure does not allow ICMP traffic to internet.
		},
		"[Skipped:gce]": {
			// Requires creation of a different compute instance in a different zone and is not compatible with volumeBindingMode of WaitForFirstConsumer which we use in 4.x
			`\[sig-scheduling\] Multi-AZ Cluster Volumes \[sig-storage\] should only be allowed to provision PDs in zones where nodes exist`,

			// The following tests try to ssh directly to a node. None of our nodes have external IPs
			`\[k8s.io\] \[sig-node\] crictl should be able to run crictl on the node`,
			`\[sig-storage\] Flexvolumes should be mountable`,
			`\[sig-storage\] Detaching volumes should not work when mount is in progress`,

			// We are using openshift-sdn to conceal metadata
			`\[sig-auth\] Metadata Concealment should run a check-metadata-concealment job to completion`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1740959
			`\[sig-api-machinery\] AdmissionWebhook should be able to deny pod and configmap creation`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1745720
			`\[sig-storage\] CSI Volumes \[Driver: pd.csi.storage.gke.io\]\[Serial\]`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1749882
			`\[sig-storage\] CSI Volumes CSI Topology test using GCE PD driver \[Serial\]`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1751367
			`gce-localssd-scsi-fs`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1750851
			// should be serial if/when it's re-enabled
			`\[HPA\] Horizontal pod autoscaling \(scale resource: Custom Metrics from Stackdriver\)`,
		},
		"[sig-node]": {
			`\[NodeConformance\]`,
			`NodeLease`,
			`lease API`,
			`\[NodeFeature`,
			`\[NodeAlphaFeature`,
			`Probing container`,
			`Security Context When creating a`,
			`Downward API should create a pod that prints his name and namespace`,
			`Liveness liveness pods should be automatically restarted`,
			`Secret should create a pod that reads a secret`,
			`Pods should delete a collection of pods`,
		},
		"[sig-cluster-lifecycle]": {
			`Feature:ClusterAutoscalerScalability`,
			`recreate nodes and ensure they function`,
		},
		"[sig-arch]": {
			// not run, assigned to arch as catch-all
			`\[Feature:GKELocalSSD\]`,
			`\[Feature:GKENodePool\]`,
		},
	}

	// labelExcludes temporarily block tests out of a specific suite
	LabelExcludes = map[string][]string{}

	ExcludedTests = []string{
		`\[Disabled:`,
		`\[Disruptive\]`,
		`\[Skipped\]`,
		`\[Slow\]`,
		`\[Flaky\]`,
		`\[Local\]`,
	}
)
<commit_msg>UPSTREAM: <carry>: Update test annotation rules<commit_after>package annotate

import (
	// ensure all the ginkgo tests are loaded
	_ "k8s.io/kubernetes/openshift-hack/e2e"
)

var (
	TestMaps = map[string][]string{
		// alpha features that are not gated
		"[Disabled:Alpha]": {
			// ALPHA features in 1.19, disabled by default.
			// !!! Review their status as part of the 1.20 rebase.
			`\[Feature:CSIStorageCapacity\]`,
			`\[Feature:IPv6DualStack.*\]`,
			`\[Feature:ServiceAccountIssuerDiscovery\]`,
			`\[Feature:SetHostnameAsFQDN\]`,
			`\[Feature:TTLAfterFinished\]`,

			// BETA features in 1.19, enabled by default
			// Their enablement is tracked via bz's targeted at 4.6.
			`\[Feature:SCTPConnectivity\]`, // https://bugzilla.redhat.com/show_bug.cgi?id=1861606
		},
		// tests for features that are not implemented in openshift
		"[Disabled:Unimplemented]": {
			`\[Feature:Networking-IPv6\]`, // openshift-sdn doesn't support yet
			`Monitoring`,                  // Not installed, should be
			`Cluster level logging`,       // Not installed yet
			`Kibana`,                      // Not installed
			`Ubernetes`,                   // Can't set zone labels today
			`kube-ui`,                     // Not installed by default
			`Kubernetes Dashboard`,        // Not installed by default (also probably slow image pull)

			`NetworkPolicy.*egress`,     // not supported
			`NetworkPolicy.*named port`, // not yet implemented
			`enforce egress policy`,     // not support
			`should proxy to cadvisor`,  // we don't expose cAdvisor port directly for security reasons

			`NetworkPolicy.*IPBlock`,          // not supported
			`NetworkPolicy.*Egress`,           // not supported
			`NetworkPolicy.*default-deny-all`, // not supported
		},
		// tests that rely on special configuration that we do not yet support
		"[Disabled:SpecialConfig]": {
			// GPU node needs to be available
			`\[Feature:GPUDevicePlugin\]`,
			`\[sig-scheduling\] GPUDevicePluginAcrossRecreate \[Feature:Recreate\]`,

			`\[Feature:ImageQuota\]`,                    // Quota isn't turned on by default, we should do that and then reenable these tests
			`\[Feature:Audit\]`,                         // Needs special configuration
			`\[Feature:LocalStorageCapacityIsolation\]`, // relies on a separate daemonset?
			`\[sig-cloud-provider-gcp\]`,                // these test require a different configuration - note that GCE tests from the sig-cluster-lifecycle were moved to the sig-cloud-provider-gcpcluster lifecycle see https://github.com/kubernetes/kubernetes/commit/0b3d50b6dccdc4bbd0b3e411c648b092477d79ac#diff-3b1910d08fb8fd8b32956b5e264f87cb

			`kube-dns-autoscaler`, // Don't run kube-dns
			`should check if Kubernetes master services is included in cluster-info`, // Don't run kube-dns
			`DNS configMap`, // this tests dns federation configuration via configmap, which we don't support yet

			`NodeProblemDetector`,                   // requires a non-master node to run on
			`Advanced Audit should audit API calls`, // expects to be able to call /logs

			`Firewall rule should have correct firewall rules for e2e cluster`, // Upstream-install specific
		},
		// tests that are known broken and need to be fixed upstream or in openshift
		// always add an issue here
		"[Disabled:Broken]": {
			`mount an API token into pods`,                              // We add 6 secrets, not 1
			`ServiceAccounts should ensure a single API token exists`,   // We create lots of secrets
			`unchanging, static URL paths for kubernetes api services`,  // the test needs to exclude URLs that are not part of conformance (/logs)
			`Services should be able to up and down services`,           // we don't have wget installed on nodes
			`Network should set TCP CLOSE_WAIT timeout`,                 // possibly some difference between ubuntu and fedora
			`\[NodeFeature:Sysctls\]`,                                   // needs SCC support
			`should check kube-proxy urls`,                              // previously this test was skipped b/c we reported -1 as the number of nodes, now we report proper number and test fails
			`SSH`,                                                       // TRIAGE
			`should implement service.kubernetes.io/service-proxy-name`, // this is an optional test that requires SSH. sig-network
			`should allow ingress access on one named port`,             // https://bugzilla.redhat.com/show_bug.cgi?id=1711602
			`recreate nodes and ensure they function upon restart`,      // https://bugzilla.redhat.com/show_bug.cgi?id=1756428
			`\[Driver: iscsi\]`,                                         // https://bugzilla.redhat.com/show_bug.cgi?id=1711627

			"RuntimeClass should reject",

			`Services should implement service.kubernetes.io/headless`,       // requires SSH access to function, needs to be refactored
			`ClusterDns \[Feature:Example\] should create pod that uses dns`, // doesn't use bindata, not part of kube test binary
			`Simple pod should handle in-cluster config`,                     // kubectl cp doesn't work or is not preserving executable bit, we have this test already

			// TODO(node): configure the cri handler for the runtime class to make this work
			"should run a Pod requesting a RuntimeClass with a configured handler",
			"should reject a Pod requesting a RuntimeClass with conflicting node selector",
			"should run a Pod requesting a RuntimeClass with scheduling",

			// A fix is in progress: https://github.com/openshift/origin/pull/24709
			`Multi-AZ Clusters should spread the pods of a replication controller across zones`,

			`should check if kubectl diff finds a difference for Deployments`, // https://bugzilla.redhat.com/show_bug.cgi?id=1875194
		},
		// tests that may work, but we don't support them
		"[Disabled:Unsupported]": {
			`\[Driver: rbd\]`,               // OpenShift 4.x does not support Ceph RBD (use CSI instead)
			`\[Driver: ceph\]`,              // OpenShift 4.x does not support CephFS (use CSI instead)
			`\[Feature:PodSecurityPolicy\]`, // OpenShift 4.x does not enable PSP by default
		},
		// tests too slow to be part of conformance
		"[Slow]": {
			`\[sig-scalability\]`,                          // disable from the default set for now
			`should create and stop a working application`, // Inordinately slow tests

			`\[Feature:PerformanceDNS\]`, // very slow

			`validates that there exists conflict between pods with same hostPort and protocol but one using 0\.0\.0\.0 hostIP`, // 5m, really?
		},
		// tests that are known flaky
		"[Flaky]": {
			`Job should run a job to completion when tasks sometimes fail and are not locally restarted`, // seems flaky, also may require too many resources
			// TODO(node): test works when run alone, but not in the suite in CI
			`\[Feature:HPA\] Horizontal pod autoscaling \(scale resource: CPU\) \[sig-autoscaling\] ReplicationController light Should scale from 1 pod to 2 pods`,
		},
		// tests that must be run without competition
		"[Serial]": {
			`\[Disruptive\]`,
			`\[Feature:Performance\]`, // requires isolation

			`Service endpoints latency`, // requires low latency
			`Clean up pods on node`,     // schedules up to max pods per node
			`DynamicProvisioner should test that deleting a claim before the volume is provisioned deletes the volume`, // test is very disruptive to other tests

			`Multi-AZ Clusters should spread the pods of a service across zones`, // spreading is a priority, not a predicate, and if the node is temporarily full the priority will be ignored

			`Should be able to support the 1\.7 Sample API Server using the current Aggregator`, // down apiservices break other clients today https://bugzilla.redhat.com/show_bug.cgi?id=1623195

			`\[Feature:HPA\] Horizontal pod autoscaling \(scale resource: CPU\) \[sig-autoscaling\] ReplicationController light Should scale from 1 pod to 2 pods`,

			`should prevent Ingress creation if more than 1 IngressClass marked as default`, // https://bugzilla.redhat.com/show_bug.cgi?id=1822286

			`\[sig-network\] IngressClass \[Feature:Ingress\] should set default value on new IngressClass`, //https://bugzilla.redhat.com/show_bug.cgi?id=1833583
		},
		"[Skipped:azure]": {
			"Networking should provide Internet connection for containers", // Azure does not allow ICMP traffic to internet.
		},
		"[Skipped:gce]": {
			// Requires creation of a different compute instance in a different zone and is not compatible with volumeBindingMode of WaitForFirstConsumer which we use in 4.x
			`\[sig-scheduling\] Multi-AZ Cluster Volumes \[sig-storage\] should only be allowed to provision PDs in zones where nodes exist`,

			// The following tests try to ssh directly to a node. None of our nodes have external IPs
			`\[k8s.io\] \[sig-node\] crictl should be able to run crictl on the node`,
			`\[sig-storage\] Flexvolumes should be mountable`,
			`\[sig-storage\] Detaching volumes should not work when mount is in progress`,

			// We are using openshift-sdn to conceal metadata
			`\[sig-auth\] Metadata Concealment should run a check-metadata-concealment job to completion`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1740959
			`\[sig-api-machinery\] AdmissionWebhook should be able to deny pod and configmap creation`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1745720
			`\[sig-storage\] CSI Volumes \[Driver: pd.csi.storage.gke.io\]\[Serial\]`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1749882
			`\[sig-storage\] CSI Volumes CSI Topology test using GCE PD driver \[Serial\]`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1751367
			`gce-localssd-scsi-fs`,

			// https://bugzilla.redhat.com/show_bug.cgi?id=1750851
			// should be serial if/when it's re-enabled
			`\[HPA\] Horizontal pod autoscaling \(scale resource: Custom Metrics from Stackdriver\)`,
		},
		"[sig-node]": {
			`\[NodeConformance\]`,
			`NodeLease`,
			`lease API`,
			`\[NodeFeature`,
			`\[NodeAlphaFeature`,
			`Probing container`,
			`Security Context When creating a`,
			`Downward API should create a pod that prints his name and namespace`,
			`Liveness liveness pods should be automatically restarted`,
			`Secret should create a pod that reads a secret`,
			`Pods should delete a collection of pods`,
		},
		"[sig-cluster-lifecycle]": {
			`Feature:ClusterAutoscalerScalability`,
			`recreate nodes and ensure they function`,
		},
		"[sig-arch]": {
			// not run, assigned to arch as catch-all
			`\[Feature:GKELocalSSD\]`,
			`\[Feature:GKENodePool\]`,
		},
	}

	// labelExcludes temporarily block tests out of a specific suite
	LabelExcludes = map[string][]string{}

	ExcludedTests = []string{
		`\[Disabled:`,
		`\[Disruptive\]`,
		`\[Skipped\]`,
		`\[Slow\]`,
		`\[Flaky\]`,
		`\[Local\]`,
	}
)
<|endoftext|>


<commit_before>package components

import (
	"strings"

	"github.com/gizak/termui"
)

type Chat struct {
	List *termui.List
}

func CreateChat(inputHeight int) *Chat {
	chat := &Chat{
		List: termui.NewList(),
	}

	chat.List.Height = termui.TermHeight() - inputHeight
	chat.List.Overflow = "wrap"
	chat.LoadMessages()

	return chat
}

// Buffer implements interface termui.Bufferer
func (c *Chat) Buffer() termui.Buffer {
	// Build cells, after every item put a newline
	cells := termui.DefaultTxBuilder.Build(
		strings.Join(c.List.Items, "\n"),
		c.List.ItemFgColor, c.List.ItemBgColor,
	)

	type Line struct {
		cells []termui.Cell
	}

	// Uncover how many lines there are in total for all items
	lines := []Line{}
	line := Line{}

	x := 0
	for _, cell := range cells {

		if cell.Ch == '\n' {
			lines = append(lines, line)
			line = Line{}
			x = 0
			continue
		}

		if x+cell.Width() > c.List.InnerBounds().Dx() {
			lines = append(lines, line)
			line = Line{}
			x = 0
		}

		line.cells = append(line.cells, cell)
		x++
	}

	// We will print lines bottom up
	buf := c.List.Buffer()
	linesHeight := len(lines)

	windowMinY := c.List.InnerBounds().Min.Y
	windowMaxY := c.List.InnerBounds().Max.Y

	currentY := windowMaxY - 1
	for i := linesHeight - 1; i >= 0; i-- {
		if currentY <= windowMinY {
			break
		}

		x := c.List.InnerBounds().Min.X
		for _, cell := range lines[i].cells {
			buf.Set(x, currentY, cell)
			x += cell.Width()
		}

		currentY--
	}

	return buf
}

// GetHeight implements interface termui.GridBufferer
func (c *Chat) GetHeight() int {
	return c.List.Block.GetHeight()
}

// SetWidth implements interface termui.GridBufferer
func (c *Chat) SetWidth(w int) {
	c.List.SetWidth(w)
}

// SetX implements interface termui.GridBufferer
func (c *Chat) SetX(x int) {
	c.List.SetX(x)
}

// SetY implements interface termui.GridBufferer
func (c *Chat) SetY(y int) {
	c.List.SetY(y)
}

func (c *Chat) LoadMessages() {
	messages := []string{
		"[jp] hello world",
		"[erroneousboat] foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar",
	}

	for _, message := range messages {
		c.AddMessages(message)
	}
}

func (c *Chat) AddMessages(message string) {
	c.List.Items = append(c.List.Items, message)
}

func (c *Chat) ScrollUp() {
}

func (c *Chat) ScrollDown() {}
<commit_msg>Lay down foundation for scrollable list<commit_after>package components

import (
	"strings"

	"github.com/gizak/termui"
)

type Chat struct {
	List *termui.List
}

func CreateChat(inputHeight int) *Chat {
	chat := &Chat{
		List: termui.NewList(),
	}

	chat.List.Height = termui.TermHeight() - inputHeight
	chat.List.Overflow = "wrap"
	chat.LoadMessages()

	return chat
}

// Buffer implements interface termui.Bufferer
func (c *Chat) Buffer() termui.Buffer {
	// Build cells, after every item put a newline
	cells := termui.DefaultTxBuilder.Build(
		strings.Join(c.List.Items, "\n"),
		c.List.ItemFgColor, c.List.ItemBgColor,
	)

	// We will create an array of Line structs, this allows us
	// to more easily render the items in a list. We will range
	// over the cells we've created and create a Line within
	// the bounds of the Chat pane
	type Line struct {
		cells []termui.Cell
	}

	lines := []Line{}
	line := Line{}

	x := 0
	for _, cell := range cells {

		if cell.Ch == '\n' {
			lines = append(lines, line)
			line = Line{}
			x = 0
			continue
		}

		if x+cell.Width() > c.List.InnerBounds().Dx() {
			lines = append(lines, line)
			line = Line{}
			x = 0
		}

		line.cells = append(line.cells, cell)
		x++
	}
	lines = append(lines, line)

	// We will print lines bottom up, it will loop over the lines
	// backwards and for every line it'll set the cell in that line
	buf := c.List.Buffer()
	linesHeight := len(lines)
	paneMinY := c.List.InnerBounds().Min.Y
	paneMaxY := c.List.InnerBounds().Max.Y

	currentY := paneMaxY - 1
	for i := linesHeight - 1; i >= 0; i-- {
		if currentY < paneMinY {
			break
		}

		x := c.List.InnerBounds().Min.X
		for _, cell := range lines[i].cells {
			buf.Set(x, currentY, cell)
			x += cell.Width()
		}

		// When we're not at the end of the pane, fill it up
		// with empty characters
		for x < c.List.InnerBounds().Max.X {
			buf.Set(x, currentY, termui.Cell{Ch: ' '})
			x++
		}
		currentY--
	}

	// If the space above currentY is empty we need to fill
	// it up with blank lines, otherwise the List object will
	// render the items top down, and the result will mix.
	for currentY >= paneMinY {
		x := c.List.InnerBounds().Min.X
		for x < c.List.InnerBounds().Max.X {
			buf.Set(x, currentY, termui.Cell{Ch: ' '})
			x++
		}
		currentY--
	}

	return buf
}

// GetHeight implements interface termui.GridBufferer
func (c *Chat) GetHeight() int {
	return c.List.Block.GetHeight()
}

// SetWidth implements interface termui.GridBufferer
func (c *Chat) SetWidth(w int) {
	c.List.SetWidth(w)
}

// SetX implements interface termui.GridBufferer
func (c *Chat) SetX(x int) {
	c.List.SetX(x)
}

// SetY implements interface termui.GridBufferer
func (c *Chat) SetY(y int) {
	c.List.SetY(y)
}

func (c *Chat) LoadMessages() {
	messages := []string{
		"[jp] hello world",
		"[erroneousboat] foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar",
	}

	for _, message := range messages {
		c.AddMessages(message)
	}
}

func (c *Chat) AddMessages(message string) {
	c.List.Items = append(c.List.Items, message)
}

func (c *Chat) ScrollUp() {
}

func (c *Chat) ScrollDown() {}
<|endoftext|>


<commit_before><commit_msg>Bump to v0.7.2<commit_after><|endoftext|>