<commit_before>package gonvim

import (
	"strings"

	"github.com/dzhou121/ui"
)

// SpanHandler is
type SpanHandler struct {
	AreaHandler
	match         string
	matchColor    *RGBA
	matchIndex    []int
	text          string
	bg            *RGBA
	color         *RGBA
	font          *ui.Font
	paddingLeft   int
	paddingRight  int
	paddingTop    int
	paddingBottom int
}

// Draw the span
func (s *SpanHandler) Draw(a *ui.Area, dp *ui.AreaDrawParams) {
	if s.bg == nil {
		return
	}
	bg := s.bg
	p := ui.NewPath(ui.Winding)
	p.AddRectangle(dp.ClipX, dp.ClipY, dp.ClipWidth, dp.ClipHeight)
	p.End()

	bottomBg := newRGBA(14, 17, 18, 1)
	dp.Context.Fill(p, &ui.Brush{
		Type: ui.Solid,
		R:    bottomBg.R,
		G:    bottomBg.G,
		B:    bottomBg.B,
		A:    bottomBg.A,
	})
	dp.Context.Fill(p, &ui.Brush{
		Type: ui.Solid,
		R:    bg.R,
		G:    bg.G,
		B:    bg.B,
		A:    bg.A,
	})
	p.Free()

	textLayout := s.getTextLayout()
	dp.Context.Text(
		float64(s.paddingLeft),
		float64(s.paddingTop),
		textLayout,
	)
	textLayout.Free()
}

// SetColor sets the color
func (s *SpanHandler) SetColor(rgba *RGBA) {
	s.color = rgba
}

// SetBackground sets the color
func (s *SpanHandler) SetBackground(rgba *RGBA) {
	s.bg = rgba
}

// SetFont sets the font
func (s *SpanHandler) SetFont(font *ui.Font) {
	s.font = font
}

// SetText sets the text
func (s *SpanHandler) SetText(text string) {
	s.text = text
}

func (s *SpanHandler) getTextLayout() *ui.TextLayout {
	textLayout := ui.NewTextLayout(s.text, s.font, -1)
	fg := s.color
	textLayout.SetColor(0, len(s.text), fg.R, fg.G, fg.B, fg.A)
	if s.matchColor != nil {
		if len(s.matchIndex) > 0 {
			for _, i := range s.matchIndex {
				textLayout.SetColor(i, i+1, s.matchColor.R, s.matchColor.G, s.matchColor.B, s.matchColor.A)
			}
		} else if s.match != "" {
			for _, c := range s.match {
				i := strings.Index(s.text, string(c))
				if i != -1 {
					textLayout.SetColor(i, i+1, s.matchColor.R, s.matchColor.G, s.matchColor.B, s.matchColor.A)
				}
			}
		}
	}
	return textLayout
}

func (s *SpanHandler) getSize() (int, int) {
	width := editor.font.width*len(s.text) + s.paddingLeft + s.paddingRight
	height := editor.font.height + s.paddingTop + s.paddingBottom
	return width, height
}
<commit_msg>updte panic<commit_after>package gonvim

import (
	"fmt"
	"runtime/debug"
	"strings"

	"github.com/dzhou121/ui"
)

// SpanHandler is
type SpanHandler struct {
	AreaHandler
	match         string
	matchColor    *RGBA
	matchIndex    []int
	text          string
	bg            *RGBA
	color         *RGBA
	font          *ui.Font
	paddingLeft   int
	paddingRight  int
	paddingTop    int
	paddingBottom int
}

// Draw the span
func (s *SpanHandler) Draw(a *ui.Area, dp *ui.AreaDrawParams) {
	if s.bg == nil {
		return
	}
	bg := s.bg
	p := ui.NewPath(ui.Winding)
	p.AddRectangle(dp.ClipX, dp.ClipY, dp.ClipWidth, dp.ClipHeight)
	p.End()

	bottomBg := newRGBA(14, 17, 18, 1)
	dp.Context.Fill(p, &ui.Brush{
		Type: ui.Solid,
		R:    bottomBg.R,
		G:    bottomBg.G,
		B:    bottomBg.B,
		A:    bottomBg.A,
	})
	dp.Context.Fill(p, &ui.Brush{
		Type: ui.Solid,
		R:    bg.R,
		G:    bg.G,
		B:    bg.B,
		A:    bg.A,
	})
	p.Free()

	textLayout := s.getTextLayout()
	dp.Context.Text(
		float64(s.paddingLeft),
		float64(s.paddingTop),
		textLayout,
	)
	textLayout.Free()
}

// SetColor sets the color
func (s *SpanHandler) SetColor(rgba *RGBA) {
	s.color = rgba
}

// SetBackground sets the color
func (s *SpanHandler) SetBackground(rgba *RGBA) {
	s.bg = rgba
}

// SetFont sets the font
func (s *SpanHandler) SetFont(font *ui.Font) {
	s.font = font
}

// SetText sets the text
func (s *SpanHandler) SetText(text string) {
	s.text = text
}

func (s *SpanHandler) getTextLayout() *ui.TextLayout {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println(r, debug.Stack())
		}
	}()
	textLayout := ui.NewTextLayout(s.text, s.font, -1)
	fg := s.color
	textLayout.SetColor(0, len(s.text), fg.R, fg.G, fg.B, fg.A)
	if s.matchColor != nil {
		if len(s.matchIndex) > 0 {
			for _, i := range s.matchIndex {
				textLayout.SetColor(i, i+1, s.matchColor.R, s.matchColor.G, s.matchColor.B, s.matchColor.A)
			}
		} else if s.match != "" {
			for _, c := range s.match {
				i := strings.Index(s.text, string(c))
				if i != -1 {
					textLayout.SetColor(i, i+1, s.matchColor.R, s.matchColor.G, s.matchColor.B, s.matchColor.A)
				}
			}
		}
	}
	return textLayout
}

func (s *SpanHandler) getSize() (int, int) {
	width := editor.font.width*len(s.text) + s.paddingLeft + s.paddingRight
	height := editor.font.height + s.paddingTop + s.paddingBottom
	return width, height
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"time"
)

const defaultTimeout = time.Second * 30

type Step interface {
	Execute(Runtime, TaskReporter) error
	Description() string
}

type StopStep struct {
	services []string
}

func NewStopStep(config StepConfig) Step {
	return &StopStep{
		services: config.Stop,
	}
}

func (s *StopStep) Execute(runtime Runtime, reporter TaskReporter) error {
	return runtime.StopServices(s.services...)
}

func (s *StopStep) Description() string {
	return fmt.Sprintf("<Stop: %v>", s.services)
}

type StartStep struct {
	services []string
}

func NewStartStep(config StepConfig) Step {
	return &StartStep{
		services: config.Start,
	}
}

func (s *StartStep) Execute(runtime Runtime, reporter TaskReporter) error {
	return runtime.StartServices(s.services...)
}

func (s *StartStep) Description() string {
	return fmt.Sprintf("<Start: %v>", s.services)
}

type WaitStep struct {
	task TaskConfig
	env  TaskEnvironment
}

func NewWaitStep(task TaskConfig, env TaskEnvironment) Step {
	return &WaitStep{
		task: task,
		env:  env,
	}
}

func (s *WaitStep) Execute(runtime Runtime, reporter TaskReporter) error {
	timeout := time.After(defaultTimeout)
	for {
		if err := runtime.ExecuteTask(s.task, s.env, reporter); err == nil {
			return nil
		}
		select {
		case <-timeout:
			break
		default:
			continue
		}
	}
	return fmt.Errorf("Task never completed successfully")
}

func (s *WaitStep) Description() string {
	return fmt.Sprintf("<Wait: %s>", s.task.Name)
}

type AssertStep struct {
	task TaskConfig
	env  TaskEnvironment
}

func NewAssertStep(task TaskConfig, env TaskEnvironment) Step {
	return &AssertStep{
		task: task,
		env:  env,
	}
}

func (s *AssertStep) Execute(runtime Runtime, reporter TaskReporter) error {
	return runtime.ExecuteTask(s.task, s.env, reporter)
}

func (s *AssertStep) Description() string {
	return fmt.Sprintf("<Assert: %s>", s.task.Name)
}

type FailStep struct {
	task TaskConfig
	env  TaskEnvironment
}

func NewFailStep(task TaskConfig, env TaskEnvironment) Step {
	return &FailStep{
		task: task,
		env:  env,
	}
}

func (s *FailStep) Execute(runtime Runtime, reporter TaskReporter) error {
	if err := runtime.ExecuteTask(s.task, s.env, reporter); err == nil {
		return fmt.Errorf("Expected task to fail!")
	}
	return nil
}

func (s *FailStep) Description() string {
	return fmt.Sprintf("<Fail: %s>", s.task.Name)
}
<commit_msg>Return early when timeout gets triggered<commit_after>package main

import (
	"fmt"
	"time"
)

const defaultTimeout = time.Second * 30

type Step interface {
	Execute(Runtime, TaskReporter) error
	Description() string
}

type StopStep struct {
	services []string
}

func NewStopStep(config StepConfig) Step {
	return &StopStep{
		services: config.Stop,
	}
}

func (s *StopStep) Execute(runtime Runtime, reporter TaskReporter) error {
	return runtime.StopServices(s.services...)
}

func (s *StopStep) Description() string {
	return fmt.Sprintf("<Stop: %v>", s.services)
}

type StartStep struct {
	services []string
}

func NewStartStep(config StepConfig) Step {
	return &StartStep{
		services: config.Start,
	}
}

func (s *StartStep) Execute(runtime Runtime, reporter TaskReporter) error {
	return runtime.StartServices(s.services...)
}

func (s *StartStep) Description() string {
	return fmt.Sprintf("<Start: %v>", s.services)
}

type WaitStep struct {
	task TaskConfig
	env  TaskEnvironment
}

func NewWaitStep(task TaskConfig, env TaskEnvironment) Step {
	return &WaitStep{
		task: task,
		env:  env,
	}
}

func (s *WaitStep) Execute(runtime Runtime, reporter TaskReporter) error {
	timeout := time.After(defaultTimeout)
	for {
		if err := runtime.ExecuteTask(s.task, s.env, reporter); err == nil {
			return nil
		}
		select {
		case <-timeout:
			return fmt.Errorf("Task never completed successfully")
		default:
			continue
		}
	}
}

func (s *WaitStep) Description() string {
	return fmt.Sprintf("<Wait: %s>", s.task.Name)
}

type AssertStep struct {
	task TaskConfig
	env  TaskEnvironment
}

func NewAssertStep(task TaskConfig, env TaskEnvironment) Step {
	return &AssertStep{
		task: task,
		env:  env,
	}
}

func (s *AssertStep) Execute(runtime Runtime, reporter TaskReporter) error {
	return runtime.ExecuteTask(s.task, s.env, reporter)
}

func (s *AssertStep) Description() string {
	return fmt.Sprintf("<Assert: %s>", s.task.Name)
}

type FailStep struct {
	task TaskConfig
	env  TaskEnvironment
}

func NewFailStep(task TaskConfig, env TaskEnvironment) Step {
	return &FailStep{
		task: task,
		env:  env,
	}
}

func (s *FailStep) Execute(runtime Runtime, reporter TaskReporter) error {
	if err := runtime.ExecuteTask(s.task, s.env, reporter); err == nil {
		return fmt.Errorf("Expected task to fail!")
	}
	return nil
}

func (s *FailStep) Description() string {
	return fmt.Sprintf("<Fail: %s>", s.task.Name)
}
<|endoftext|>


<commit_before>package main

import (
	"net/http"

	"github.com/Felamande/filesync/syncer"
)

func main() {
	syncer.New().Run()
	http.ListenAndServe(":8070", nil)
}<commit_msg>Test http server powered by martini<commit_after>package main

import (
	"net/http"

	"github.com/Felamande/filesync/log"
	"github.com/go-martini/martini"

	"github.com/Felamande/filesync/syncer"
)

func main() {
	s := syncer.New()
	m := martini.Classic()
	l := log.NewFileLogger("./.log/http.log")
	m.Map(s)
	m.Map(l)
	m.Post("/new", NewPair)
	m.Get("/new", HelloNewPair)
	go s.Run()
	http.ListenAndServe(":20000", m)

}

func NewPair(logger *log.FileLogger, s *syncer.Syncer, w http.ResponseWriter, r *http.Request) int {
	r.ParseForm()
	_, lExist := r.Form["left"]
	_, rExist := r.Form["right"]

	if !lExist || !rExist {
		return 400

	}
	return 200

}

func HelloNewPair() string {
	return "Hello"
}
<|endoftext|>


<commit_before>package main
import "fmt"
import "strings"
func main(){
// your code goes here
var st string
st = "arch=b64"
take := strings.ContainsRune(st, int32("arch"))
fmt.Println(take)
}<commit_msg>Removed test.go<commit_after><|endoftext|>


<commit_before>// Copyright 2015 Bobby Powers. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package tmux

import (
	"bytes"
	"encoding/json"
	"fmt"
	"os/exec"
)

var NotFound = fmt.Errorf("object not found")

type Session struct {
	Name     string
	NWindows int
	Created  string
	Width    int
	Height   int
}

type Window struct {
	Index       int
	Name        string
	SessionName string
	NPanes      int
	Width       int
	Height      int
	Active      bool
}

func execTmux(args ...string) ([]byte, error) {
	cmd := exec.Command("tmux", args...)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return nil, fmt.Errorf("Run: %s", err)
	}
	return out.Bytes(), nil
}

func ListSessions() ([]Session, error) {
	out, err := Command("list-sessions", "-F",
		`{"Name":"#{session_name}","NWindow":#{session_windows},`+
			`"Created":"#{session_created_string}",`+
			`"Width":#{session_width},"Height":#{session_height}}`)
	if err != nil {
		return nil, fmt.Errorf("Command: %s", err)
	}
	bufs := bytes.Split(out, []byte{'\n'})
	sessions := make([]Session, len(bufs))
	for i, buf := range bufs {
		err := json.Unmarshal(buf, &sessions[i])
		if err != nil {
			return nil, fmt.Errorf("Unmarshal(%s): %s", string(buf), err)
		}
	}
	return sessions, nil
}

func GetSession(name string) (Session, error) {
	sessions, err := ListSessions()
	if err != nil {
		return Session{}, err
	}
	for _, s := range sessions {
		if s.Name == name {
			return s, nil
		}
	}
	return Session{}, NotFound
}

func ListWindows() ([]Window, error) {
	out, err := Command("list-windows", "-a", "-F",
		`{"Index":#{window_index},"Name":"#{window_name}",`+
			`"SessionName":"#{session_name}",`+
			`"Active":#{?window_active,true,false},`+
			`"NPanes":#{window_panes},"Width":#{window_width},`+
			`"Height":#{window_height}}`)
	if err != nil {
		return nil, fmt.Errorf("Command: %s", err)
	}
	windowBufs := bytes.Split(out, []byte{'\n'})
	windows := make([]Window, len(windowBufs))
	for i, buf := range windowBufs {
		err := json.Unmarshal(buf, &windows[i])
		if err != nil {
			return nil, fmt.Errorf("Unmarshal: %s", err)
		}
	}
	return windows, nil
}

func GetWindow(name string) (Window, error) {
	windows, err := ListWindows()
	if err != nil {
		return Window{}, err
	}
	for _, s := range windows {
		if s.Name == name {
			return s, nil
		}
	}
	return Window{}, NotFound
}

func NewSession(sessionName, windowName string, args ...string) (Session, error) {
	cmdArgs := make([]string, 0, 12)
	cmdArgs = append(cmdArgs, "new-session", "-d", "-s", sessionName)
	if windowName != "" {
		cmdArgs = append(cmdArgs, "-n", windowName)
	}
	cmdArgs = append(cmdArgs, args...)
	out, err := Command(cmdArgs...)
	if err != nil {
		return Session{}, fmt.Errorf("Command(new-session): %s", err)
	}
	fmt.Printf("out: `%s`\n", out)
	return GetSession(sessionName)
}

func NewWindow(target, windowName string, args ...string) (Window, error) {
	return Window{}, nil
}

func ResizePane(target string) error {
	return nil
}
<commit_msg>a few more commands<commit_after>// Copyright 2015 Bobby Powers. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package tmux

import (
	"bytes"
	"encoding/json"
	"fmt"
	"os/exec"
)

var NotFound = fmt.Errorf("object not found")

type Session struct {
	Name     string
	NWindows int
	Created  string
	Width    int
	Height   int
}

type Window struct {
	Index       int
	Name        string
	SessionName string
	NPanes      int
	Width       int
	Height      int
	Active      bool
}

func execTmux(args ...string) ([]byte, error) {
	cmd := exec.Command("tmux", args...)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return nil, fmt.Errorf("Run: %s", err)
	}
	return out.Bytes(), nil
}

func StartServer() error {
	_, err := execTmux("start-server")
	return err
}

func ListSessions() ([]Session, error) {
	out, err := Command("list-sessions", "-F",
		`{"Name":"#{session_name}","NWindow":#{session_windows},`+
			`"Created":"#{session_created_string}",`+
			`"Width":#{session_width},"Height":#{session_height}}`)
	if err != nil {
		return nil, fmt.Errorf("Command: %s", err)
	}
	bufs := bytes.Split(out, []byte{'\n'})
	sessions := make([]Session, len(bufs))
	for i, buf := range bufs {
		err := json.Unmarshal(buf, &sessions[i])
		if err != nil {
			return nil, fmt.Errorf("Unmarshal(%s): %s", string(buf), err)
		}
	}
	return sessions, nil
}

func GetSession(name string) (Session, error) {
	sessions, err := ListSessions()
	if err != nil {
		return Session{}, err
	}
	for _, s := range sessions {
		if s.Name == name {
			return s, nil
		}
	}
	return Session{}, NotFound
}

func ListWindows() ([]Window, error) {
	out, err := Command("list-windows", "-a", "-F",
		`{"Index":#{window_index},"Name":"#{window_name}",`+
			`"SessionName":"#{session_name}",`+
			`"Active":#{?window_active,true,false},`+
			`"NPanes":#{window_panes},"Width":#{window_width},`+
			`"Height":#{window_height}}`)
	if err != nil {
		return nil, fmt.Errorf("Command: %s", err)
	}
	windowBufs := bytes.Split(out, []byte{'\n'})
	windows := make([]Window, len(windowBufs))
	for i, buf := range windowBufs {
		err := json.Unmarshal(buf, &windows[i])
		if err != nil {
			return nil, fmt.Errorf("Unmarshal: %s", err)
		}
	}
	return windows, nil
}

func GetWindow(name string) (Window, error) {
	windows, err := ListWindows()
	if err != nil {
		return Window{}, err
	}
	for _, s := range windows {
		if s.Name == name {
			return s, nil
		}
	}
	return Window{}, NotFound
}

func NewSession(sessionName, windowName string, args ...string) (Session, error) {
	cmdArgs := make([]string, 0, 16)
	cmdArgs = append(cmdArgs, "new-session", "-d", "-s", sessionName)
	if windowName != "" {
		cmdArgs = append(cmdArgs, "-n", windowName)
	}
	cmdArgs = append(cmdArgs, args...)
	out, err := Command(cmdArgs...)
	if err != nil {
		return Session{}, fmt.Errorf("Command(new-session): %s", err)
	}
	fmt.Printf("out: `%s`\n", out)
	return GetSession(sessionName)
}

func NewWindow(target, windowName string, args ...string) (Window, error) {
	cmdArgs := make([]string, 0, 16)
	cmdArgs = append(cmdArgs, "new-window", "-a", "-t", target)
	if windowName != "" {
		cmdArgs = append(cmdArgs, "-n", windowName)
	}
	cmdArgs = append(cmdArgs, args...)
	out, err := Command(cmdArgs...)
	if err != nil {
		return Window{}, fmt.Errorf("Command(new-window): %s", err)
	}
	fmt.Printf("out2: `%s`\n", out)
	return GetWindow(windowName)
}

func SplitWindow(target string, args ...string) error {
	cmdArgs := make([]string, 0, 3+len(args))
	cmdArgs = append(cmdArgs, "split-window", "-t", target)
	cmdArgs = append(cmdArgs, args...)
	_, err := Command(cmdArgs...)
	return err
}

func ResizePane(target string, args ...string) error {
	cmdArgs := make([]string, 0, 3+len(args))
	cmdArgs = append(cmdArgs, "resize-pane", "-t", target)
	cmdArgs = append(cmdArgs, args...)
	_, err := Command(cmdArgs...)
	return err
}

func SelectPane(target string) error {
	_, err := Command("select-pane", "-t", target)
	return err
}
<|endoftext|>


<commit_before>package yalzo

import (
	"io"
	"strconv"
)

type TodoList struct {
	todos  []Todo
	archs  []Todo
	labels []string
	reader io.Reader
}

type Todo struct {
	label      string
	title      string
	isArchived bool
	no         int
}

type Tab int

const (
	TODO Tab = iota
	ARCHIVE
)

func (t Tab) String() string {
	switch t {
	case TODO:
		return "Todo"
	case ARCHIVE:
		return "Archive"
	}
	return "Unknown"
}

func NewTodoList(r io.Reader, ls []string) *TodoList {
	l, as, err := ReadCSV(r)
	if err != nil {
		panic(err)
	}

	return &TodoList{
		todos:  l,
		archs:  as,
		labels: ls,
		reader: r,
	}
}

func (tl *TodoList) GetList(width int, tab Tab) []string {
	lines := make([]string, 0, 100)
	lists := tl.getListInTab(tab)
	for i := 0; i < len(lists); i++ {
		lines = append(lines, lists[i].tolimitStr(width))
	}
	return lines
}

func (tl *TodoList) GetLabels() []string {
	for i := 0; i < len(tl.todos); i++ {
		label := tl.todos[i].label
		if !tl.existLabel(label) && label != "" {
			tl.labels = append(tl.labels, label)
		}
	}

	for i := 0; i < len(tl.archs); i++ {
		label := tl.archs[i].label
		if !tl.existLabel(label) && label != "" {
			tl.labels = append(tl.labels, label)
		}
	}

	return tl.labels
}

func (tl *TodoList) ChangeTitle(i int, t string, tab Tab) {
	switch tab {
	case TODO:
		(*tl).todos[i].title = t
	case ARCHIVE:
		(*tl).archs[i].title = t
	}
}

func (tl *TodoList) ChangeLabelName(i int, l string, tab Tab) {
	switch tab {
	case TODO:
		(*tl).todos[i].label = l
	case ARCHIVE:
		(*tl).archs[i].label = l
	}
}

func (tl *TodoList) Delete(n int) {
	for i := n; i < len((*tl).todos); i++ {
		(*tl).todos[i].setNumber(i)
	}
	tl.todos = append(tl.todos[:n], tl.todos[n+1:]...)
}

func (tl *TodoList) AddTodo(t string) {
	tl.todos = append(tl.todos, Todo{
		no:    len(tl.todos),
		label: "",
		title: t,
	})
}

func (tl *TodoList) MoveArchive(n int) {
	length := len(tl.todos)
	tl.todos[n].isArchived = true
	tl.todos[n].setNumber(length)
	tl.archs = append(tl.archs, tl.todos[n])
	for i := n + 1; i < len(tl.todos); i++ {
		tl.todos[i].setNumber(i - 1)
	}
	tl.todos = append(tl.todos[:n], tl.todos[n+1:]...)
}

func (tl *TodoList) MoveTodo(n int) {
	length := len(tl.todos)
	tl.archs[n].isArchived = false
	tl.archs[n].setNumber(length)
	tl.todos = append(tl.todos, tl.archs[n])
	for i := n + 1; i < length; i++ {
		tl.todos[i].setNumber(i - 1)
	}
	tl.archs = append(tl.archs[:n], tl.archs[n+1:]...)
}

func (tl *TodoList) Exchange(i1 int, i2 int) {
	(*tl).todos[i2].setNumber(i1 + 1)
	(*tl).todos[i1].setNumber(i2 + 1)

	(*tl).todos[i2], (*tl).todos[i1] = (*tl).todos[i1], (*tl).todos[i2]
}

func (t *Todo) setNumber(n int) {
	(*t).no = n
}

func (tl *TodoList) existLabel(l string) bool {
	for i := 0; i < len(tl.labels); i++ {
		if tl.labels[i] == l {
			return true
		}
	}
	return false
}

func (tl *TodoList) getListInTab(tab Tab) []Todo {
	switch tab {
	case ARCHIVE:
		return tl.archs
	case TODO:
		return tl.todos
	}
	return []Todo{}
}

func (t *Todo) tolimitStr(limit int) string {
	str := strconv.Itoa(t.no) + " [ " + t.label + " ] " + t.title
	length := len(str)
	if length > limit {
		return str[:limit]
	} else {
		return str
	}
}
<commit_msg>ナンバリングのバグ修正<commit_after>package yalzo

import (
	"io"
	"strconv"
)

type TodoList struct {
	todos  []Todo
	archs  []Todo
	labels []string
	reader io.Reader
}

type Todo struct {
	label      string
	title      string
	isArchived bool
	no         int
}

type Tab int

const (
	TODO Tab = iota
	ARCHIVE
)

func (t Tab) String() string {
	switch t {
	case TODO:
		return "Todo"
	case ARCHIVE:
		return "Archive"
	}
	return "Unknown"
}

func NewTodoList(r io.Reader, ls []string) *TodoList {
	l, as, err := ReadCSV(r)
	if err != nil {
		panic(err)
	}

	return &TodoList{
		todos:  l,
		archs:  as,
		labels: ls,
		reader: r,
	}
}

func (tl *TodoList) GetList(width int, tab Tab) []string {
	lines := make([]string, 0, 100)
	lists := tl.getListInTab(tab)
	for i := 0; i < len(lists); i++ {
		lines = append(lines, lists[i].tolimitStr(width))
	}
	return lines
}

func (tl *TodoList) GetLabels() []string {
	for i := 0; i < len(tl.todos); i++ {
		label := tl.todos[i].label
		if !tl.existLabel(label) && label != "" {
			tl.labels = append(tl.labels, label)
		}
	}

	for i := 0; i < len(tl.archs); i++ {
		label := tl.archs[i].label
		if !tl.existLabel(label) && label != "" {
			tl.labels = append(tl.labels, label)
		}
	}

	return tl.labels
}

func (tl *TodoList) ChangeTitle(i int, t string, tab Tab) {
	switch tab {
	case TODO:
		(*tl).todos[i].title = t
	case ARCHIVE:
		(*tl).archs[i].title = t
	}
}

func (tl *TodoList) ChangeLabelName(i int, l string, tab Tab) {
	switch tab {
	case TODO:
		(*tl).todos[i].label = l
	case ARCHIVE:
		(*tl).archs[i].label = l
	}
}

func (tl *TodoList) Delete(n int) {
	for i := n; i < len((*tl).todos); i++ {
		(*tl).todos[i].setNumber(i)
	}
	tl.todos = append(tl.todos[:n], tl.todos[n+1:]...)
}

func (tl *TodoList) AddTodo(t string) {
	tl.todos = append(tl.todos, Todo{
		no:    len(tl.todos) + 1,
		label: "",
		title: t,
	})
}

func (tl *TodoList) MoveArchive(n int) {
	length := len(tl.todos)
	tl.todos[n].isArchived = true
	tl.todos[n].setNumber(length)
	tl.archs = append(tl.archs, tl.todos[n])
	for i := n + 1; i < len(tl.todos); i++ {
		tl.todos[i].setNumber(i - 1)
	}
	tl.todos = append(tl.todos[:n], tl.todos[n+1:]...)
}

func (tl *TodoList) MoveTodo(n int) {
	length := len(tl.todos)
	tl.archs[n].isArchived = false
	tl.archs[n].setNumber(length)
	tl.todos = append(tl.todos, tl.archs[n])
	for i := n + 1; i < length; i++ {
		tl.todos[i].setNumber(i - 1)
	}
	tl.archs = append(tl.archs[:n], tl.archs[n+1:]...)
}

func (tl *TodoList) Exchange(i1 int, i2 int) {
	(*tl).todos[i2].setNumber(i1 + 1)
	(*tl).todos[i1].setNumber(i2 + 1)

	(*tl).todos[i2], (*tl).todos[i1] = (*tl).todos[i1], (*tl).todos[i2]
}

func (t *Todo) setNumber(n int) {
	(*t).no = n
}

func (tl *TodoList) existLabel(l string) bool {
	for i := 0; i < len(tl.labels); i++ {
		if tl.labels[i] == l {
			return true
		}
	}
	return false
}

func (tl *TodoList) getListInTab(tab Tab) []Todo {
	switch tab {
	case ARCHIVE:
		return tl.archs
	case TODO:
		return tl.todos
	}
	return []Todo{}
}

func (t *Todo) tolimitStr(limit int) string {
	str := strconv.Itoa(t.no) + " [ " + t.label + " ] " + t.title
	length := len(str)
	if length > limit {
		return str[:limit]
	} else {
		return str
	}
}
<|endoftext|>


<commit_before>package gedcom

import (
	"io/ioutil"
	"strconv"
	"strings"
)

// Tree contains a node structure of a GEDCOM file.
type Tree struct {
	Nodes    []*Node
	Families []*Family
}

// ParseFromFile loads a file into memory and parses it to a Tree.
func ParseFromFile(file string) (*Tree, error) {
	bytes, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	str := string(bytes)
	str = strings.Replace(str, "\r\n", "\n", -1)
	str = strings.TrimSpace(str)

	return Parse(strings.Split(str, "\n"))
}

// Parse takes a slice of GEDCOM lines and converts it to a Node structure in a
// Tree.
func Parse(lines []string) (*Tree, error) {
	t := &Tree{}
	var nodes []*Node

	// Convert every line to a node
	for _, line := range lines {
		parts := strings.Split(line, " ")
		n := &Node{}
		var err error
		n.Depth, err = strconv.Atoi(parts[0])
		if err != nil {
			return nil, err
		}

		n.Attribute = strings.TrimSpace(parts[1])
		n.Data = strings.TrimSpace(strings.Join(parts[2:], " "))

		nodes = append(nodes, n)
	}

	// Temporary root node that is changed throughout loop
	var root *Node

	// Loop through every node and assign parent and children nodes
	for index, node := range nodes {
		// If index is 0 we have a new root element
		if node.Depth == 0 {
			t.Nodes = append(t.Nodes, node)
			root = node
			continue
		}

		// If depth is 1, the root element is the parent of this node
		if node.Depth == 1 {
			node.Parent = root
			root.Children = append(root.Children, node)
			continue
		}

		// If depth is > 1, the parent element of this node is a node that we
		// have already processed.
		if node.Depth > 1 {
			for i := index - 1; i > 0; i-- {
				if nodes[i].Depth == node.Depth {
					continue
				}

				if nodes[i].Depth == node.Depth-1 {
					node.Parent = nodes[i]
					nodes[i].Children = append(node.Parent.Children, node)
					break
				}
			}

			continue
		}
	}

	return t, nil
}

func (t *Tree) TraverseFamilies() error {
	var individuals map[string]*Node = make(map[string]*Node)
	var families map[string]*Node = make(map[string]*Node)

	for _, node := range t.Nodes {
		switch node.Data {
		case "INDI":
			individuals[node.Attribute] = node
		case "FAM":
			families[node.Attribute] = node
		}
	}

	for _, family := range families {
		f := &Family{}

		for _, node := range family.Children {
			individual := individuals[node.Data]

			switch node.Attribute {
			case "HUSB":
				f.Father = individual
			case "WIFE":
				f.Mother = individual
			case "CHIL":
				f.Children = append(f.Children, individual)
			}
		}

		t.Families = append(t.Families, f)
	}

	return nil
}
<commit_msg>Use a slice instead of a map for families to keep them in order.<commit_after>package gedcom

import (
	"io/ioutil"
	"strconv"
	"strings"
)

// Tree contains a node structure of a GEDCOM file.
type Tree struct {
	Nodes    []*Node
	Families []*Family
}

// ParseFromFile loads a file into memory and parses it to a Tree.
func ParseFromFile(file string) (*Tree, error) {
	bytes, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	str := string(bytes)
	str = strings.Replace(str, "\r\n", "\n", -1)
	str = strings.TrimSpace(str)

	return Parse(strings.Split(str, "\n"))
}

// Parse takes a slice of GEDCOM lines and converts it to a Node structure in a
// Tree.
func Parse(lines []string) (*Tree, error) {
	t := &Tree{}
	var nodes []*Node

	// Convert every line to a node
	for _, line := range lines {
		parts := strings.Split(line, " ")
		n := &Node{}
		var err error
		n.Depth, err = strconv.Atoi(parts[0])
		if err != nil {
			return nil, err
		}

		n.Attribute = strings.TrimSpace(parts[1])
		n.Data = strings.TrimSpace(strings.Join(parts[2:], " "))

		nodes = append(nodes, n)
	}

	// Temporary root node that is changed throughout loop
	var root *Node

	// Loop through every node and assign parent and children nodes
	for index, node := range nodes {
		// If index is 0 we have a new root element
		if node.Depth == 0 {
			t.Nodes = append(t.Nodes, node)
			root = node
			continue
		}

		// If depth is 1, the root element is the parent of this node
		if node.Depth == 1 {
			node.Parent = root
			root.Children = append(root.Children, node)
			continue
		}

		// If depth is > 1, the parent element of this node is a node that we
		// have already processed.
		if node.Depth > 1 {
			for i := index - 1; i > 0; i-- {
				if nodes[i].Depth == node.Depth {
					continue
				}

				if nodes[i].Depth == node.Depth-1 {
					node.Parent = nodes[i]
					nodes[i].Children = append(node.Parent.Children, node)
					break
				}
			}

			continue
		}
	}

	return t, nil
}

func (t *Tree) TraverseFamilies() error {
	var individuals map[string]*Node = make(map[string]*Node)
	var families []*Node

	for _, node := range t.Nodes {
		switch node.Data {
		case "INDI":
			individuals[node.Attribute] = node
		case "FAM":
			families = append(families, node)
		}
	}

	for _, family := range families {

		f := &Family{}

		for _, node := range family.Children {
			individual := individuals[node.Data]

			switch node.Attribute {
			case "HUSB":
				f.Father = individual
			case "WIFE":
				f.Mother = individual
			case "CHIL":
				f.Children = append(f.Children, individual)
			}
		}

		t.Families = append(t.Families, f)
	}

	return nil
}
<|endoftext|>


<commit_before>// Package trie implements a simple trie data structure that maps "paths" (which
// are slices of strings) to arbitrary data values (type interface{}).
package trie

type trieChildren map[string]*Trie

type Trie struct {
	Leaf     bool
	Entry    interface{}
	Children trieChildren
}

// NewTrie makes a new empty Trie
func NewTrie() *Trie {
	return &Trie{
		Children: make(trieChildren),
	}
}

// Get retrieves an element from the Trie
//
// Takes a path (which can be empty, to denote the root element of the Trie),
// and returns the object if the path exists in the Trie, or nil and a status of
// false. Example:
//
//     if res, ok := trie.Get([]string{"foo", "bar"}), ok {
//       fmt.Println("Value at /foo/bar was", res)
//     }
func (t *Trie) Get(path []string) (entry interface{}, ok bool) {
	if len(path) == 0 {
		return t.getentry()
	}

	key := path[0]
	newpath := path[1:]

	res, ok := t.Children[key]
	if !ok {
		// Path doesn't exist: shortcut return value
		return nil, false
	}

	return res.Get(newpath)
}

// GetLongestPrefix retrieves an element from the Trie
//
// Takes a path (which can be empty, to denote the root element of the Trie).
// If a matching object exists, it is returned. Otherwise the object with the
// longest matching prefix is returned. If nothing matches at all, nil and a
// status of false is returned. Example:
//
//     if res, ok := trie.GetLongestPrefix([]string{"foo", "bar"}), ok {
//       fmt.Println("Value at /foo/bar was", res)
//     }
func (t *Trie) GetLongestPrefix(path []string) (entry interface{}, ok bool) {
	if len(path) == 0 {
		return t.getentry()
	}

	key := path[0]
	newpath := path[1:]

	res, ok := t.Children[key]
	if !ok {
		// Path doesn't exist: return this node as possible best match
		return t.getentry()
	}

	entry, ok = res.GetLongestPrefix(newpath)
	if ok {
		return entry, ok
	} else {
		// We haven't found a match yet, return this node
		return t.getentry()
	}
}

// Set creates an element in the Trie
//
// Takes a path (which can be empty, to denote the root element of the Trie),
// and an arbitrary value (interface{}) to use as the leaf data.
func (t *Trie) Set(path []string, value interface{}) {
	if len(path) == 0 {
		t.setentry(value)
		return
	}

	key := path[0]
	newpath := path[1:]

	res, ok := t.Children[key]
	if !ok {
		// Trie node that should hold entry doesn't already exist, so let's create it
		res = NewTrie()
		t.Children[key] = res
	}

	res.Set(newpath, value)
}

// Del removes an element from the Trie. Returns a boolean indicating whether an
// element was actually deleted.
func (t *Trie) Del(path []string) bool {
	if len(path) == 0 {
		return t.delentry()
	}

	key := path[0]
	newpath := path[1:]

	res, ok := t.Children[key]
	if !ok {
		return false
	}

	return res.Del(newpath)
}

func (t *Trie) setentry(value interface{}) {
	t.Leaf = true
	t.Entry = value
}

func (t *Trie) getentry() (entry interface{}, ok bool) {
	if t.Leaf {
		return t.Entry, true
	}
	return nil, false
}

func (t *Trie) delentry() (ok bool) {
	ok = t.Leaf
	t.Leaf = false
	t.Entry = nil
	return
}
<commit_msg>Update to work with go 1.0<commit_after>// Package trie implements a simple trie data structure that maps "paths" (which
// are slices of strings) to arbitrary data values (type interface{}).
package trie

type trieChildren map[string]*Trie

type Trie struct {
	Leaf     bool
	Entry    interface{}
	Children trieChildren
}

// NewTrie makes a new empty Trie
func NewTrie() *Trie {
	return &Trie{
		Children: make(trieChildren),
	}
}

// Get retrieves an element from the Trie
//
// Takes a path (which can be empty, to denote the root element of the Trie),
// and returns the object if the path exists in the Trie, or nil and a status of
// false. Example:
//
//     if res, ok := trie.Get([]string{"foo", "bar"}), ok {
//       fmt.Println("Value at /foo/bar was", res)
//     }
func (t *Trie) Get(path []string) (entry interface{}, ok bool) {
	if len(path) == 0 {
		return t.getentry()
	}

	key := path[0]
	newpath := path[1:]

	res, ok := t.Children[key]
	if !ok {
		// Path doesn't exist: shortcut return value
		return nil, false
	}

	return res.Get(newpath)
}

// GetLongestPrefix retrieves an element from the Trie
//
// Takes a path (which can be empty, to denote the root element of the Trie).
// If a matching object exists, it is returned. Otherwise the object with the
// longest matching prefix is returned. If nothing matches at all, nil and a
// status of false is returned. Example:
//
//     if res, ok := trie.GetLongestPrefix([]string{"foo", "bar"}), ok {
//       fmt.Println("Value at /foo/bar was", res)
//     }
func (t *Trie) GetLongestPrefix(path []string) (entry interface{}, ok bool) {
	if len(path) == 0 {
		return t.getentry()
	}

	key := path[0]
	newpath := path[1:]

	res, ok := t.Children[key]
	if !ok {
		// Path doesn't exist: return this node as possible best match
		return t.getentry()
	}

	entry, ok = res.GetLongestPrefix(newpath)
	if ok {
		return entry, ok
	}
	// We haven't found a match yet, return this node
	return t.getentry()
}

// Set creates an element in the Trie
//
// Takes a path (which can be empty, to denote the root element of the Trie),
// and an arbitrary value (interface{}) to use as the leaf data.
func (t *Trie) Set(path []string, value interface{}) {
	if len(path) == 0 {
		t.setentry(value)
		return
	}

	key := path[0]
	newpath := path[1:]

	res, ok := t.Children[key]
	if !ok {
		// Trie node that should hold entry doesn't already exist, so let's create it
		res = NewTrie()
		t.Children[key] = res
	}

	res.Set(newpath, value)
}

// Del removes an element from the Trie. Returns a boolean indicating whether an
// element was actually deleted.
func (t *Trie) Del(path []string) bool {
	if len(path) == 0 {
		return t.delentry()
	}

	key := path[0]
	newpath := path[1:]

	res, ok := t.Children[key]
	if !ok {
		return false
	}

	return res.Del(newpath)
}

func (t *Trie) setentry(value interface{}) {
	t.Leaf = true
	t.Entry = value
}

func (t *Trie) getentry() (entry interface{}, ok bool) {
	if t.Leaf {
		return t.Entry, true
	}
	return nil, false
}

func (t *Trie) delentry() (ok bool) {
	ok = t.Leaf
	t.Leaf = false
	t.Entry = nil
	return
}
<|endoftext|>


<commit_before>package goquery

import (
	"io"
	"net/http"
	"net/url"
	"errors"
	"code.google.com/p/go.net/html"
)

// Document represents an HTML document to be manipulated. Unlike jQuery, which
// is loaded as part of a DOM document, and thus acts upon its containing
// document, GoQuery doesn't know which HTML document to act upon. So it needs
// to be told, and that's what the Document class is for. It holds the root
// document node to manipulate, and can make selections on this document.
type Document struct {
	*Selection
	Url      *url.URL
	rootNode *html.Node
}

// NewDocumentFromNode is a Document constructor that takes a root html Node
// as argument.
func NewDocumentFromNode(root *html.Node) *Document {
	return newDocument(root, nil)
}

// NewDocument is a Document constructor that takes a string URL as argument.
// It loads the specified document, parses it, and stores the root Document
// node, ready to be manipulated.
func NewDocument(url string) (*Document, error) {
	// Load the URL
	res, e := http.Get(url)
	if e != nil {
		return nil, e
	}
	return NewDocumentFromResponse(res)
}

// NewDocumentFromReader returns a Document from a generic reader.
// It returns an error as second value if the reader's data cannot be parsed
// as html. It does *not* check if the reader is also an io.Closer, so the
// provided reader is never closed by this call, it is the responsibility
// of the caller to close it if required.
func NewDocumentFromReader(r io.Reader) (*Document, error) {
	root, e := html.Parse(r)
	if e != nil {
		return nil, e
	}
	return newDocument(root, nil), nil
}

// NewDocumentFromResponse is another Document constructor that takes an http resonse as argument.
// It loads the specified response's document, parses it, and stores the root Document
// node, ready to be manipulated. The response's body is closed on return.
func NewDocumentFromResponse(res *http.Response) (*Document, error) {
	if res == nil {
		return nil, errors.New("Response is nil pointer")
	}

	defer res.Body.Close()

	// Parse the HTML into nodes
	root, e := html.Parse(res.Body)
	if e != nil {
		return nil, e
	}

	// Create and fill the document
	return newDocument(root, res.Request.URL), nil
}

// Private constructor, make sure all fields are correctly filled.
func newDocument(root *html.Node, url *url.URL) *Document {
	// Create and fill the document
	d := &Document{nil, url, root}
	d.Selection = newSingleSelection(root, d)
	return d
}

// Selection represents a collection of nodes matching some criteria. The
// initial Selection can be created by using Document.Find, and then
// manipulated using the jQuery-like chainable syntax and methods.
type Selection struct {
	Nodes    []*html.Node
	document *Document
	prevSel  *Selection
}

// Helper constructor to create an empty selection
func newEmptySelection(doc *Document) *Selection {
	return &Selection{nil, doc, nil}
}

// Helper constructor to create a selection of only one node
func newSingleSelection(node *html.Node, doc *Document) *Selection {
	return &Selection{[]*html.Node{node}, doc, nil}
}
<commit_msg>gofmt<commit_after>package goquery

import (
	"code.google.com/p/go.net/html"
	"errors"
	"io"
	"net/http"
	"net/url"
)

// Document represents an HTML document to be manipulated. Unlike jQuery, which
// is loaded as part of a DOM document, and thus acts upon its containing
// document, GoQuery doesn't know which HTML document to act upon. So it needs
// to be told, and that's what the Document class is for. It holds the root
// document node to manipulate, and can make selections on this document.
type Document struct {
	*Selection
	Url      *url.URL
	rootNode *html.Node
}

// NewDocumentFromNode is a Document constructor that takes a root html Node
// as argument.
func NewDocumentFromNode(root *html.Node) *Document {
	return newDocument(root, nil)
}

// NewDocument is a Document constructor that takes a string URL as argument.
// It loads the specified document, parses it, and stores the root Document
// node, ready to be manipulated.
func NewDocument(url string) (*Document, error) {
	// Load the URL
	res, e := http.Get(url)
	if e != nil {
		return nil, e
	}
	return NewDocumentFromResponse(res)
}

// NewDocumentFromReader returns a Document from a generic reader.
// It returns an error as second value if the reader's data cannot be parsed
// as html. It does *not* check if the reader is also an io.Closer, so the
// provided reader is never closed by this call, it is the responsibility
// of the caller to close it if required.
func NewDocumentFromReader(r io.Reader) (*Document, error) {
	root, e := html.Parse(r)
	if e != nil {
		return nil, e
	}
	return newDocument(root, nil), nil
}

// NewDocumentFromResponse is another Document constructor that takes an http resonse as argument.
// It loads the specified response's document, parses it, and stores the root Document
// node, ready to be manipulated. The response's body is closed on return.
func NewDocumentFromResponse(res *http.Response) (*Document, error) {
	if res == nil {
		return nil, errors.New("Response is nil pointer")
	}

	defer res.Body.Close()

	// Parse the HTML into nodes
	root, e := html.Parse(res.Body)
	if e != nil {
		return nil, e
	}

	// Create and fill the document
	return newDocument(root, res.Request.URL), nil
}

// Private constructor, make sure all fields are correctly filled.
func newDocument(root *html.Node, url *url.URL) *Document {
	// Create and fill the document
	d := &Document{nil, url, root}
	d.Selection = newSingleSelection(root, d)
	return d
}

// Selection represents a collection of nodes matching some criteria. The
// initial Selection can be created by using Document.Find, and then
// manipulated using the jQuery-like chainable syntax and methods.
type Selection struct {
	Nodes    []*html.Node
	document *Document
	prevSel  *Selection
}

// Helper constructor to create an empty selection
func newEmptySelection(doc *Document) *Selection {
	return &Selection{nil, doc, nil}
}

// Helper constructor to create a selection of only one node
func newSingleSelection(node *html.Node, doc *Document) *Selection {
	return &Selection{[]*html.Node{node}, doc, nil}
}
<|endoftext|>


<commit_before>package discorddotgo

import "github.com/bwmarrin/discordgo"

type User struct {
	context      Context
	internalUser *discordgo.User
}

func (u *User) Username() string {
	return u.internalUser.Username
}

func (u *User) ID() string {
	return u.internalUser.ID
}

func (u *User) IsBot() bool {
	return u.internalUser.Bot
}

func (u *User) Avatar() string {
	return u.internalUser.Avatar
}

func (u *User) Member(g *Guild) (*Member, error) {
	m, err := u.context.intSession.GuildMember(g.ID(), u.ID())
	if err != nil {
		return nil, err
	}
	return u.context.memberFromRaw(m), nil
}

type Member struct {
	context        Context
	internalMember *discordgo.Member
}

func (m *Member) Nick() string {
	return m.internalMember.Nick
}

func (m *Member) User() *User {
	return m.context.userFromRaw(m.internalMember.User)
}
<commit_msg>New Helper methods in User and Member<commit_after>package discorddotgo

import "github.com/bwmarrin/discordgo"

type User struct {
	context      Context
	internalUser *discordgo.User
}

func (u *User) Username() string {
	return u.internalUser.Username
}

func (u *User) ID() string {
	return u.internalUser.ID
}

func (u *User) IsSelf() bool {
	return u.internalUser.ID == u.context.Self().ID()
}

func (u *User) IsBot() bool {
	return u.internalUser.Bot
}

func (u *User) Avatar() string {
	return u.internalUser.Avatar
}

func (u *User) Member(g *Guild) (*Member, error) {
	m, err := u.context.intSession.GuildMember(g.ID(), u.ID())
	if err != nil {
		return nil, err
	}
	return u.context.memberFromRaw(m), nil
}

type Member struct {
	context        Context
	internalMember *discordgo.Member
}

// Nick returns the Nickname of a member
func (m *Member) Nick() string {
	return m.internalMember.Nick
}

// SetNick sets the nickname of a user. If the user is the currently logged in
// user it will default to using @me/nick instead of the user id.
func (m *Member) SetNick(nick string) error {
	id := m.User().ID()
	if m.User().IsSelf() {
		id = "@me/nick"
	}
	guild, err := m.Guild()
	if err != nil {
		return err
	}
	return m.context.intSession.GuildMemberNickname(guild.ID(), id, nick)
}

// User returns the user of a Member
func (m *Member) User() *User {
	return m.context.userFromRaw(m.internalMember.User)
}

// Guild returns the Guild the member belongs to or an error
func (m *Member) Guild() (*Guild, error) {
	return m.context.GuildFromID(m.internalMember.GuildID)
}

// Ban will create a ban for a member or return an error
func (m *Member) Ban() error {
	return m.BanAndDeleteMessages(0)
}

// BanAndDeleteMessages will create a ban and also delete messages of the past
// days, specified by the days parameter, or return an error.
func (m *Member) BanAndDeleteMessages(days int) error {
	s := m.context.intSession
	g, err := m.Guild()
	if err != nil {
		return err
	}
	return s.GuildBanCreate(g.ID(), m.User().ID(), days)
}

func (m *Member) HasRole(r *Role) bool {
	for _, k := range m.internalMember.Roles {
		if k == r.ID() {
			return true
		}
	}
	return false
}
<|endoftext|>


<commit_before>package spotify

import (
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

// User contains the basic, publicly available information about a Spotify user.
type User struct {
	// The name displayed on the user's profile.
	// Note: Spotify currently fails to populate
	// this field when querying for a playlist.
	DisplayName string `json:"display_name"`
	// Known public external URLs for the user.
	ExternalURLs map[string]string `json:"external_urls"`
	// Information about followers of the user.
	Followers Followers `json:"followers"`
	// A link to the Web API endpoint for this user.
	Endpoint string `json:"href"`
	// The Spotify user ID for the user.
	ID string `json:"id"`
	// The user's profile image.
	Images []Image `json:"images"`
	// The Spotify URI for the user.
	URI URI `json:"uri"`
}

// PrivateUser contains additional information about a user.
// This data is private and requires user authentication.
type PrivateUser struct {
	User
	// The country of the user, as set in the user's account profile.
	// An ISO 3166-1 alpha-2 country code.  This field is only available when the
	// current user has granted acess to the ScopeUserReadPrivate scope.
	Country string `json:"country"`
	// The user's email address, as entered by the user when creating their account.
	// Note: this email is UNVERIFIED - there is no proof that it actually
	// belongs to the user.  This field is only available when the current user
	// has granted access to the ScopeUserReadEmail scope.
	Email string `json:"email"`
	// The user's Spotify subscription level: "premium", "free", etc.
	// The subscription level "open" can be considered the same as "free".
	// This field is only available when the current user has granted access to
	// the ScopeUserReadPrivate scope.
	Product string `json:"product"`
	// The user's date of birth, in the format 'YYYY-MM-DD'.  You can use
	// the DateLayout constant to convert this to a time.Time value.
	// This field is only available when the current user has granted
	// access to the ScopeUserReadBirthdate scope.
	Birthdate string `json:"birthdate"`
}

// GetUsersPublicProfile gets public profile information about a
// Spotify User.  It does not require authentication.
func (c *Client) GetUsersPublicProfile(userID ID) (*User, error) {
	spotifyURL := c.baseURL + "users/" + string(userID)

	var user User

	err := c.get(spotifyURL, &user)
	if err != nil {
		return nil, err
	}

	return &user, nil
}

// CurrentUser gets detailed profile information about the
// current user.
//
// Reading the user's email address requires that the application
// has the ScopeUserReadEmail scope.  Reading the country, display
// name, profile images, and product subscription level requires
// that the application has the ScopeUserReadPrivate scope.
//
// Warning: The email address in the response will be the address
// that was entered when the user created their spotify account.
// This email address is unverified - do not assume that Spotify has
// checked that the email address actually belongs to the user.
func (c *Client) CurrentUser() (*PrivateUser, error) {
	var result PrivateUser

	err := c.get(c.baseURL+"me", &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersTracks gets a list of songs saved in the current
// Spotify user's "Your Music" library.
func (c *Client) CurrentUsersTracks() (*SavedTrackPage, error) {
	return c.CurrentUsersTracksOpt(nil)
}

// CurrentUsersTracksOpt is like CurrentUsersTracks, but it accepts additional
// options for sorting and filtering the results.
func (c *Client) CurrentUsersTracksOpt(opt *Options) (*SavedTrackPage, error) {
	spotifyURL := c.baseURL + "me/tracks"
	if opt != nil {
		v := url.Values{}
		if opt.Country != nil {
			v.Set("country", *opt.Country)
		}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Offset != nil {
			v.Set("offset", strconv.Itoa(*opt.Offset))
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result SavedTrackPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// FollowUser adds the current user as a follower of one or more
// spotify users, identified by their Spotify IDs.
//
// Modifying the lists of artists or users the current user follows
// requires that the application has the ScopeUserFollowModify scope.
func (c *Client) FollowUser(ids ...ID) error {
	return c.modifyFollowers("user", true, ids...)
}

// FollowArtist adds the current user as a follower of one or more
// spotify artists, identified by their Spotify IDs.
//
// Modifying the lists of artists or users the current user follows
// requires that the application has the ScopeUserFollowModify scope.
func (c *Client) FollowArtist(ids ...ID) error {
	return c.modifyFollowers("artist", true, ids...)
}

// UnfollowUser removes the current user as a follower of one or more
// Spotify users.
//
// Modifying the lists of artists or users the current user follows
// requires that the application has the ScopeUserFollowModify scope.
func (c *Client) UnfollowUser(ids ...ID) error {
	return c.modifyFollowers("user", false, ids...)
}

// UnfollowArtist removes the current user as a follower of one or more
// Spotify artists.
//
// Modifying the lists of artists or users the current user follows
// requires that the application has the ScopeUserFollowModify scope.
func (c *Client) UnfollowArtist(ids ...ID) error {
	return c.modifyFollowers("artist", false, ids...)
}

// CurrentUserFollows checks to see if the current user is following
// one or more artists or other Spotify Users.  This call requires
// ScopeUserFollowRead.
//
// The t argument indicates the type of the IDs, and must be either
// "user" or "artist".
//
// The result is returned as a slice of bool values in the same order
// in which the IDs were specified.
func (c *Client) CurrentUserFollows(t string, ids ...ID) ([]bool, error) {
	if l := len(ids); l == 0 || l > 50 {
		return nil, errors.New("spotify: UserFollows supports 1 to 50 IDs")
	}
	if t != "artist" && t != "user" {
		return nil, errors.New("spotify: t must be 'artist' or 'user'")
	}
	spotifyURL := fmt.Sprintf("%sme/following/contains?type=%s&ids=%s",
		c.baseURL, t, strings.Join(toStringSlice(ids), ","))

	var result []bool

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return result, nil
}

func (c *Client) modifyFollowers(usertype string, follow bool, ids ...ID) error {
	if l := len(ids); l == 0 || l > 50 {
		return errors.New("spotify: Follow/Unfollow supports 1 to 50 IDs")
	}
	v := url.Values{}
	v.Add("type", usertype)
	v.Add("ids", strings.Join(toStringSlice(ids), ","))
	spotifyURL := c.baseURL + "me/following?" + v.Encode()
	method := "PUT"
	if !follow {
		method = "DELETE"
	}
	req, err := http.NewRequest(method, spotifyURL, nil)
	if err != nil {
		return err
	}
	err = c.execute(req, nil, http.StatusNoContent)
	if err != nil {
		return err
	}
	return nil
}

// CurrentUsersFollowedArtists gets the current user's followed artists.
// This call requires that the user has granted the ScopeUserFollowRead scope.
func (c *Client) CurrentUsersFollowedArtists() (*FullArtistCursorPage, error) {
	return c.CurrentUsersFollowedArtistsOpt(-1, "")
}

// CurrentUsersFollowedArtistsOpt is like CurrentUsersFollowedArtists,
// but it accept the optional arguments limit and after.  Limit is the
// maximum number of items to return (1 <= limit <= 50), and after is
// the last artist ID retrieved from the previous request.  If you don't
// wish to specify either of the parameters, use -1 for limit and the empty
// string for after.
func (c *Client) CurrentUsersFollowedArtistsOpt(limit int, after string) (*FullArtistCursorPage, error) {
	spotifyURL := c.baseURL + "me/following"
	v := url.Values{}
	v.Set("type", "artist")
	if limit != -1 {
		v.Set("limit", strconv.Itoa(limit))
	}
	if after != "" {
		v.Set("after", after)
	}
	if params := v.Encode(); params != "" {
		spotifyURL += "?" + params
	}

	var result struct {
		A FullArtistCursorPage `json:"artists"`
	}

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result.A, nil
}

// CurrentUsersAlbums gets a list of albums saved in the current
// Spotify user's "Your Music" library.
func (c *Client) CurrentUsersAlbums() (*SavedAlbumPage, error) {
	return c.CurrentUsersAlbumsOpt(nil)
}

// CurrentUsersAlbumsOpt is like CurrentUsersAlbums, but it accepts additional
// options for sorting and filtering the results.
func (c *Client) CurrentUsersAlbumsOpt(opt *Options) (*SavedAlbumPage, error) {
	spotifyURL := c.baseURL + "me/albums"
	if opt != nil {
		v := url.Values{}
		if opt.Country != nil {
			v.Set("market", *opt.Country)
		}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Offset != nil {
			v.Set("offset", strconv.Itoa(*opt.Offset))
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result SavedAlbumPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersPlaylists gets a list of the playlists owned or followed by
// the current spotify user.
//
// Private playlists require the ScopePlaylistReadPrivate scope.  Note that
// this scope alone will not return collaborative playlists, even though
// they are always private.  In order to retrieve collaborative playlists
// the user must authorize the ScopePlaylistReadCollaborative scope.
func (c *Client) CurrentUsersPlaylists() (*SimplePlaylistPage, error) {
	return c.CurrentUsersPlaylistsOpt(nil)
}

// CurrentUsersPlaylistsOpt is like CurrentUsersPlaylists, but it accepts
// additional options for sorting and filtering the results.
func (c *Client) CurrentUsersPlaylistsOpt(opt *Options) (*SimplePlaylistPage, error) {
	spotifyURL := c.baseURL + "me/playlists"
	if opt != nil {
		v := url.Values{}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Offset != nil {
			v.Set("offset", strconv.Itoa(*opt.Offset))
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result SimplePlaylistPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersTopArtistsOpt gets a list of the top played artists in a given time
// range of the current Spotify user. It supports up to 50 artists in a single
// call. This call requires ScopeUserTopRead.
func (c *Client) CurrentUsersTopArtistsOpt(opt *Options) (*FullArtistPage, error) {
	spotifyURL := c.baseURL + "me/top/artists"
	if opt != nil {
		v := url.Values{}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Timerange != nil {
			v.Set("time_range", *opt.Timerange+"_term")
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result FullArtistPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersTopArtists is like CurrentUsersTopArtistsOpt but with
// sensible defaults. The default limit is 20 and the default timerange
// is medium_term.
func (c *Client) CurrentUsersTopArtists() (*FullArtistPage, error) {
	return c.CurrentUsersTopArtistsOpt(nil)
}

// CurrentUsersTopTracksOpt gets a list of the top played tracks in a given time
// range of the current Spotify user. It supports up to 50 tracks in a single
// call. This call requires ScopeUserTopRead.
func (c *Client) CurrentUsersTopTracksOpt(opt *Options) (*FullTrackPage, error) {
	spotifyURL := c.baseURL + "me/top/tracks"
	if opt != nil {
		v := url.Values{}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Timerange != nil {
			v.Set("time_range", *opt.Timerange+"_term")
		}
		if opt.Offset != nil {
			v.Set("offset", strconv.Itoa(*opt.Offset))
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result FullTrackPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersTopTracks is like CurrentUsersTopTracksOpt but with
// sensible defaults. The default limit is 20 and the default timerange
// is medium_term.
func (c *Client) CurrentUsersTopTracks() (*FullTrackPage, error) {
	return c.CurrentUsersTopTracksOpt(nil)
}<commit_msg>ran go fmt on code<commit_after>package spotify

import (
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

// User contains the basic, publicly available information about a Spotify user.
type User struct {
	// The name displayed on the user's profile.
	// Note: Spotify currently fails to populate
	// this field when querying for a playlist.
	DisplayName string `json:"display_name"`
	// Known public external URLs for the user.
	ExternalURLs map[string]string `json:"external_urls"`
	// Information about followers of the user.
	Followers Followers `json:"followers"`
	// A link to the Web API endpoint for this user.
	Endpoint string `json:"href"`
	// The Spotify user ID for the user.
	ID string `json:"id"`
	// The user's profile image.
	Images []Image `json:"images"`
	// The Spotify URI for the user.
	URI URI `json:"uri"`
}

// PrivateUser contains additional information about a user.
// This data is private and requires user authentication.
type PrivateUser struct {
	User
	// The country of the user, as set in the user's account profile.
	// An ISO 3166-1 alpha-2 country code.  This field is only available when the
	// current user has granted acess to the ScopeUserReadPrivate scope.
	Country string `json:"country"`
	// The user's email address, as entered by the user when creating their account.
	// Note: this email is UNVERIFIED - there is no proof that it actually
	// belongs to the user.  This field is only available when the current user
	// has granted access to the ScopeUserReadEmail scope.
	Email string `json:"email"`
	// The user's Spotify subscription level: "premium", "free", etc.
	// The subscription level "open" can be considered the same as "free".
	// This field is only available when the current user has granted access to
	// the ScopeUserReadPrivate scope.
	Product string `json:"product"`
	// The user's date of birth, in the format 'YYYY-MM-DD'.  You can use
	// the DateLayout constant to convert this to a time.Time value.
	// This field is only available when the current user has granted
	// access to the ScopeUserReadBirthdate scope.
	Birthdate string `json:"birthdate"`
}

// GetUsersPublicProfile gets public profile information about a
// Spotify User.  It does not require authentication.
func (c *Client) GetUsersPublicProfile(userID ID) (*User, error) {
	spotifyURL := c.baseURL + "users/" + string(userID)

	var user User

	err := c.get(spotifyURL, &user)
	if err != nil {
		return nil, err
	}

	return &user, nil
}

// CurrentUser gets detailed profile information about the
// current user.
//
// Reading the user's email address requires that the application
// has the ScopeUserReadEmail scope.  Reading the country, display
// name, profile images, and product subscription level requires
// that the application has the ScopeUserReadPrivate scope.
//
// Warning: The email address in the response will be the address
// that was entered when the user created their spotify account.
// This email address is unverified - do not assume that Spotify has
// checked that the email address actually belongs to the user.
func (c *Client) CurrentUser() (*PrivateUser, error) {
	var result PrivateUser

	err := c.get(c.baseURL+"me", &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersTracks gets a list of songs saved in the current
// Spotify user's "Your Music" library.
func (c *Client) CurrentUsersTracks() (*SavedTrackPage, error) {
	return c.CurrentUsersTracksOpt(nil)
}

// CurrentUsersTracksOpt is like CurrentUsersTracks, but it accepts additional
// options for sorting and filtering the results.
func (c *Client) CurrentUsersTracksOpt(opt *Options) (*SavedTrackPage, error) {
	spotifyURL := c.baseURL + "me/tracks"
	if opt != nil {
		v := url.Values{}
		if opt.Country != nil {
			v.Set("country", *opt.Country)
		}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Offset != nil {
			v.Set("offset", strconv.Itoa(*opt.Offset))
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result SavedTrackPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// FollowUser adds the current user as a follower of one or more
// spotify users, identified by their Spotify IDs.
//
// Modifying the lists of artists or users the current user follows
// requires that the application has the ScopeUserFollowModify scope.
func (c *Client) FollowUser(ids ...ID) error {
	return c.modifyFollowers("user", true, ids...)
}

// FollowArtist adds the current user as a follower of one or more
// spotify artists, identified by their Spotify IDs.
//
// Modifying the lists of artists or users the current user follows
// requires that the application has the ScopeUserFollowModify scope.
func (c *Client) FollowArtist(ids ...ID) error {
	return c.modifyFollowers("artist", true, ids...)
}

// UnfollowUser removes the current user as a follower of one or more
// Spotify users.
//
// Modifying the lists of artists or users the current user follows
// requires that the application has the ScopeUserFollowModify scope.
func (c *Client) UnfollowUser(ids ...ID) error {
	return c.modifyFollowers("user", false, ids...)
}

// UnfollowArtist removes the current user as a follower of one or more
// Spotify artists.
//
// Modifying the lists of artists or users the current user follows
// requires that the application has the ScopeUserFollowModify scope.
func (c *Client) UnfollowArtist(ids ...ID) error {
	return c.modifyFollowers("artist", false, ids...)
}

// CurrentUserFollows checks to see if the current user is following
// one or more artists or other Spotify Users.  This call requires
// ScopeUserFollowRead.
//
// The t argument indicates the type of the IDs, and must be either
// "user" or "artist".
//
// The result is returned as a slice of bool values in the same order
// in which the IDs were specified.
func (c *Client) CurrentUserFollows(t string, ids ...ID) ([]bool, error) {
	if l := len(ids); l == 0 || l > 50 {
		return nil, errors.New("spotify: UserFollows supports 1 to 50 IDs")
	}
	if t != "artist" && t != "user" {
		return nil, errors.New("spotify: t must be 'artist' or 'user'")
	}
	spotifyURL := fmt.Sprintf("%sme/following/contains?type=%s&ids=%s",
		c.baseURL, t, strings.Join(toStringSlice(ids), ","))

	var result []bool

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return result, nil
}

func (c *Client) modifyFollowers(usertype string, follow bool, ids ...ID) error {
	if l := len(ids); l == 0 || l > 50 {
		return errors.New("spotify: Follow/Unfollow supports 1 to 50 IDs")
	}
	v := url.Values{}
	v.Add("type", usertype)
	v.Add("ids", strings.Join(toStringSlice(ids), ","))
	spotifyURL := c.baseURL + "me/following?" + v.Encode()
	method := "PUT"
	if !follow {
		method = "DELETE"
	}
	req, err := http.NewRequest(method, spotifyURL, nil)
	if err != nil {
		return err
	}
	err = c.execute(req, nil, http.StatusNoContent)
	if err != nil {
		return err
	}
	return nil
}

// CurrentUsersFollowedArtists gets the current user's followed artists.
// This call requires that the user has granted the ScopeUserFollowRead scope.
func (c *Client) CurrentUsersFollowedArtists() (*FullArtistCursorPage, error) {
	return c.CurrentUsersFollowedArtistsOpt(-1, "")
}

// CurrentUsersFollowedArtistsOpt is like CurrentUsersFollowedArtists,
// but it accept the optional arguments limit and after.  Limit is the
// maximum number of items to return (1 <= limit <= 50), and after is
// the last artist ID retrieved from the previous request.  If you don't
// wish to specify either of the parameters, use -1 for limit and the empty
// string for after.
func (c *Client) CurrentUsersFollowedArtistsOpt(limit int, after string) (*FullArtistCursorPage, error) {
	spotifyURL := c.baseURL + "me/following"
	v := url.Values{}
	v.Set("type", "artist")
	if limit != -1 {
		v.Set("limit", strconv.Itoa(limit))
	}
	if after != "" {
		v.Set("after", after)
	}
	if params := v.Encode(); params != "" {
		spotifyURL += "?" + params
	}

	var result struct {
		A FullArtistCursorPage `json:"artists"`
	}

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result.A, nil
}

// CurrentUsersAlbums gets a list of albums saved in the current
// Spotify user's "Your Music" library.
func (c *Client) CurrentUsersAlbums() (*SavedAlbumPage, error) {
	return c.CurrentUsersAlbumsOpt(nil)
}

// CurrentUsersAlbumsOpt is like CurrentUsersAlbums, but it accepts additional
// options for sorting and filtering the results.
func (c *Client) CurrentUsersAlbumsOpt(opt *Options) (*SavedAlbumPage, error) {
	spotifyURL := c.baseURL + "me/albums"
	if opt != nil {
		v := url.Values{}
		if opt.Country != nil {
			v.Set("market", *opt.Country)
		}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Offset != nil {
			v.Set("offset", strconv.Itoa(*opt.Offset))
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result SavedAlbumPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersPlaylists gets a list of the playlists owned or followed by
// the current spotify user.
//
// Private playlists require the ScopePlaylistReadPrivate scope.  Note that
// this scope alone will not return collaborative playlists, even though
// they are always private.  In order to retrieve collaborative playlists
// the user must authorize the ScopePlaylistReadCollaborative scope.
func (c *Client) CurrentUsersPlaylists() (*SimplePlaylistPage, error) {
	return c.CurrentUsersPlaylistsOpt(nil)
}

// CurrentUsersPlaylistsOpt is like CurrentUsersPlaylists, but it accepts
// additional options for sorting and filtering the results.
func (c *Client) CurrentUsersPlaylistsOpt(opt *Options) (*SimplePlaylistPage, error) {
	spotifyURL := c.baseURL + "me/playlists"
	if opt != nil {
		v := url.Values{}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Offset != nil {
			v.Set("offset", strconv.Itoa(*opt.Offset))
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result SimplePlaylistPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersTopArtistsOpt gets a list of the top played artists in a given time
// range of the current Spotify user. It supports up to 50 artists in a single
// call. This call requires ScopeUserTopRead.
func (c *Client) CurrentUsersTopArtistsOpt(opt *Options) (*FullArtistPage, error) {
	spotifyURL := c.baseURL + "me/top/artists"
	if opt != nil {
		v := url.Values{}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Timerange != nil {
			v.Set("time_range", *opt.Timerange+"_term")
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result FullArtistPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersTopArtists is like CurrentUsersTopArtistsOpt but with
// sensible defaults. The default limit is 20 and the default timerange
// is medium_term.
func (c *Client) CurrentUsersTopArtists() (*FullArtistPage, error) {
	return c.CurrentUsersTopArtistsOpt(nil)
}

// CurrentUsersTopTracksOpt gets a list of the top played tracks in a given time
// range of the current Spotify user. It supports up to 50 tracks in a single
// call. This call requires ScopeUserTopRead.
func (c *Client) CurrentUsersTopTracksOpt(opt *Options) (*FullTrackPage, error) {
	spotifyURL := c.baseURL + "me/top/tracks"
	if opt != nil {
		v := url.Values{}
		if opt.Limit != nil {
			v.Set("limit", strconv.Itoa(*opt.Limit))
		}
		if opt.Timerange != nil {
			v.Set("time_range", *opt.Timerange+"_term")
		}
		if opt.Offset != nil {
			v.Set("offset", strconv.Itoa(*opt.Offset))
		}
		if params := v.Encode(); params != "" {
			spotifyURL += "?" + params
		}
	}

	var result FullTrackPage

	err := c.get(spotifyURL, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

// CurrentUsersTopTracks is like CurrentUsersTopTracksOpt but with
// sensible defaults. The default limit is 20 and the default timerange
// is medium_term.
func (c *Client) CurrentUsersTopTracks() (*FullTrackPage, error) {
	return c.CurrentUsersTopTracksOpt(nil)
}
<|endoftext|>


<commit_before>package telebot

import (
	"encoding/json"
	"fmt"
	"strconv"

	"github.com/pkg/errors"
)

func (b *Bot) debug(err error) {
	if b.reporter != nil {
		b.reporter(errors.WithStack(err))
	}
}

func (b *Bot) deferDebug() {
	if r := recover(); r != nil {
		if err, ok := r.(error); ok {
			b.debug(err)
		} else if str, ok := r.(string); ok {
			b.debug(fmt.Errorf("%s", str))
		}
	}
}

func (b *Bot) sendText(to Recipient, text string, opt *SendOptions) (*Message, error) {
	params := map[string]string{
		"chat_id": to.Recipient(),
		"text":    text,
	}
	embedSendOptions(params, opt)

	respJSON, err := b.Raw("sendMessage", params)
	if err != nil {
		return nil, err
	}

	return extractMsgResponse(respJSON)
}

func wrapSystem(err error) error {
	return errors.Wrap(err, "system error")
}

func isUserInList(user *User, list []User) bool {
	for _, user2 := range list {
		if user.ID == user2.ID {
			return true
		}
	}

	return false
}

func extractMsgResponse(respJSON []byte) (*Message, error) {
	var resp struct {
		Ok          bool
		Result      *Message
		Description string
	}

	err := json.Unmarshal(respJSON, &resp)
	if err != nil {
		return nil, errors.Wrap(err, "bad response json")
	}

	if !resp.Ok {
		return nil, errors.Errorf("api error: %s", resp.Description)
	}

	return resp.Result, nil
}

func extractOkResponse(respJSON []byte) error {
	var resp struct {
		Ok          bool
		Description string
	}

	err := json.Unmarshal(respJSON, &resp)
	if err != nil {
		return errors.Wrap(err, "bad response json")
	}

	if !resp.Ok {
		return errors.Errorf("api error: %s", resp.Description)
	}

	return nil
}

func extractOptions(how []interface{}) *SendOptions {
	var opts *SendOptions

	for _, prop := range how {
		switch opt := prop.(type) {
		case *SendOptions:
			opts = opt.copy()

		case *ReplyMarkup:
			if opts == nil {
				opts = &SendOptions{}
			}
			opts.ReplyMarkup = opt.copy()

		case Option:
			if opts == nil {
				opts = &SendOptions{}
			}

			switch opt {
			case NoPreview:
				opts.DisableWebPagePreview = true
			case Silent:
				opts.DisableNotification = true
			case ForceReply:
				if opts.ReplyMarkup == nil {
					opts.ReplyMarkup = &ReplyMarkup{}
				}
				opts.ReplyMarkup.ForceReply = true
			case OneTimeKeyboard:
				if opts.ReplyMarkup == nil {
					opts.ReplyMarkup = &ReplyMarkup{}
				}
				opts.ReplyMarkup.OneTimeKeyboard = true
			default:
				panic("telebot: unsupported flag-option")
			}

		case ParseMode:
			if opts == nil {
				opts = &SendOptions{}
			}
			opts.ParseMode = opt

		default:
			panic("telebot: unsupported send-option")
		}
	}

	return opts
}

func embedSendOptions(params map[string]string, opt *SendOptions) {
	if opt == nil {
		return
	}

	if opt.ReplyTo != nil && opt.ReplyTo.ID != 0 {
		params["reply_to_message_id"] = strconv.Itoa(opt.ReplyTo.ID)
	}

	if opt.DisableWebPagePreview {
		params["disable_web_page_preview"] = "true"
	}

	if opt.DisableNotification {
		params["disable_notification"] = "true"
	}

	if opt.ParseMode != ModeDefault {
		params["parse_mode"] = string(opt.ParseMode)
	}

	if opt.ReplyMarkup != nil {
		keys := opt.ReplyMarkup.InlineKeyboard
		if len(keys) > 0 && len(keys[0]) > 0 {
			for i, _ := range keys {
				for j, _ := range keys[i] {
					key := &keys[i][j]
					if key.Unique != "" {
						// Format: "\f<callback_name>|<data>"
						data := key.Data
						if data == "" {
							key.Data = "\f" + key.Unique
						} else {
							key.Data = "\f" + key.Unique + "|" + data
						}
					}
				}
			}
		}

		replyMarkup, _ := json.Marshal(opt.ReplyMarkup)
		params["reply_markup"] = string(replyMarkup)
	}
}

func embedRights(p map[string]string, prv Rights) {
	jsonRepr, _ := json.Marshal(prv)
	json.Unmarshal(jsonRepr, p)
}
<commit_msg>Reporting errors correctly.<commit_after>package telebot

import (
	"encoding/json"
	"strconv"

	"github.com/pkg/errors"
)

func (b *Bot) debug(err error) {
	if b.reporter != nil {
		b.reporter(err)
	}
}

func (b *Bot) deferDebug() {
	if r := recover(); r != nil {
		if err, ok := r.(error); ok {
			b.debug(err)
		} else if str, ok := r.(string); ok {
			b.debug(errors.Errorf("%s", str))
		}
	}
}

func (b *Bot) sendText(to Recipient, text string, opt *SendOptions) (*Message, error) {
	params := map[string]string{
		"chat_id": to.Recipient(),
		"text":    text,
	}
	embedSendOptions(params, opt)

	respJSON, err := b.Raw("sendMessage", params)
	if err != nil {
		return nil, err
	}

	return extractMsgResponse(respJSON)
}

func wrapSystem(err error) error {
	return errors.Wrap(err, "system error")
}

func isUserInList(user *User, list []User) bool {
	for _, user2 := range list {
		if user.ID == user2.ID {
			return true
		}
	}

	return false
}

func extractMsgResponse(respJSON []byte) (*Message, error) {
	var resp struct {
		Ok          bool
		Result      *Message
		Description string
	}

	err := json.Unmarshal(respJSON, &resp)
	if err != nil {
		return nil, errors.Wrap(err, "bad response json")
	}

	if !resp.Ok {
		return nil, errors.Errorf("api error: %s", resp.Description)
	}

	return resp.Result, nil
}

func extractOkResponse(respJSON []byte) error {
	var resp struct {
		Ok          bool
		Description string
	}

	err := json.Unmarshal(respJSON, &resp)
	if err != nil {
		return errors.Wrap(err, "bad response json")
	}

	if !resp.Ok {
		return errors.Errorf("api error: %s", resp.Description)
	}

	return nil
}

func extractOptions(how []interface{}) *SendOptions {
	var opts *SendOptions

	for _, prop := range how {
		switch opt := prop.(type) {
		case *SendOptions:
			opts = opt.copy()

		case *ReplyMarkup:
			if opts == nil {
				opts = &SendOptions{}
			}
			opts.ReplyMarkup = opt.copy()

		case Option:
			if opts == nil {
				opts = &SendOptions{}
			}

			switch opt {
			case NoPreview:
				opts.DisableWebPagePreview = true
			case Silent:
				opts.DisableNotification = true
			case ForceReply:
				if opts.ReplyMarkup == nil {
					opts.ReplyMarkup = &ReplyMarkup{}
				}
				opts.ReplyMarkup.ForceReply = true
			case OneTimeKeyboard:
				if opts.ReplyMarkup == nil {
					opts.ReplyMarkup = &ReplyMarkup{}
				}
				opts.ReplyMarkup.OneTimeKeyboard = true
			default:
				panic("telebot: unsupported flag-option")
			}

		case ParseMode:
			if opts == nil {
				opts = &SendOptions{}
			}
			opts.ParseMode = opt

		default:
			panic("telebot: unsupported send-option")
		}
	}

	return opts
}

func embedSendOptions(params map[string]string, opt *SendOptions) {
	if opt == nil {
		return
	}

	if opt.ReplyTo != nil && opt.ReplyTo.ID != 0 {
		params["reply_to_message_id"] = strconv.Itoa(opt.ReplyTo.ID)
	}

	if opt.DisableWebPagePreview {
		params["disable_web_page_preview"] = "true"
	}

	if opt.DisableNotification {
		params["disable_notification"] = "true"
	}

	if opt.ParseMode != ModeDefault {
		params["parse_mode"] = string(opt.ParseMode)
	}

	if opt.ReplyMarkup != nil {
		keys := opt.ReplyMarkup.InlineKeyboard
		if len(keys) > 0 && len(keys[0]) > 0 {
			for i, _ := range keys {
				for j, _ := range keys[i] {
					key := &keys[i][j]
					if key.Unique != "" {
						// Format: "\f<callback_name>|<data>"
						data := key.Data
						if data == "" {
							key.Data = "\f" + key.Unique
						} else {
							key.Data = "\f" + key.Unique + "|" + data
						}
					}
				}
			}
		}

		replyMarkup, _ := json.Marshal(opt.ReplyMarkup)
		params["reply_markup"] = string(replyMarkup)
	}
}

func embedRights(p map[string]string, prv Rights) {
	jsonRepr, _ := json.Marshal(prv)
	json.Unmarshal(jsonRepr, p)
}
<|endoftext|>


<commit_before>package main

import (
	//	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"strconv"
)

func getChildren(mt *MeshTree, db *gorm.DB) ([]*MeshTree, error) {
	var mtChildren []*MeshTree
	if mt.Depth == 12 {
		return mtChildren, nil
	}
	q := getChildrenQuery(mt, false)

	log.Println("**************************", mt.Depth, q)

	db.Where(q).Find(&mtChildren)
	var count int64
	db.Model(&MeshTree{}).Where(q).Count(&count)
	log.Println(count)
	q = getChildrenQuery(mt, true)
	log.Println("******* all", q)
	db.Model(&MeshTree{}).Where(q).Count(&count)
	log.Println(count)
	return mtChildren, nil
}

func countChildren(mt *MeshTree, db *gorm.DB, allChildren bool) int64 {
	if mt.Depth == 12 {
		return 0
	}
	var count int64 = 0

	q := getChildrenQuery(mt, allChildren)
	db.Model(&MeshTree{}).Where(q).Count(&count)
	return count
}

func getLevel(level int, db *gorm.DB) ([]int64, []*MeshTree, error) {
	var mt []*MeshTree
	q := "T0 is not null"
	for i := 1; i < level+2; i++ {
		q += " AND t" + strconv.Itoa(i) + " is null"
	}
	//log.Println(q)
	db.Where(q).Find(&mt)

	var tmp []int64
	return tmp, mt, nil
}

func whichDescendents(all bool, l1, l2 string) string {
	if all {
		if l1 != "" {
			return " AND " + l1 + " IS NOT NULL"
		} else {
			return ""
		}
	} else {
		r := " AND " + l1 + " IS NOT NULL"
		if l1 != "" && l1 != T12 {
			r += " AND " + l2 + " IS NULL"
		}
		return r
	}
}

const T0 = "T0"
const T1 = "T1"
const T2 = "T2"
const T3 = "T3"
const T4 = "T4"
const T5 = "T5"
const T6 = "T6"
const T7 = "T7"
const T8 = "T8"
const T9 = "T9"
const T10 = "T10"
const T11 = "T11"
const T12 = "T12"

func getChildrenQuery(mt *MeshTree, allDescendents bool) string {
	q := ""

	//log.Println("Depth=" + strconv.Itoa(mt.Depth))

	switch mt.Depth {
	case 0:
		q = T0 + "=\"" + *mt.T0 + "\"" + whichDescendents(allDescendents, T1, T2)
	case 1:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\"" + whichDescendents(allDescendents, T2, T3)
	case 2:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\"" + whichDescendents(allDescendents, T3, T4)
	case 3:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\"" + whichDescendents(allDescendents, T4, T5)
	case 4:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\"" + whichDescendents(allDescendents, T5, T6)

	case 5:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\"" + whichDescendents(allDescendents, T6, T7)
	case 6:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\"" + whichDescendents(allDescendents, T7, T8)
	case 7:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\"" + whichDescendents(allDescendents, T8, T9)
	case 8:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\" and " + T8 + "=\"" + *mt.T8 + "\"" + whichDescendents(allDescendents, T9, T10)

	case 9:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\" and " + T8 + "=\"" + *mt.T8 + "\" and T9=\"" + *mt.T9 + "\"" + whichDescendents(allDescendents, T10, T11)

	case 10:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\" and " + T8 + "=\"" + *mt.T8 + "\" and T9=\"" + *mt.T9 + "\" and T10=\"" + *mt.T10 + "\"" + whichDescendents(allDescendents, T11, T12)

	case 11:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\" and " + T8 + "=\"" + *mt.T8 + "\" and T9=\"" + *mt.T9 + "\" and T10=\"" + *mt.T10 + "\" and T11=\"" + *mt.T11 + "\"" + whichDescendents(allDescendents, T12, "")

	}

	return q

}
func findLabel(t *MeshTree) string {
	if t.T12 != nil {
		return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8 + "." + *t.T9 + "." + *t.T10 + "." + *t.T11 + "." + *t.T12
	} else {
		if t.T11 != nil {
			return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8 + "." + *t.T9 + "." + *t.T10 + "." + *t.T11
		} else {
			if t.T10 != nil {
				return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8 + "." + *t.T9 + "." + *t.T10
			} else {
				if t.T9 != nil {
					return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8 + "." + *t.T9
				} else {
					if t.T8 != nil {
						return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8
					} else {
						if t.T7 != nil {
							return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7
						} else {
							if t.T6 != nil {
								return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6
							} else {
								if t.T5 != nil {
									return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5
								} else {
									if t.T4 != nil {
										return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4
									} else {
										if t.T3 != nil {
											return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3
										} else {
											if t.T2 != nil {
												return *t.T0 + "." + *t.T1 + "." + *t.T2
											} else {
												if t.T1 != nil {
													return *t.T0 + "." + *t.T1
												} else {
													return *t.T0
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

func makeChildWord(n int64) string {
	if n == 1 {
		return DESCENDANT
	} else {
		return DESCENDANTS
	}
}
<commit_msg>Fixed unnecessary queries for getChildren<commit_after>package main

import (
	//	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"strconv"
)

func getChildren(mt *MeshTree, db *gorm.DB) ([]*MeshTree, error) {
	var mtChildren []*MeshTree
	if mt.Depth == 12 {
		return mtChildren, nil
	}
	q := getChildrenQuery(mt, false)

	log.Println("**************************", mt.Depth, q)

	db.Where(q).Find(&mtChildren)
	// var count int64
	// db.Model(&MeshTree{}).Where(q).Count(&count)
	// log.Println(count)
	// q = getChildrenQuery(mt, true)
	// log.Println("******* all", q)
	// db.Model(&MeshTree{}).Where(q).Count(&count)
	// log.Println(count)
	return mtChildren, nil
}

func countChildren(mt *MeshTree, db *gorm.DB, allChildren bool) int64 {
	if mt.Depth == 12 {
		return 0
	}
	var count int64 = 0

	q := getChildrenQuery(mt, allChildren)
	db.Model(&MeshTree{}).Where(q).Count(&count)
	return count
}

func getLevel(level int, db *gorm.DB) ([]int64, []*MeshTree, error) {
	var mt []*MeshTree
	q := "T0 is not null"
	for i := 1; i < level+2; i++ {
		q += " AND t" + strconv.Itoa(i) + " is null"
	}
	//log.Println(q)
	db.Where(q).Find(&mt)

	var tmp []int64
	return tmp, mt, nil
}

func whichDescendents(all bool, l1, l2 string) string {
	if all {
		if l1 != "" {
			return " AND " + l1 + " IS NOT NULL"
		} else {
			return ""
		}
	} else {
		r := " AND " + l1 + " IS NOT NULL"
		if l1 != "" && l1 != T12 {
			r += " AND " + l2 + " IS NULL"
		}
		return r
	}
}

const T0 = "T0"
const T1 = "T1"
const T2 = "T2"
const T3 = "T3"
const T4 = "T4"
const T5 = "T5"
const T6 = "T6"
const T7 = "T7"
const T8 = "T8"
const T9 = "T9"
const T10 = "T10"
const T11 = "T11"
const T12 = "T12"

func getChildrenQuery(mt *MeshTree, allDescendents bool) string {
	q := ""

	//log.Println("Depth=" + strconv.Itoa(mt.Depth))

	switch mt.Depth {
	case 0:
		q = T0 + "=\"" + *mt.T0 + "\"" + whichDescendents(allDescendents, T1, T2)
	case 1:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\"" + whichDescendents(allDescendents, T2, T3)
	case 2:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\"" + whichDescendents(allDescendents, T3, T4)
	case 3:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\"" + whichDescendents(allDescendents, T4, T5)
	case 4:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\"" + whichDescendents(allDescendents, T5, T6)

	case 5:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\"" + whichDescendents(allDescendents, T6, T7)
	case 6:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\"" + whichDescendents(allDescendents, T7, T8)
	case 7:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\"" + whichDescendents(allDescendents, T8, T9)
	case 8:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\" and " + T8 + "=\"" + *mt.T8 + "\"" + whichDescendents(allDescendents, T9, T10)

	case 9:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\" and " + T8 + "=\"" + *mt.T8 + "\" and T9=\"" + *mt.T9 + "\"" + whichDescendents(allDescendents, T10, T11)

	case 10:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\" and " + T8 + "=\"" + *mt.T8 + "\" and T9=\"" + *mt.T9 + "\" and T10=\"" + *mt.T10 + "\"" + whichDescendents(allDescendents, T11, T12)

	case 11:
		q = T0 + "=\"" + *mt.T0 + "\" and " + T1 + "=\"" + *mt.T1 + "\" and " + T2 + "=\"" + *mt.T2 + "\" and " + T3 + "=\"" + *mt.T3 + "\" and " + T4 + "=\"" + *mt.T4 + "\" and " + T5 + "=\"" + *mt.T5 + "\" and " + T6 + "=\"" + *mt.T6 + "\" and " + T7 + "=\"" + *mt.T7 + "\" and " + T8 + "=\"" + *mt.T8 + "\" and T9=\"" + *mt.T9 + "\" and T10=\"" + *mt.T10 + "\" and T11=\"" + *mt.T11 + "\"" + whichDescendents(allDescendents, T12, "")

	}

	return q

}
func findLabel(t *MeshTree) string {
	if t.T12 != nil {
		return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8 + "." + *t.T9 + "." + *t.T10 + "." + *t.T11 + "." + *t.T12
	} else {
		if t.T11 != nil {
			return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8 + "." + *t.T9 + "." + *t.T10 + "." + *t.T11
		} else {
			if t.T10 != nil {
				return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8 + "." + *t.T9 + "." + *t.T10
			} else {
				if t.T9 != nil {
					return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8 + "." + *t.T9
				} else {
					if t.T8 != nil {
						return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7 + "." + *t.T8
					} else {
						if t.T7 != nil {
							return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6 + *t.T7
						} else {
							if t.T6 != nil {
								return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5 + "." + *t.T6
							} else {
								if t.T5 != nil {
									return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4 + "." + *t.T5
								} else {
									if t.T4 != nil {
										return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3 + "." + *t.T4
									} else {
										if t.T3 != nil {
											return *t.T0 + "." + *t.T1 + "." + *t.T2 + "." + *t.T3
										} else {
											if t.T2 != nil {
												return *t.T0 + "." + *t.T1 + "." + *t.T2
											} else {
												if t.T1 != nil {
													return *t.T0 + "." + *t.T1
												} else {
													return *t.T0
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

func makeChildWord(n int64) string {
	if n == 1 {
		return DESCENDANT
	} else {
		return DESCENDANTS
	}
}
<|endoftext|>


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

// +build linux,!appengine

// Package terminal provides support functions for dealing with terminals, as
// commonly found on UNIX systems.
//
// Putting a terminal into raw mode is the most common requirement:
//
// 	oldState, err := terminal.MakeRaw(0)
// 	if err != nil {
// 	        panic(err)
// 	}
// 	defer terminal.Restore(0, oldState)
package terminal

import (
	"io"
	"syscall"
	"unsafe"
)

// State contains the state of a terminal.
type State struct {
	termios syscall.Termios
}

// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal(fd int) bool {
	var termios syscall.Termios
	_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
	return err == 0
}

// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd int) (*State, error) {
	var oldState State
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 {
		return nil, err
	}

	newState := oldState.termios
	newState.Iflag &^= syscall.ISTRIP | syscall.INLCR | syscall.ICRNL | syscall.IGNCR | syscall.IXON | syscall.IXOFF
	newState.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.ISIG
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
		return nil, err
	}

	return &oldState, nil
}

// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func Restore(fd int, state *State) error {
	_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&state.termios)), 0, 0, 0)
	return err
}

// GetSize returns the dimensions of the given terminal.
func GetSize(fd int) (width, height int, err error) {
	var dimensions [4]uint16

	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&dimensions)), 0, 0, 0); err != 0 {
		return -1, -1, err
	}
	return int(dimensions[1]), int(dimensions[0]), nil
}

// ReadPassword reads a line of input from a terminal without local echo.  This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
func ReadPassword(fd int) ([]byte, error) {
	var oldState syscall.Termios
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); err != 0 {
		return nil, err
	}

	newState := oldState
	newState.Lflag &^= syscall.ECHO
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
		return nil, err
	}

	defer func() {
		syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&oldState)), 0, 0, 0)
	}()

	var buf [16]byte
	var ret []byte
	for {
		n, err := syscall.Read(fd, buf[:])
		if err != nil {
			return nil, err
		}
		if n == 0 {
			if len(ret) == 0 {
				return nil, io.EOF
			}
			break
		}
		if buf[n-1] == '\n' {
			n--
		}
		ret = append(ret, buf[:n]...)
		if n < len(buf) {
			break
		}
	}

	return ret, nil
}
<commit_msg>ssh/terminal: add GetState and make ReadPassword work in raw mode.<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build linux,!appengine

// Package terminal provides support functions for dealing with terminals, as
// commonly found on UNIX systems.
//
// Putting a terminal into raw mode is the most common requirement:
//
// 	oldState, err := terminal.MakeRaw(0)
// 	if err != nil {
// 	        panic(err)
// 	}
// 	defer terminal.Restore(0, oldState)
package terminal

import (
	"io"
	"syscall"
	"unsafe"
)

// State contains the state of a terminal.
type State struct {
	termios syscall.Termios
}

// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal(fd int) bool {
	var termios syscall.Termios
	_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
	return err == 0
}

// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd int) (*State, error) {
	var oldState State
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 {
		return nil, err
	}

	newState := oldState.termios
	newState.Iflag &^= syscall.ISTRIP | syscall.INLCR | syscall.ICRNL | syscall.IGNCR | syscall.IXON | syscall.IXOFF
	newState.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.ISIG
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
		return nil, err
	}

	return &oldState, nil
}

// GetState returns the current state of a terminal which may be useful to
// restore the terminal after a signal.
func GetState(fd int) (*State, error) {
	var oldState State
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 {
		return nil, err
	}

	return &oldState, nil
}

// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func Restore(fd int, state *State) error {
	_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&state.termios)), 0, 0, 0)
	return err
}

// GetSize returns the dimensions of the given terminal.
func GetSize(fd int) (width, height int, err error) {
	var dimensions [4]uint16

	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&dimensions)), 0, 0, 0); err != 0 {
		return -1, -1, err
	}
	return int(dimensions[1]), int(dimensions[0]), nil
}

// ReadPassword reads a line of input from a terminal without local echo.  This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
func ReadPassword(fd int) ([]byte, error) {
	var oldState syscall.Termios
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); err != 0 {
		return nil, err
	}

	newState := oldState
	newState.Lflag &^= syscall.ECHO
	newState.Lflag |= syscall.ICANON | syscall.ISIG
	newState.Iflag |= syscall.ICRNL
	if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
		return nil, err
	}

	defer func() {
		syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&oldState)), 0, 0, 0)
	}()

	var buf [16]byte
	var ret []byte
	for {
		n, err := syscall.Read(fd, buf[:])
		if err != nil {
			return nil, err
		}
		if n == 0 {
			if len(ret) == 0 {
				return nil, io.EOF
			}
			break
		}
		if buf[n-1] == '\n' {
			n--
		}
		ret = append(ret, buf[:n]...)
		if n < len(buf) {
			break
		}
	}

	return ret, nil
}
<|endoftext|>