<commit_before>package handlers

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

	"google.golang.org/appengine"
	"google.golang.org/appengine/datastore"
	"google.golang.org/appengine/log"
	"google.golang.org/appengine/memcache"
	"google.golang.org/appengine/user"

	"github.com/icco/natnatnat/models"
	"github.com/pilu/traffic"
)

type ArchiveData struct {
	Years   *map[string]Year
	Posts   *[]models.Entry
	IsAdmin bool
}

// TODO(icco): Rewrite to fix map iteration problems.
type Year map[time.Month]Month
type Month []Day
type Day []int64

var months = [12]time.Month{
	time.January,
	time.February,
	time.March,
	time.April,
	time.May,
	time.June,
	time.July,
	time.August,
	time.September,
	time.October,
	time.November,
	time.December,
}

func ArchiveTaskHandler(w traffic.ResponseWriter, r *traffic.Request) {
	c := appengine.NewContext(r.Request)

	entries, err := models.AllPosts(c)
	if err != nil {
		log.Errorf(c, err.Error())
		http.Error(w, err.Error(), 500)
		return
	}
	log.Infof(c, "Retrieved data: %d.", len(*entries))

	years := make(map[string]Year)

	oldest := (*entries)[len(*entries)-1].Datetime
	newest := (*entries)[0].Datetime

	log.Infof(c, "Oldest: %v, Newest: %v", oldest, newest)

	for year := oldest.Year(); year <= newest.Year(); year += 1 {
		ystr := strconv.Itoa(year)
		years[ystr] = make(Year)
		log.Infof(c, "Adding %d.", year)
		for _, month := range months {
			if year < newest.Year() || (year == newest.Year() && month <= newest.Month()) {
				years[ystr][month] = make([]Day, daysIn(month, year))
				log.Debugf(c, "Adding %d/%d - %d days.", year, month, len(years[ystr][month]))
			}
		}
	}

	q := models.ArchivePageQuery()
	t := q.Run(c)
	for {
		var p models.Entry
		_, err := t.Next(&p)
		if err == datastore.Done {
			break // No further entities match the query.
		}

		if err != nil {
			log.Errorf(c, "Error fetching next Entry: %v", err)
			break
		}

		year := strconv.Itoa(p.Datetime.Year())
		yint := p.Datetime.Year()
		month := p.Datetime.Month()
		day := p.Datetime.Day()
		log.Infof(c, "Trying post id %d", p.Id)

		if years[year] == nil {
			years[year] = make(Year)
			log.Errorf(c, "%s isn't a valid year.", year)
		}

		if years[year][month] == nil {
			log.Errorf(c, "%s/%d isn't a valid month.", year, month)
			years[year][month] = make([]Day, daysIn(month, yint))
		}

		if years[year][month][day] == nil {
			log.Infof(c, "Making %s/%d/%d", year, month, day)
			years[year][month][day] = make(Day, 0)
		}

		// log.Infof(c, "Appending %d/%d/%d: %+v", year, month, day, years[year][month][day])
		years[year][month][day] = append(years[year][month][day], p.Id)
	}
	log.Infof(c, "Added posts.")

	// https://blog.golang.org/json-and-go
	b, err := json.Marshal(years)
	if err != nil {
		log.Errorf(c, err.Error())
		http.Error(w, err.Error(), 500)
	}

	item := &memcache.Item{
		Key:   "archive_data",
		Value: b,
	}

	// Set the item, unconditionally
	if err := memcache.Set(c, item); err != nil {
		log.Errorf(c, "error setting item: %v", err)
	}
}

func ArchiveHandler(w traffic.ResponseWriter, r *traffic.Request) {
	c := appengine.NewContext(r.Request)

	entries, err := models.AllPosts(c)
	if err != nil {
		log.Errorf(c, err.Error())
		http.Error(w, err.Error(), 500)
		return
	}
	log.Infof(c, "Retrieved data: %d.", len(*entries))

	// Get the item from the memcache
	var years map[string]Year
	if year_data, err := memcache.Get(c, "archive_data"); err == memcache.ErrCacheMiss {
		log.Infof(c, "item not in the cache")
	} else if err != nil {
		log.Errorf(c, "error getting item: %v", err)
	} else {
		err := json.Unmarshal(year_data.Value, &years)
		if err != nil {
			log.Errorf(c, err.Error())
			http.Error(w, err.Error(), 500)
			return
		}
	}

	data := &ArchiveData{Years: &years, IsAdmin: user.IsAdmin(c), Posts: entries}
	w.Render("archive", data)
}

// daysIn returns the number of days in a month for a given year.
func daysIn(m time.Month, year int) int {
	// This is equivalent to time.daysIn(m, year).
	return time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day()
}
<commit_msg>strings<commit_after>package handlers

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

	"google.golang.org/appengine"
	"google.golang.org/appengine/datastore"
	"google.golang.org/appengine/log"
	"google.golang.org/appengine/memcache"
	"google.golang.org/appengine/user"

	"github.com/icco/natnatnat/models"
	"github.com/pilu/traffic"
)

type ArchiveData struct {
	Years   *map[string]Year
	Posts   *[]models.Entry
	IsAdmin bool
}

type Year map[string]Month
type Month []Day
type Day []int64

var months = [12]time.Month{
	time.January,
	time.February,
	time.March,
	time.April,
	time.May,
	time.June,
	time.July,
	time.August,
	time.September,
	time.October,
	time.November,
	time.December,
}

func ArchiveTaskHandler(w traffic.ResponseWriter, r *traffic.Request) {
	c := appengine.NewContext(r.Request)

	entries, err := models.AllPosts(c)
	if err != nil {
		log.Errorf(c, err.Error())
		http.Error(w, err.Error(), 500)
		return
	}
	log.Infof(c, "Retrieved data: %d.", len(*entries))

	years := make(map[string]Year)

	oldest := (*entries)[len(*entries)-1].Datetime
	newest := (*entries)[0].Datetime

	log.Infof(c, "Oldest: %v, Newest: %v", oldest, newest)

	for year := oldest.Year(); year <= newest.Year(); year += 1 {
		ystr := strconv.Itoa(year)
		years[ystr] = make(Year)
		log.Infof(c, "Adding %d.", year)
		for _, month := range months {
			if year < newest.Year() || (year == newest.Year() && month <= newest.Month()) {
				mstr := month.String()
				years[ystr][mstr] = make([]Day, daysIn(month, year))
				log.Debugf(c, "Adding %d/%d - %d days.", year, month, len(years[ystr][mstr]))
			}
		}
	}

	q := models.ArchivePageQuery()
	t := q.Run(c)
	for {
		var p models.Entry
		_, err := t.Next(&p)
		if err == datastore.Done {
			break // No further entities match the query.
		}

		if err != nil {
			log.Errorf(c, "Error fetching next Entry: %v", err)
			break
		}

		year := strconv.Itoa(p.Datetime.Year())
		yint := p.Datetime.Year()
		month := p.Datetime.Month()
		mstr := month.String()
		day := p.Datetime.Day()
		log.Infof(c, "Trying post id %d", p.Id)

		if years[year] == nil {
			years[year] = make(Year)
			log.Errorf(c, "%s isn't a valid year.", year)
		}

		if years[year][mstr] == nil {
			log.Errorf(c, "%s/%d isn't a valid month.", year, month)
			years[year][mstr] = make([]Day, daysIn(month, yint))
		}

		if years[year][mstr][day] == nil {
			log.Infof(c, "Making %s/%d/%d", year, month, day)
			years[year][mstr][day] = make(Day, 0)
		}

		years[year][mstr][day] = append(years[year][mstr][day], p.Id)
	}
	log.Infof(c, "Added posts.")

	// https://blog.golang.org/json-and-go
	b, err := json.Marshal(years)
	if err != nil {
		log.Errorf(c, err.Error())
		http.Error(w, err.Error(), 500)
	}

	item := &memcache.Item{
		Key:   "archive_data",
		Value: b,
	}

	// Set the item, unconditionally
	if err := memcache.Set(c, item); err != nil {
		log.Errorf(c, "error setting item: %v", err)
	}
}

func ArchiveHandler(w traffic.ResponseWriter, r *traffic.Request) {
	c := appengine.NewContext(r.Request)

	entries, err := models.AllPosts(c)
	if err != nil {
		log.Errorf(c, err.Error())
		http.Error(w, err.Error(), 500)
		return
	}
	log.Infof(c, "Retrieved data: %d.", len(*entries))

	// Get the item from the memcache
	var years map[string]Year
	if year_data, err := memcache.Get(c, "archive_data"); err == memcache.ErrCacheMiss {
		log.Infof(c, "item not in the cache")
	} else if err != nil {
		log.Errorf(c, "error getting item: %v", err)
	} else {
		err := json.Unmarshal(year_data.Value, &years)
		if err != nil {
			log.Errorf(c, err.Error())
			http.Error(w, err.Error(), 500)
			return
		}
	}

	data := &ArchiveData{Years: &years, IsAdmin: user.IsAdmin(c), Posts: entries}
	w.Render("archive", data)
}

// daysIn returns the number of days in a month for a given year.
func daysIn(m time.Month, year int) int {
	// This is equivalent to time.daysIn(m, year).
	return time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day()
}
<|endoftext|>


<commit_before>package prompt

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"regexp"
	"strings"
	"sync"

	"github.com/josledp/goprompt/prompt/plugins"
	"github.com/josledp/termcolor"
)

//Prompt is the struct with the prompt options/config
type Prompt struct {
	options map[string]interface{}
	cache   *Cache
}

//Plugin is the interface all the plugins MUST implement
type Plugin interface {
	Name() string
	Load(pr plugins.Prompter) error
	Get(format func(string, ...termcolor.Mode) string) (string, []termcolor.Mode)
}

//New returns a new promp
func New(options map[string]interface{}) Prompt {
	c, err := newCache()
	if err != nil {
		log.Printf("unable to initializa cache: %v", err)
	}
	return Prompt{options, c}
}

//GetOption returns the option value for key
func (pr Prompt) GetOption(key string) (interface{}, bool) {
	value, ok := pr.options[key]
	return value, ok
}

//GetCache recovers a value from cache
func (pr Prompt) GetCache(key string) (interface{}, bool) {
	//Encapsulate more cache?
	if pr.cache == nil {
		return nil, false
	}
	value, ok := pr.cache.data[key]
	return value, ok
}

//Cache caches a key, value on cache
func (pr Prompt) Cache(key string, value interface{}) error {
	if pr.cache == nil {
		return fmt.Errorf("Cache not initialized")
	}
	if pr.cache.data == nil {
		pr.cache.data = make(map[string]interface{})
	}
	pr.cache.data[key] = value
	return nil
}

//Compile processes the template and returns a prompt string
func (pr Prompt) Compile(template string, color bool) string {
	var format func(string, ...termcolor.Mode) string
	output := template

	if color {

		shell := pr.detectShell()
		switch shell {
		case "bash":
			format = termcolor.EscapedFormat
		case "fish":
			format = termcolor.Format
		case "zsh":
			format = termcolor.Format

		default:
			//Defaut failsafe
			format = func(s string, modes ...termcolor.Mode) string { return s }
		}
	} else {

		format = func(s string, modes ...termcolor.Mode) string { return s }
	}

	// map plugin by name
	mPlugins := make(map[string]Plugin)
	for _, p := range availablePlugins {
		mPlugins[p.Name()] = p
	}

	//Regular expresions for matching on template
	reChunk, _ := regexp.Compile("<[^<>]*>")
	rePlugin, _ := regexp.Compile("%[a-z]*%")
	chunks := reChunk.FindAllString(template, -1)

	//Channel for plugins to write (parallel plugin processing)
	pluginsOutput := make(chan []string)
	pluginsWg := sync.WaitGroup{}
	pluginsWg.Add(len(chunks))
	go func() {
		pluginsWg.Wait()
		close(pluginsOutput)
	}()

	//For each chunk of <[^<>]*> we process it in parallel putting in the channel the string to replace on template
	for _, chunk := range chunks {
		go func(chunk string) {
			defer pluginsWg.Done()
			processedChunk := chunk[1 : len(chunk)-1]
			rawPlugin := rePlugin.FindString(chunk)
			plugin := rawPlugin[1 : len(rawPlugin)-1]
			if p, ok := mPlugins[plugin]; ok {
				//TODO +options
				err := p.Load(pr)
				if err != nil {
					log.Printf("Unable to load plugin %s: %v", plugin, err)
					return
				}
				output, modes := p.Get(format)
				if output != "" {
					extra := strings.Split(processedChunk, rawPlugin)
					for _, e := range extra {
						useless, _ := regexp.MatchString("^[ ]*$", e)
						if !useless {
							processed := format(e, modes...)
							processedChunk = strings.Replace(processedChunk, e, processed, -1)
						}
					}
					processedChunk = strings.Replace(processedChunk, rawPlugin, output, -1)
					pluginsOutput <- []string{chunk, format(processedChunk, modes...)}
				} else {
					pluginsOutput <- []string{chunk, ""}
				}
			} else {
				log.Printf("Plugin %s not found", plugin)
			}

		}(chunk)
	}
	for rep := range pluginsOutput {
		output = strings.Replace(output, rep[0], rep[1], -1)
	}
	err := pr.cache.save()
	if err != nil {
		log.Printf("Unable to save cache: %v", err)
	}
	return output
}

var availablePlugins []Plugin

func init() {
	availablePlugins = []Plugin{
		&plugins.Aws{},
		&plugins.Git{},
		&plugins.LastCommand{},
		&plugins.Path{},
		&plugins.Python{},
		&plugins.User{},
		&plugins.Hostname{},
		&plugins.UserChar{},
		&plugins.Golang{},
	}

}

func (p Prompt) detectShell() string {
	pid := os.Getppid()
	cmdlineFile := fmt.Sprintf("/proc/%d/cmdline", pid)
	cmdline, err := ioutil.ReadFile(cmdlineFile)
	if err != nil {
		return "unknown"
	}

	shells := []string{"bash", "zsh", "fish"}
	for _, shell := range shells {
		if matches, _ := regexp.Match(shell, cmdline); matches {
			return shell
		}
	}
	return "unknown"
}
<commit_msg>typo on receiver name<commit_after>package prompt

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"regexp"
	"strings"
	"sync"

	"github.com/josledp/goprompt/prompt/plugins"
	"github.com/josledp/termcolor"
)

//Prompt is the struct with the prompt options/config
type Prompt struct {
	options map[string]interface{}
	cache   *Cache
}

//Plugin is the interface all the plugins MUST implement
type Plugin interface {
	Name() string
	Load(pr plugins.Prompter) error
	Get(format func(string, ...termcolor.Mode) string) (string, []termcolor.Mode)
}

//New returns a new promp
func New(options map[string]interface{}) Prompt {
	c, err := newCache()
	if err != nil {
		log.Printf("unable to initializa cache: %v", err)
	}
	return Prompt{options, c}
}

//GetOption returns the option value for key
func (pr Prompt) GetOption(key string) (interface{}, bool) {
	value, ok := pr.options[key]
	return value, ok
}

//GetCache recovers a value from cache
func (pr Prompt) GetCache(key string) (interface{}, bool) {
	//Encapsulate more cache?
	if pr.cache == nil {
		return nil, false
	}
	value, ok := pr.cache.data[key]
	return value, ok
}

//Cache caches a key, value on cache
func (pr Prompt) Cache(key string, value interface{}) error {
	if pr.cache == nil {
		return fmt.Errorf("Cache not initialized")
	}
	if pr.cache.data == nil {
		pr.cache.data = make(map[string]interface{})
	}
	pr.cache.data[key] = value
	return nil
}

//Compile processes the template and returns a prompt string
func (pr Prompt) Compile(template string, color bool) string {
	var format func(string, ...termcolor.Mode) string
	output := template

	if color {

		shell := pr.detectShell()
		switch shell {
		case "bash":
			format = termcolor.EscapedFormat
		case "fish":
			format = termcolor.Format
		case "zsh":
			format = termcolor.Format

		default:
			//Defaut failsafe
			format = func(s string, modes ...termcolor.Mode) string { return s }
		}
	} else {

		format = func(s string, modes ...termcolor.Mode) string { return s }
	}

	// map plugin by name
	mPlugins := make(map[string]Plugin)
	for _, p := range availablePlugins {
		mPlugins[p.Name()] = p
	}

	//Regular expresions for matching on template
	reChunk, _ := regexp.Compile("<[^<>]*>")
	rePlugin, _ := regexp.Compile("%[a-z]*%")
	chunks := reChunk.FindAllString(template, -1)

	//Channel for plugins to write (parallel plugin processing)
	pluginsOutput := make(chan []string)
	pluginsWg := sync.WaitGroup{}
	pluginsWg.Add(len(chunks))
	go func() {
		pluginsWg.Wait()
		close(pluginsOutput)
	}()

	//For each chunk of <[^<>]*> we process it in parallel putting in the channel the string to replace on template
	for _, chunk := range chunks {
		go func(chunk string) {
			defer pluginsWg.Done()
			processedChunk := chunk[1 : len(chunk)-1]
			rawPlugin := rePlugin.FindString(chunk)
			plugin := rawPlugin[1 : len(rawPlugin)-1]
			if p, ok := mPlugins[plugin]; ok {
				//TODO +options
				err := p.Load(pr)
				if err != nil {
					log.Printf("Unable to load plugin %s: %v", plugin, err)
					return
				}
				output, modes := p.Get(format)
				if output != "" {
					extra := strings.Split(processedChunk, rawPlugin)
					for _, e := range extra {
						useless, _ := regexp.MatchString("^[ ]*$", e)
						if !useless {
							processed := format(e, modes...)
							processedChunk = strings.Replace(processedChunk, e, processed, -1)
						}
					}
					processedChunk = strings.Replace(processedChunk, rawPlugin, output, -1)
					pluginsOutput <- []string{chunk, format(processedChunk, modes...)}
				} else {
					pluginsOutput <- []string{chunk, ""}
				}
			} else {
				log.Printf("Plugin %s not found", plugin)
			}

		}(chunk)
	}
	for rep := range pluginsOutput {
		output = strings.Replace(output, rep[0], rep[1], -1)
	}
	err := pr.cache.save()
	if err != nil {
		log.Printf("Unable to save cache: %v", err)
	}
	return output
}

var availablePlugins []Plugin

func init() {
	availablePlugins = []Plugin{
		&plugins.Aws{},
		&plugins.Git{},
		&plugins.LastCommand{},
		&plugins.Path{},
		&plugins.Python{},
		&plugins.User{},
		&plugins.Hostname{},
		&plugins.UserChar{},
		&plugins.Golang{},
	}

}

func (pr Prompt) detectShell() string {
	pid := os.Getppid()
	cmdlineFile := fmt.Sprintf("/proc/%d/cmdline", pid)
	cmdline, err := ioutil.ReadFile(cmdlineFile)
	if err != nil {
		return "unknown"
	}

	shells := []string{"bash", "zsh", "fish"}
	for _, shell := range shells {
		if matches, _ := regexp.Match(shell, cmdline); matches {
			return shell
		}
	}
	return "unknown"
}
<|endoftext|>


<commit_before>package api

import (
	"errors"
	"fmt"
	"github.com/gofxh/blog/lib/base"
	"github.com/gofxh/blog/lib/core"
	"github.com/gofxh/blog/mvc/action"
	"github.com/lunny/tango"
	"github.com/tango-contrib/binding"
)

// login controller
type LoginController struct {
	tango.Ctx
	binding.Binder
}

// login controller post method
func (l *LoginController) Post() {
	var form action.LoginForm
	if e := l.Bind(&form); e.Len() > 0 {
		l.ServeJson(core.NewErrorResult(errors.New(e[0].Error())))
		return
	}
	form.Ip = l.Req().RemoteAddr
	form.UserAgent = l.Req().UserAgent()
	form.Expire = 3600 * 24 * 7
	result := base.Action.Call(action.Login, &form)
	l.ServeJson(result)
}
<commit_msg>add login cookie saving<commit_after>package api

import (
	"errors"
	"fmt"
	"github.com/gofxh/blog/lib/base"
	"github.com/gofxh/blog/lib/core"
	"github.com/gofxh/blog/lib/entity"
	"github.com/gofxh/blog/mvc/action"
	"github.com/lunny/tango"
	"github.com/tango-contrib/binding"
	"net/http"
	"time"
)

// login controller
type LoginController struct {
	tango.Ctx
	binding.Binder
}

// login controller post method
func (l *LoginController) Post() {
	var form action.LoginForm
	if e := l.Bind(&form); e.Len() > 0 {
		l.ServeJson(core.NewErrorResult(errors.New(e[0].Error())))
		return
	}
	form.Ip = l.Req().RemoteAddr
	form.UserAgent = l.Req().UserAgent()
	form.Expire = 3600 * 24 * 7
	result := base.Action.Call(action.Login, &form)
	if result.Meta.Status {
		tk := result.Data["token"].(*entity.Token)
		l.Cookies().Set(&http.Cookie{
			Name:   "token",
			Value:  tk.Value,
			MaxAge: int(tk.ExpireTime - time.Now().Unix()),
		})
	}
	l.ServeJson(result)
}
<|endoftext|>


<commit_before>package graph

type NodeInfo struct {
	Pre           int
	Post          int
	IDom          NodeID
	LoopHead      NodeID
	IsHead        bool
	IsIrreducible bool
	Live          bool
}

type EdgeType int

const (
	DEAD EdgeType = iota
	FORWARD
	BACKWARD
	CROSS
	REENTRY
)

type loopFinder struct {
	graph     *Graph
	node      []NodeInfo
	edge      []EdgeType
	postorder []NodeID
	depth     []int
	current   int
}

func (lf *loopFinder) beginTraversingNode(n NodeID, prev NodeID) {
	lf.current += 1

	lf.node[n] = NodeInfo{
		Pre:      lf.current,
		IDom:     prev, // A reasonable inital guess.
		LoopHead: NoNode,
		Live:     true,
	}

	lf.depth[n] = lf.current
}

func (lf *loopFinder) endTraversingNode(n NodeID) {
	lf.current += 1
	lf.node[n].Post = lf.current

	lf.depth[n] = 0

	lf.postorder = append(lf.postorder, n)
}

func (lf *loopFinder) isUnprocessed(n NodeID) bool {
	return !lf.node[n].Live
}

func (lf *loopFinder) isBeingProcessed(dst NodeID) bool {
	return lf.depth[dst] > 0
}

func (lf *loopFinder) markLoopHeader(child NodeID, head NodeID) {
	if child == head {
		// Trivial loop.
		return
	}
	childHead := lf.node[child].LoopHead
	for childHead != NoNode {
		if childHead == head {
			return
		}
		if lf.depth[childHead] < lf.depth[head] {
			// Found a closer head for this child, adopt it.
			lf.node[child].LoopHead = head
			child, head = head, childHead
		} else {
			child = childHead
		}
		childHead = lf.node[child].LoopHead
	}
	lf.node[child].LoopHead = head
}

func (lf *loopFinder) process(n NodeID, prev NodeID) {
	lf.beginTraversingNode(n, prev)
	xit := lf.graph.ExitIterator(n)
	for xit.HasNext() {
		e, next := xit.GetNext()
		if lf.isUnprocessed(next) {
			lf.edge[e] = FORWARD
			lf.process(next, n)

			// Propagage loop headers upwards.
			head := lf.node[next].LoopHead
			if head != NoNode {
				lf.markLoopHeader(n, head)
			}
		} else if lf.isBeingProcessed(next) {
			lf.edge[e] = BACKWARD
			lf.node[next].IsHead = true
			lf.markLoopHeader(n, next)
		} else {
			lf.edge[e] = CROSS
			if lf.node[next].LoopHead != NoNode {
				// Propagate loop header from cross edge.
				otherHead := lf.node[next].LoopHead
				if lf.isBeingProcessed(otherHead) {
					lf.markLoopHeader(n, otherHead)
				} else {
					lf.edge[e] = REENTRY
					lf.node[otherHead].IsIrreducible = true
					// Find and mark the common loop head.
					otherHead = lf.node[otherHead].LoopHead
					for otherHead != NoNode {
						if lf.isBeingProcessed(otherHead) {
							lf.markLoopHeader(n, otherHead)
							break
						}
						otherHead = lf.node[otherHead].LoopHead
					}
				}
			}
		}
	}
	lf.endTraversingNode(n)
}

func Intersect(nodes []NodeInfo, n0 NodeID, n1 NodeID) NodeID {
	i0 := nodes[n0].Post
	i1 := nodes[n1].Post
	for i0 != i1 {
		for i0 < i1 {
			n0 = nodes[n0].IDom
			i0 = nodes[n0].Post
		}
		for i0 > i1 {
			n1 = nodes[n1].IDom
			i1 = nodes[n1].Post
		}
	}
	return n0
}

func (lf *loopFinder) intersect(n0 NodeID, n1 NodeID) NodeID {
	return Intersect(lf.node, n0, n1)
}

func (lf *loopFinder) cleanDeadEdges() {
	numEdges := lf.graph.NumEdges()
	for i := 0; i < numEdges; i++ {
		if lf.edge[i] == DEAD {
			lf.graph.KillEdge(EdgeID(i))
		}
	}
}

func (lf *loopFinder) findIdoms() {
	g := lf.graph
	changed := true
	for changed {
		changed = false
		for i := len(lf.postorder) - 1; i >= 0; i-- {
			n := lf.postorder[i]
			original := lf.node[n].IDom
			idom := original
			eit := g.EntryIterator(n)
			for eit.HasNext() {
				src, _ := eit.GetNext()
				idom = lf.intersect(idom, src)
			}
			if idom != original {
				lf.node[n].IDom = idom
				changed = true
			}
		}
	}
}

func AnalyzeStructure(g *Graph) ([]NodeInfo, []EdgeType, []NodeID) {
	numNodes := g.NumNodes()
	lf := &loopFinder{
		graph: g,
		node:  make([]NodeInfo, numNodes),
		edge:  make([]EdgeType, g.NumEdges()),
		depth: make([]int, numNodes),
	}

	e := g.Entry()
	lf.process(e, e)
	lf.cleanDeadEdges()
	lf.findIdoms()
	return lf.node, lf.edge, lf.postorder
}
<commit_msg>Better initial estimates of IDoms while analyzing graph structure.<commit_after>package graph

type NodeInfo struct {
	Pre           int
	Post          int
	IDom          NodeID
	LoopHead      NodeID
	IsHead        bool
	IsIrreducible bool
	Live          bool
}

type EdgeType int

const (
	DEAD EdgeType = iota
	FORWARD
	BACKWARD
	CROSS
	REENTRY
)

type loopFinder struct {
	graph     *Graph
	node      []NodeInfo
	edge      []EdgeType
	postorder []NodeID
	depth     []int
	current   int
}

func (lf *loopFinder) beginTraversingNode(n NodeID, prev NodeID) {
	lf.current += 1

	lf.node[n] = NodeInfo{
		Pre:      lf.current,
		IDom:     prev, // A reasonable inital guess.
		LoopHead: NoNode,
		Live:     true,
	}

	lf.depth[n] = lf.current
}

func (lf *loopFinder) endTraversingNode(n NodeID) {
	lf.current += 1
	lf.node[n].Post = lf.current

	lf.depth[n] = 0

	lf.postorder = append(lf.postorder, n)
}

func (lf *loopFinder) isUnprocessed(n NodeID) bool {
	return !lf.node[n].Live
}

func (lf *loopFinder) isBeingProcessed(dst NodeID) bool {
	return lf.depth[dst] > 0
}

func (lf *loopFinder) markLoopHeader(child NodeID, head NodeID) {
	if child == head {
		// Trivial loop.
		return
	}
	childHead := lf.node[child].LoopHead
	for childHead != NoNode {
		if childHead == head {
			return
		}
		if lf.depth[childHead] < lf.depth[head] {
			// Found a closer head for this child, adopt it.
			lf.node[child].LoopHead = head
			child, head = head, childHead
		} else {
			child = childHead
		}
		childHead = lf.node[child].LoopHead
	}
	lf.node[child].LoopHead = head
}

func (lf *loopFinder) updateCrossEdgeIDom(n NodeID) {
	// The IDom will always be in the path of nodes being processed.
	// Climb until we find the path.
	idom := lf.node[n].IDom
	for !lf.isBeingProcessed(idom) {
		idom = lf.node[idom].IDom
	}
	lf.node[n].IDom = idom
}

func (lf *loopFinder) process(n NodeID, prev NodeID) {
	lf.beginTraversingNode(n, prev)
	xit := lf.graph.ExitIterator(n)
	for xit.HasNext() {
		e, next := xit.GetNext()
		if lf.isUnprocessed(next) {
			lf.edge[e] = FORWARD
			lf.process(next, n)

			// Propagage loop headers upwards.
			head := lf.node[next].LoopHead
			if head != NoNode {
				lf.markLoopHeader(n, head)
			}
		} else if lf.isBeingProcessed(next) {
			lf.edge[e] = BACKWARD
			lf.node[next].IsHead = true
			lf.markLoopHeader(n, next)
		} else {
			lf.edge[e] = CROSS
			lf.updateCrossEdgeIDom(next)
			if lf.node[next].LoopHead != NoNode {
				// Propagate loop header from cross edge.
				otherHead := lf.node[next].LoopHead
				if lf.isBeingProcessed(otherHead) {
					lf.markLoopHeader(n, otherHead)
				} else {
					lf.edge[e] = REENTRY
					lf.node[otherHead].IsIrreducible = true
					// Find and mark the common loop head.
					otherHead = lf.node[otherHead].LoopHead
					for otherHead != NoNode {
						if lf.isBeingProcessed(otherHead) {
							lf.markLoopHeader(n, otherHead)
							break
						}
						otherHead = lf.node[otherHead].LoopHead
					}
				}
			}
		}
	}
	lf.endTraversingNode(n)
}

func Intersect(nodes []NodeInfo, n0 NodeID, n1 NodeID) NodeID {
	i0 := nodes[n0].Post
	i1 := nodes[n1].Post
	for i0 != i1 {
		for i0 < i1 {
			n0 = nodes[n0].IDom
			i0 = nodes[n0].Post
		}
		for i0 > i1 {
			n1 = nodes[n1].IDom
			i1 = nodes[n1].Post
		}
	}
	return n0
}

func (lf *loopFinder) intersect(n0 NodeID, n1 NodeID) NodeID {
	return Intersect(lf.node, n0, n1)
}

func (lf *loopFinder) cleanDeadEdges() {
	numEdges := lf.graph.NumEdges()
	for i := 0; i < numEdges; i++ {
		if lf.edge[i] == DEAD {
			lf.graph.KillEdge(EdgeID(i))
		}
	}
}

func (lf *loopFinder) findIdoms() {
	g := lf.graph
	changed := true
	for changed {
		changed = false
		for i := len(lf.postorder) - 1; i >= 0; i-- {
			n := lf.postorder[i]
			original := lf.node[n].IDom
			idom := original
			eit := g.EntryIterator(n)
			for eit.HasNext() {
				src, _ := eit.GetNext()
				idom = lf.intersect(idom, src)
			}
			if idom != original {
				lf.node[n].IDom = idom
				changed = true
			}
		}
	}
}

func AnalyzeStructure(g *Graph) ([]NodeInfo, []EdgeType, []NodeID) {
	numNodes := g.NumNodes()
	lf := &loopFinder{
		graph: g,
		node:  make([]NodeInfo, numNodes),
		edge:  make([]EdgeType, g.NumEdges()),
		depth: make([]int, numNodes),
	}

	e := g.Entry()
	lf.process(e, e)
	lf.cleanDeadEdges()
	lf.findIdoms()
	return lf.node, lf.edge, lf.postorder
}
<|endoftext|>


<commit_before>package transactions

import (
	"errors"
	"fmt"

	"github.com/jinzhu/gorm"
	"github.com/joshheinrichs/geosource/server/config"
	_ "github.com/lib/pq"
)

var db *gorm.DB

var ErrInsufficientPermission error = errors.New("Insufficient permission.")

func Init(config *config.Config) (err error) {
	arguments := ""
	if len(config.Database.Host) > 0 {
		arguments += fmt.Sprintf("host=%s ", config.Database.Host)
	}
	if len(config.Database.Database) > 0 {
		arguments += fmt.Sprintf("dbname=%s ", config.Database.Database)
	}
	if len(config.Database.User) > 0 {
		arguments += fmt.Sprintf("user=%s ", config.Database.User)
	}
	if len(config.Database.Password) > 0 {
		arguments += fmt.Sprintf("password=%s ", config.Database.Password)
	}

	db, err = gorm.Open("postgres", arguments)
	if err != nil {
		return err
	}
	return nil
}
<commit_msg>Add some documentation to transactions package<commit_after>// Package transactions provides a set of functions which allow for interaction
// with the database.
package transactions

import (
	"errors"
	"fmt"

	"github.com/jinzhu/gorm"
	"github.com/joshheinrichs/geosource/server/config"
	_ "github.com/lib/pq"
)

var db *gorm.DB

var ErrInsufficientPermission error = errors.New("Insufficient permission.")

// Init opens a connection to the database based on the information in the
// given config. Returns an error if the connection  could not be established.
func Init(config *config.Config) (err error) {
	arguments := ""
	if len(config.Database.Host) > 0 {
		arguments += fmt.Sprintf("host=%s ", config.Database.Host)
	}
	if len(config.Database.Database) > 0 {
		arguments += fmt.Sprintf("dbname=%s ", config.Database.Database)
	}
	if len(config.Database.User) > 0 {
		arguments += fmt.Sprintf("user=%s ", config.Database.User)
	}
	if len(config.Database.Password) > 0 {
		arguments += fmt.Sprintf("password=%s ", config.Database.Password)
	}

	db, err = gorm.Open("postgres", arguments)
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>// Package bitcoind is a package
package bitcoind

/*
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
import (
 	"github.com/rvelhote/bitcoind-status/bitcoind/rpc"
	"github.com/rvelhote/bitcoind-status/bitcoind/rpc/method"
	"github.com/rvelhote/bitcoind-status/configuration"
	"html/template"
	"log"
	"net/http"
)

// IndexTemplateParams holds various values to be passed to the main template
type IndexTemplateParams struct {
	Title   string
	Peers   []method.PeerInfo
	Network method.NetworkInfo
}

// IndexRequestHandler handles the requests to present the main url of the application
type IndexRequestHandler struct {
	// Configuration contains the app configuration. In this context only the server list is used.
	Configuration configuration.Configuration
}

// ServeHTTP handles the request made to the homepage of the app. It will only serve the required files to start
// the RectJS app as well as some important configuration.
func (i IndexRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	w.Header().Add("Content-Type", "text/html")
	t, err := template.New("index.html").ParseFiles("templates/index.html")

	if err != nil {
		t, _ = template.New("index.html").ParseFiles("../templates/index.html")
	}

	client := rpc.NewRPCClient(i.Configuration.Url, i.Configuration.Username, i.Configuration.Password)
	peerinfo, err := method.GetPeerInfo(client)
	networkinfo, err := method.GetNetworkInfo(client)

	if err != nil {
		log.Fatal(err)
	}

	params := IndexTemplateParams{
		Title:   "Bitcoin Daemon Status",
		Peers:   peerinfo,
		Network: networkinfo,
	}

	t.Execute(w, params)
}

func Init(mux *http.ServeMux, configuration configuration.Configuration) {
	indexHandler := IndexRequestHandler{Configuration: configuration}

	mux.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
	mux.Handle("/", indexHandler)
}
<commit_msg>Check for errors on GetPeerInfo. Was mesmerized for a bit because it was failing occasionaly when SynchedHeaders was a negative value.<commit_after>// Package bitcoind is a package
package bitcoind

/*
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
import (
 	"github.com/rvelhote/bitcoind-status/bitcoind/rpc"
	"github.com/rvelhote/bitcoind-status/bitcoind/rpc/method"
	"github.com/rvelhote/bitcoind-status/configuration"
	"html/template"
	"log"
	"net/http"
)

// IndexTemplateParams holds various values to be passed to the main template
type IndexTemplateParams struct {
	Title   string
	Peers   []method.PeerInfo
	Network method.NetworkInfo
}

// IndexRequestHandler handles the requests to present the main url of the application
type IndexRequestHandler struct {
	// Configuration contains the app configuration. In this context only the server list is used.
	Configuration configuration.Configuration
}

// ServeHTTP handles the request made to the homepage of the app. It will only serve the required files to start
// the RectJS app as well as some important configuration.
func (i IndexRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	w.Header().Add("Content-Type", "text/html")
	t, err := template.New("index.html").ParseFiles("templates/index.html")

	if err != nil {
		t, _ = template.New("index.html").ParseFiles("../templates/index.html")
	}

	client := rpc.NewRPCClient(i.Configuration.Url, i.Configuration.Username, i.Configuration.Password)

	peerinfo, err := method.GetPeerInfo(client)
	if err != nil {
		log.Fatal(err)
	}

	networkinfo, err := method.GetNetworkInfo(client)
	if err != nil {
		log.Fatal(err)
	}

	params := IndexTemplateParams{
		Title:   "Bitcoin Daemon Status",
		Peers:   peerinfo,
		Network: networkinfo,
	}

	t.Execute(w, params)
}

func Init(mux *http.ServeMux, configuration configuration.Configuration) {
	indexHandler := IndexRequestHandler{Configuration: configuration}

	mux.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
	mux.Handle("/", indexHandler)
}
<|endoftext|>


<commit_before>package editor

import (
	"fmt"
	"strings"

	"github.com/elpinal/coco3/screen"
)

type exCommand struct {
	name string
	fn   func(*commandline, []string) continuity
}

// exComands represents a table of Ex commands and corresponding functions.
// The order is important. Precede commands have higher precedence.
var exCommands = []exCommand{
	{"help", (*commandline).help},
	{"delete", (*commandline).delete},
	{"quit", (*commandline).quit},
	{"substitute", (*commandline).substitute},
}

type commandline struct {
	streamSet
	*editor

	basic *basic

	history [][]rune
	age     int
}

func newCommandline(s streamSet, e *editor) *commandline {
	return &commandline{
		streamSet: s,
		editor:    e,
		basic:     &basic{},
	}
}

func (e *commandline) Mode() mode {
	return modeCommandline
}

func (e *commandline) Position() int {
	return e.basic.pos + 1
}

func (e *commandline) Runes() []rune {
	return e.buf
}

func (e *commandline) Message() []rune {
	return append([]rune{':'}, e.basic.buf...)
}

func (e *commandline) Highlight() *screen.Hi {
	return nil
}

func (e *commandline) Run() (end continuity, next modeChanger, err error) {
	r, _, err := e.in.ReadRune()
	if err != nil {
		return end, next, err
	}
	switch r {
	case CharCtrlM, CharCtrlJ:
		end, err = e.execute()
		next = norm()

	case CharEscape, CharCtrlC:
		next = norm()

	case CharBackspace, CharCtrlH:
		if len(e.basic.buf) == 0 {
			next = norm()
			return
		}
		e.basic.delete(e.basic.pos-1, e.basic.pos)

	case CharCtrlB:
		e.basic.move(0)
	case CharCtrlE:
		e.basic.move(len(e.basic.buf))
	case CharCtrlN:
		e.historyForward()
	case CharCtrlP:
		e.historyBack()
	case CharCtrlU:
		e.basic.delete(0, e.basic.pos)
	case CharCtrlW:
		// FIXME: It's redundant.
		ed := newEditor()
		ed.pos = e.basic.pos
		ed.buf = e.basic.buf
		pos := ed.pos
		ed.wordBackward()
		e.basic.delete(pos, ed.pos)
	default:
		e.basic.insert([]rune{r}, e.basic.pos)
	}
	return
}

func (e *commandline) execute() (end continuity, err error) {
	var candidate exCommand
	s := string(e.basic.buf)
	if s == "" {
		return
	}
	args := strings.Split(s, " ")
	s = args[0]
	args = args[1:]
	defer func() {
		e.history = append(e.history, e.basic.buf)
	}()
	for _, cmd := range exCommands {
		if !strings.HasPrefix(cmd.name, s) {
			continue
		}
		if cmd.name == s {
			end = cmd.fn(e, args)
			return
		}
		if candidate.name == "" {
			candidate = cmd
		}
	}
	if candidate.name != "" {
		end = candidate.fn(e, args)
		return
	}
	err = fmt.Errorf("not a command: %q", s)
	return
}

func (e *commandline) historyBack() {
	l := len(e.history)
	if l-e.age == 0 {
		return
	}
	e.age++
	e.basic.buf = e.history[l-e.age]
}

func (e *commandline) historyForward() {
	l := len(e.history)
	if e.age == 0 {
		return
	}
	e.age--
	e.basic.buf = e.history[l-e.age]
}

func (e *commandline) quit(args []string) continuity {
	return exit
}

func (e *commandline) delete(args []string) (_ continuity) {
	e.editor.delete(0, len(e.editor.buf))
	return
}

func (e *commandline) help(args []string) continuity {
	e.buf = []rune("help")
	e.pos = 4
	return execute
}

func (e *commandline) substitute(args []string) (_ continuity) {
	if len(args) != 2 {
		return
	}
	pat := args[0]
	s0 := args[1]
	s := strings.Replace(string(e.buf), pat, s0, -1)
	e.buf = []rune(s)
	return
}
<commit_msg>Fix a grammatical error<commit_after>package editor

import (
	"fmt"
	"strings"

	"github.com/elpinal/coco3/screen"
)

type exCommand struct {
	name string
	fn   func(*commandline, []string) continuity
}

// exComands represents a table of Ex commands and corresponding functions.
// The order is important. Preceding commands have higher precedence.
var exCommands = []exCommand{
	{"help", (*commandline).help},
	{"delete", (*commandline).delete},
	{"quit", (*commandline).quit},
	{"substitute", (*commandline).substitute},
}

type commandline struct {
	streamSet
	*editor

	basic *basic

	history [][]rune
	age     int
}

func newCommandline(s streamSet, e *editor) *commandline {
	return &commandline{
		streamSet: s,
		editor:    e,
		basic:     &basic{},
	}
}

func (e *commandline) Mode() mode {
	return modeCommandline
}

func (e *commandline) Position() int {
	return e.basic.pos + 1
}

func (e *commandline) Runes() []rune {
	return e.buf
}

func (e *commandline) Message() []rune {
	return append([]rune{':'}, e.basic.buf...)
}

func (e *commandline) Highlight() *screen.Hi {
	return nil
}

func (e *commandline) Run() (end continuity, next modeChanger, err error) {
	r, _, err := e.in.ReadRune()
	if err != nil {
		return end, next, err
	}
	switch r {
	case CharCtrlM, CharCtrlJ:
		end, err = e.execute()
		next = norm()

	case CharEscape, CharCtrlC:
		next = norm()

	case CharBackspace, CharCtrlH:
		if len(e.basic.buf) == 0 {
			next = norm()
			return
		}
		e.basic.delete(e.basic.pos-1, e.basic.pos)

	case CharCtrlB:
		e.basic.move(0)
	case CharCtrlE:
		e.basic.move(len(e.basic.buf))
	case CharCtrlN:
		e.historyForward()
	case CharCtrlP:
		e.historyBack()
	case CharCtrlU:
		e.basic.delete(0, e.basic.pos)
	case CharCtrlW:
		// FIXME: It's redundant.
		ed := newEditor()
		ed.pos = e.basic.pos
		ed.buf = e.basic.buf
		pos := ed.pos
		ed.wordBackward()
		e.basic.delete(pos, ed.pos)
	default:
		e.basic.insert([]rune{r}, e.basic.pos)
	}
	return
}

func (e *commandline) execute() (end continuity, err error) {
	var candidate exCommand
	s := string(e.basic.buf)
	if s == "" {
		return
	}
	args := strings.Split(s, " ")
	s = args[0]
	args = args[1:]
	defer func() {
		e.history = append(e.history, e.basic.buf)
	}()
	for _, cmd := range exCommands {
		if !strings.HasPrefix(cmd.name, s) {
			continue
		}
		if cmd.name == s {
			end = cmd.fn(e, args)
			return
		}
		if candidate.name == "" {
			candidate = cmd
		}
	}
	if candidate.name != "" {
		end = candidate.fn(e, args)
		return
	}
	err = fmt.Errorf("not a command: %q", s)
	return
}

func (e *commandline) historyBack() {
	l := len(e.history)
	if l-e.age == 0 {
		return
	}
	e.age++
	e.basic.buf = e.history[l-e.age]
}

func (e *commandline) historyForward() {
	l := len(e.history)
	if e.age == 0 {
		return
	}
	e.age--
	e.basic.buf = e.history[l-e.age]
}

func (e *commandline) quit(args []string) continuity {
	return exit
}

func (e *commandline) delete(args []string) (_ continuity) {
	e.editor.delete(0, len(e.editor.buf))
	return
}

func (e *commandline) help(args []string) continuity {
	e.buf = []rune("help")
	e.pos = 4
	return execute
}

func (e *commandline) substitute(args []string) (_ continuity) {
	if len(args) != 2 {
		return
	}
	pat := args[0]
	s0 := args[1]
	s := strings.Replace(string(e.buf), pat, s0, -1)
	e.buf = []rune(s)
	return
}
<|endoftext|>


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

package calc

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/czcorpus/klogproc/conversion"
)

// LineParser is a parser for reading KonText application logs
type LineParser struct {
}

func (lp *LineParser) ParseLine(s string, lineNum int, localTimezone string) (*InputRecord, error) {
	rec := &InputRecord{}
	err := json.Unmarshal([]byte(s), rec)
	if err != nil {
		return rec, err
	}
	if rec.TS[len(rec.TS)-1] == 'Z' {
		minsChng, err := conversion.TimezoneToInt(localTimezone)
		if err != nil {
			return rec, err
		}
		tm, err := time.Parse("2006-01-02T15:04:05-07:00", rec.TS[:len(rec.TS)-1]+localTimezone)
		fmt.Println("tm1: ", rec.TS)
		if err != nil {
			return rec, err
		}
		tm = tm.Add(time.Minute * time.Duration(minsChng))
		rec.TS = tm.Format("2006-01-02T15:04:05-07:00")
		fmt.Println("tm2: ", rec.TS)
	}
	return rec, nil
}
<commit_msg>Update parser.go<commit_after>// Copyright 2019 Tomas Machalek <tomas.machalek@gmail.com>
// Copyright 2019 Institute of the Czech National Corpus,
//                Faculty of Arts, Charles University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package calc

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/czcorpus/klogproc/conversion"
)

// LineParser is a parser for reading KonText application logs
type LineParser struct {
}

func (lp *LineParser) ParseLine(s string, lineNum int, localTimezone string) (*InputRecord, error) {
	rec := &InputRecord{}
	err := json.Unmarshal([]byte(s), rec)
	if err != nil {
		return rec, err
	}
	if rec.TS[len(rec.TS)-1] == 'Z' {
		minsChng, err := conversion.TimezoneToInt(localTimezone)
		if err != nil {
			return rec, err
		}
		tm, err := time.Parse("2006-01-02T15:04:05-07:00", rec.TS[:len(rec.TS)-1]+localTimezone)
		fmt.Println("tm1: ", rec.TS)
		if err != nil {
			return rec, err
		}
		tm = tm.Add(time.Minute * time.Duration(minsChng))
		rec.TS = tm.Format("2006-01-02T15:04:05-07:00")
	}
	return rec, nil
}
<|endoftext|>


<commit_before>package kingpin

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

type flagGroup struct {
	short     map[string]*FlagClause
	long      map[string]*FlagClause
	flagOrder []*FlagClause
}

func newFlagGroup() *flagGroup {
	return &flagGroup{
		short: make(map[string]*FlagClause),
		long:  make(map[string]*FlagClause),
	}
}

// Flag defines a new flag with the given long name and help.
func (f *flagGroup) Flag(name, help string) *FlagClause {
	flag := newFlag(name, help)
	f.long[name] = flag
	f.flagOrder = append(f.flagOrder, flag)
	return flag
}

func (f *flagGroup) init() error {
	for _, flag := range f.long {
		if err := flag.init(); err != nil {
			return err
		}
		if flag.shorthand != 0 {
			f.short[string(flag.shorthand)] = flag
		}
	}
	return nil
}

func (f *flagGroup) parse(tokens tokens, ignoreRequired bool) (tokens, error) {
	// Track how many required flags we've seen.
	required := make(map[string]struct{})
	// Keep track of any flags that we need to initialise with defaults.
	defaults := make(map[string]struct{})
	for k, flag := range f.long {
		defaults[k] = struct{}{}
		if !ignoreRequired && flag.needsValue() {
			required[k] = struct{}{}
		}
	}

	var token *token

loop:
	for {
		token, tokens = tokens.Next()
		switch token.Type {
		case TokenEOF:
			break loop

		case TokenLong, TokenShort:
			flagToken := token
			defaultValue := ""
			var flag *FlagClause
			var ok bool
			invert := false

			name := token.Value
			if token.Type == TokenLong {
				if strings.HasPrefix(name, "no-") {
					name = name[3:]
					invert = true
				}
				flag, ok = f.long[name]
				if !ok {
					return nil, fmt.Errorf("unknown long flag '%s'", flagToken)
				}
			} else {
				flag, ok = f.short[name]
				if !ok {
					return nil, fmt.Errorf("unknown short flag '%s", flagToken)
				}
			}

			delete(required, flag.name)
			delete(defaults, flag.name)

			fb, ok := flag.value.(boolFlag)
			if ok && fb.IsBoolFlag() {
				if invert {
					defaultValue = "false"
				} else {
					defaultValue = "true"
				}
			} else {
				if invert {
					return nil, fmt.Errorf("unknown long flag '%s'", flagToken)
				}
				token, tokens = tokens.Next()
				if token.Type != TokenArg {
					return nil, fmt.Errorf("expected argument for flag '%s'", flagToken)
				}
				defaultValue = token.Value
			}

			if err := flag.value.Set(defaultValue); err != nil {
				return nil, err
			}

			if flag.dispatch != nil {
				if err := flag.dispatch(); err != nil {
					return nil, err
				}
			}

		default:
			tokens = tokens.Return(token)
			break loop
		}
	}

	// Check that required flags were provided.
	if len(required) == 1 {
		for k := range required {
			return nil, fmt.Errorf("required flag --%s not provided", k)
		}
	} else if len(required) > 1 {
		flags := make([]string, 0, len(required))
		for k := range required {
			flags = append(flags, "--"+k)
		}
		return nil, fmt.Errorf("required flags %s not provided", strings.Join(flags, ", "))
	}

	// Apply defaults to all unprocessed flags.
	for k := range defaults {
		flag := f.long[k]
		if flag.defaultValue != "" {
			if err := flag.value.Set(flag.defaultValue); err != nil {
				return nil, fmt.Errorf("default value for --%s is invalid: %s", flag.name, err)
			}
		}
	}
	return tokens, nil
}

// FlagClause is a fluid interface used to build flags.
type FlagClause struct {
	parserMixin
	name         string
	shorthand    byte
	help         string
	envar        string
	defaultValue string
	placeholder  string
	dispatch     Dispatch
}

func newFlag(name, help string) *FlagClause {
	f := &FlagClause{
		name: name,
		help: help,
	}
	return f
}

func (f *FlagClause) needsValue() bool {
	return f.required && f.defaultValue == ""
}

func (f *FlagClause) formatPlaceHolder() string {
	if f.placeholder != "" {
		return f.placeholder
	}
	if f.defaultValue != "" {
		if _, ok := f.value.(*stringValue); ok {
			return fmt.Sprintf("%q", f.value)
		}
		return f.value.String()
	}
	return strings.ToUpper(f.name)
}

func (f *FlagClause) init() error {
	if f.required && f.defaultValue != "" {
		return fmt.Errorf("required flag '--%s' with default value that will never be used", f.name)
	}
	if f.value == nil {
		return fmt.Errorf("no value defined for --%s", f.name)
	}
	if f.envar != "" {
		if v := os.Getenv(f.envar); v != "" {
			f.defaultValue = v
		}
	}
	return nil
}

// Dispatch to the given function when the flag is parsed.
func (f *FlagClause) Dispatch(dispatch Dispatch) *FlagClause {
	f.dispatch = dispatch
	return f
}

// Default value for this flag. It *must* be parseable by the value of the flag.
func (f *FlagClause) Default(value string) *FlagClause {
	f.defaultValue = value
	return f
}

// OverrideDefaultFromEnvar overrides the default value for a flag from an
// environment variable, if available.
func (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause {
	f.envar = envar
	return f
}

// PlaceHolder sets the place-holder string used for flag values in the help. The
// default behaviour is to use the value provided by Default() if provided,
// then fall back on the capitalized flag name.
func (f *FlagClause) PlaceHolder(placeholder string) *FlagClause {
	f.placeholder = placeholder
	return f
}

// Required makes the flag required. You can not provide a Default() value to a Required() flag.
func (f *FlagClause) Required() *FlagClause {
	f.required = true
	return f
}

// Short sets the short flag name.
func (f *FlagClause) Short(name byte) *FlagClause {
	f.shorthand = name
	return f
}

// Bool makes this flag a boolean flag.
func (f *FlagClause) Bool() (target *bool) {
	target = new(bool)
	f.SetValue(newBoolValue(false, target))
	return
}
<commit_msg>Print actual default value.<commit_after>package kingpin

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

type flagGroup struct {
	short     map[string]*FlagClause
	long      map[string]*FlagClause
	flagOrder []*FlagClause
}

func newFlagGroup() *flagGroup {
	return &flagGroup{
		short: make(map[string]*FlagClause),
		long:  make(map[string]*FlagClause),
	}
}

// Flag defines a new flag with the given long name and help.
func (f *flagGroup) Flag(name, help string) *FlagClause {
	flag := newFlag(name, help)
	f.long[name] = flag
	f.flagOrder = append(f.flagOrder, flag)
	return flag
}

func (f *flagGroup) init() error {
	for _, flag := range f.long {
		if err := flag.init(); err != nil {
			return err
		}
		if flag.shorthand != 0 {
			f.short[string(flag.shorthand)] = flag
		}
	}
	return nil
}

func (f *flagGroup) parse(tokens tokens, ignoreRequired bool) (tokens, error) {
	// Track how many required flags we've seen.
	required := make(map[string]struct{})
	// Keep track of any flags that we need to initialise with defaults.
	defaults := make(map[string]struct{})
	for k, flag := range f.long {
		defaults[k] = struct{}{}
		if !ignoreRequired && flag.needsValue() {
			required[k] = struct{}{}
		}
	}

	var token *token

loop:
	for {
		token, tokens = tokens.Next()
		switch token.Type {
		case TokenEOF:
			break loop

		case TokenLong, TokenShort:
			flagToken := token
			defaultValue := ""
			var flag *FlagClause
			var ok bool
			invert := false

			name := token.Value
			if token.Type == TokenLong {
				if strings.HasPrefix(name, "no-") {
					name = name[3:]
					invert = true
				}
				flag, ok = f.long[name]
				if !ok {
					return nil, fmt.Errorf("unknown long flag '%s'", flagToken)
				}
			} else {
				flag, ok = f.short[name]
				if !ok {
					return nil, fmt.Errorf("unknown short flag '%s", flagToken)
				}
			}

			delete(required, flag.name)
			delete(defaults, flag.name)

			fb, ok := flag.value.(boolFlag)
			if ok && fb.IsBoolFlag() {
				if invert {
					defaultValue = "false"
				} else {
					defaultValue = "true"
				}
			} else {
				if invert {
					return nil, fmt.Errorf("unknown long flag '%s'", flagToken)
				}
				token, tokens = tokens.Next()
				if token.Type != TokenArg {
					return nil, fmt.Errorf("expected argument for flag '%s'", flagToken)
				}
				defaultValue = token.Value
			}

			if err := flag.value.Set(defaultValue); err != nil {
				return nil, err
			}

			if flag.dispatch != nil {
				if err := flag.dispatch(); err != nil {
					return nil, err
				}
			}

		default:
			tokens = tokens.Return(token)
			break loop
		}
	}

	// Check that required flags were provided.
	if len(required) == 1 {
		for k := range required {
			return nil, fmt.Errorf("required flag --%s not provided", k)
		}
	} else if len(required) > 1 {
		flags := make([]string, 0, len(required))
		for k := range required {
			flags = append(flags, "--"+k)
		}
		return nil, fmt.Errorf("required flags %s not provided", strings.Join(flags, ", "))
	}

	// Apply defaults to all unprocessed flags.
	for k := range defaults {
		flag := f.long[k]
		if flag.defaultValue != "" {
			if err := flag.value.Set(flag.defaultValue); err != nil {
				return nil, fmt.Errorf("default value for --%s is invalid: %s", flag.name, err)
			}
		}
	}
	return tokens, nil
}

// FlagClause is a fluid interface used to build flags.
type FlagClause struct {
	parserMixin
	name         string
	shorthand    byte
	help         string
	envar        string
	defaultValue string
	placeholder  string
	dispatch     Dispatch
}

func newFlag(name, help string) *FlagClause {
	f := &FlagClause{
		name: name,
		help: help,
	}
	return f
}

func (f *FlagClause) needsValue() bool {
	return f.required && f.defaultValue == ""
}

func (f *FlagClause) formatPlaceHolder() string {
	if f.placeholder != "" {
		return f.placeholder
	}
	if f.defaultValue != "" {
		if _, ok := f.value.(*stringValue); ok {
			return fmt.Sprintf("%q", f.defaultValue)
		}
		return f.defaultValue
	}
	return strings.ToUpper(f.name)
}

func (f *FlagClause) init() error {
	if f.required && f.defaultValue != "" {
		return fmt.Errorf("required flag '--%s' with default value that will never be used", f.name)
	}
	if f.value == nil {
		return fmt.Errorf("no value defined for --%s", f.name)
	}
	if f.envar != "" {
		if v := os.Getenv(f.envar); v != "" {
			f.defaultValue = v
		}
	}
	return nil
}

// Dispatch to the given function when the flag is parsed.
func (f *FlagClause) Dispatch(dispatch Dispatch) *FlagClause {
	f.dispatch = dispatch
	return f
}

// Default value for this flag. It *must* be parseable by the value of the flag.
func (f *FlagClause) Default(value string) *FlagClause {
	f.defaultValue = value
	return f
}

// OverrideDefaultFromEnvar overrides the default value for a flag from an
// environment variable, if available.
func (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause {
	f.envar = envar
	return f
}

// PlaceHolder sets the place-holder string used for flag values in the help. The
// default behaviour is to use the value provided by Default() if provided,
// then fall back on the capitalized flag name.
func (f *FlagClause) PlaceHolder(placeholder string) *FlagClause {
	f.placeholder = placeholder
	return f
}

// Required makes the flag required. You can not provide a Default() value to a Required() flag.
func (f *FlagClause) Required() *FlagClause {
	f.required = true
	return f
}

// Short sets the short flag name.
func (f *FlagClause) Short(name byte) *FlagClause {
	f.shorthand = name
	return f
}

// Bool makes this flag a boolean flag.
func (f *FlagClause) Bool() (target *bool) {
	target = new(bool)
	f.SetValue(newBoolValue(false, target))
	return
}
<|endoftext|>


<commit_before>package notifier

import (
	log "github.com/Sirupsen/logrus"
	"github.com/eternnoir/gmrn/apis"
	"strconv"
	"time"
)

func InitGitLabNotifier(url, token string, projects []string, pollingInterval, notifyInterval time.Duration) *GitLabNotifier {
	gitlab := GitLabNotifier{}
	gitlab.Url = url
	gitlab.Token = token
	gitlab.Projects = projects
	gitlab.PollingInterval = pollingInterval
	gitlab.NotifyInterval = notifyInterval
	gitlab.NotifyRunners = []NotifyRunner{}
	gitlab.Api = apis.InitGitlabApi(url, token)
	gitlab.MRLastNotifyTime = make(map[string]time.Time)
	log.Infof("Init GitLabNotifier. Url:%s , Toke:%s, %d projects.", url, token, len(projects))
	return &gitlab
}

type GitLabNotifier struct {
	Url              string
	Token            string
	Projects         []string
	PollingInterval  time.Duration
	NotifyInterval   time.Duration
	Api              *apis.GitLabApi
	NotifyRunners    []NotifyRunner
	MRLastNotifyTime map[string]time.Time
}

func (notifier *GitLabNotifier) Run() {

	notifier.checkProjects()
	//  loops forever to polling merge request.
	for {
		err := notifier.notifyForMergeRequest()
		if err != nil {
			log.Error(err)
		}
		time.Sleep(notifier.PollingInterval)
	}
}
func (notifier *GitLabNotifier) AppendNotifyRunner(runner NotifyRunner) {
	log.Infof("Append Runner %#v", runner)
	notifier.NotifyRunners = append(notifier.NotifyRunners, runner)
}

func (notifier *GitLabNotifier) notifyForMergeRequest() error {
	allMrs, err := notifier.getAllProjectsMr()
	if err != nil {
		log.Error(err)
		return err
	}
	log.Infof("Get %d Merge Requests", len(allMrs))
	for _, mr := range allMrs {
		go notifier.triggerNitifyCommand(mr)
	}
	return nil
}

func (notifier *GitLabNotifier) triggerNitifyCommand(mr *apis.MergeRequest) {
	if mr.WorkInProgress {
		log.Debugf("%s Merge Reques is WorkInProgress. Do not need to notify.", mr.Title)
		return
	}
	uumrid := strconv.Itoa(int(mr.ProjectId)) + ":" + strconv.Itoa(int(mr.Id))
	if val, ok := notifier.MRLastNotifyTime[uumrid]; ok {
		if time.Now().Before(val.Add(notifier.NotifyInterval)) {
			// Do not need to run notify command.
			log.Debugf("Do not need to run notify command for %s", mr.Title)
			return
		}
	}
	log.Infof("Trigger command for %s", mr.Title)
	notifier.MRLastNotifyTime[uumrid] = time.Now()
	notifier.runNotifyCommand(mr)

}

func (notifier *GitLabNotifier) runNotifyCommand(mr *apis.MergeRequest) {
	mrerr := mr.GetProjectInfo(notifier.Api)
	if mrerr != nil {
		log.Errorf("Try to get merge request's project detial [FAIL]. %#v", mr)
		return
	}

	for _, nr := range notifier.NotifyRunners {
		log.Infof("Start Trigger NotifyRunner %#v", nr)
		err := nr.Trigger(mr)
		if err != nil {
			log.Errorf("Trigger NotifyRunner %#v [FAIL]", nr)
		}
		log.Infof("Tirgger NotifyRunner %#v  [Success].", nr)
	}
}

func (notifier *GitLabNotifier) getAllProjectsMr() ([]*apis.MergeRequest, error) {
	var mrs []*apis.MergeRequest
	for _, projectId := range notifier.Projects {
		resultmrs, err := notifier.Api.GetMergeRequests(projectId, "opened")
		if err != nil {
			log.Error(err)
			return nil, err
		}
		mrs = append(mrs, resultmrs...)
	}
	return mrs, nil
}

// checkProjects is check notifier's projects is exist or not.
// If projects is empty, It will set all project to project list.
func (notifier *GitLabNotifier) checkProjects() error {
	if len(notifier.Projects) < 1 {
		log.Infof("Notifier' project is empty. Load all projects from gitlab.")
		err := notifier.setAllProjectId()
		if err != nil {
			return err
		}
		log.Infof("%d projects loaded.", len(notifier.Projects))
	}
	return nil
}

func (notifier *GitLabNotifier) setAllProjectId() error {
	projects, err := notifier.Api.GetProjects()
	if err != nil {
		log.Error(err)
		return err
	}
	for _, project := range projects {
		notifier.Projects = append(notifier.Projects, project.PathWithNamespace)
	}
	return nil
}
<commit_msg>Fix typo.<commit_after>package notifier

import (
	log "github.com/Sirupsen/logrus"
	"github.com/eternnoir/gmrn/apis"
	"strconv"
	"time"
)

func InitGitLabNotifier(url, token string, projects []string, pollingInterval, notifyInterval time.Duration) *GitLabNotifier {
	gitlab := GitLabNotifier{}
	gitlab.Url = url
	gitlab.Token = token
	gitlab.Projects = projects
	gitlab.PollingInterval = pollingInterval
	gitlab.NotifyInterval = notifyInterval
	gitlab.NotifyRunners = []NotifyRunner{}
	gitlab.Api = apis.InitGitlabApi(url, token)
	gitlab.MRLastNotifyTime = make(map[string]time.Time)
	log.Infof("Init GitLabNotifier. Url:%s , Toke:%s, %d projects.", url, token, len(projects))
	return &gitlab
}

type GitLabNotifier struct {
	Url              string
	Token            string
	Projects         []string
	PollingInterval  time.Duration
	NotifyInterval   time.Duration
	Api              *apis.GitLabApi
	NotifyRunners    []NotifyRunner
	MRLastNotifyTime map[string]time.Time
}

func (notifier *GitLabNotifier) Run() {

	notifier.checkProjects()
	//  loops forever to polling merge request.
	for {
		err := notifier.notifyForMergeRequest()
		if err != nil {
			log.Error(err)
		}
		time.Sleep(notifier.PollingInterval)
	}
}
func (notifier *GitLabNotifier) AppendNotifyRunner(runner NotifyRunner) {
	log.Infof("Append Runner %#v", runner)
	notifier.NotifyRunners = append(notifier.NotifyRunners, runner)
}

func (notifier *GitLabNotifier) notifyForMergeRequest() error {
	allMrs, err := notifier.GetAllProjectsMr()
	if err != nil {
		log.Error(err)
		return err
	}
	log.Infof("Get %d Merge Requests", len(allMrs))
	for _, mr := range allMrs {
		go notifier.triggerNotifyCommand(mr)
	}
	return nil
}

func (notifier *GitLabNotifier) triggerNotifyCommand(mr *apis.MergeRequest) {
	if mr.WorkInProgress {
		log.Debugf("%s Merge Reques is WorkInProgress. Do not need to notify.", mr.Title)
		return
	}
	uumrid := strconv.Itoa(int(mr.ProjectId)) + ":" + strconv.Itoa(int(mr.Id))
	if val, ok := notifier.MRLastNotifyTime[uumrid]; ok {
		if time.Now().Before(val.Add(notifier.NotifyInterval)) {
			// Do not need to run notify command.
			log.Debugf("Do not need to run notify command for %s", mr.Title)
			return
		}
	}
	log.Infof("Trigger command for %s", mr.Title)
	notifier.MRLastNotifyTime[uumrid] = time.Now()
	notifier.runNotifyCommand(mr)

}

func (notifier *GitLabNotifier) runNotifyCommand(mr *apis.MergeRequest) {
	mrerr := mr.GetProjectInfo(notifier.Api)
	if mrerr != nil {
		log.Errorf("Try to get merge request's project detial [FAIL]. %#v", mr)
		return
	}

	for _, nr := range notifier.NotifyRunners {
		log.Infof("Start Trigger NotifyRunner %#v", nr)
		err := nr.Trigger(mr)
		if err != nil {
			log.Errorf("Trigger NotifyRunner %#v [FAIL]", nr)
		}
		log.Infof("Tirgger NotifyRunner %#v  [Success].", nr)
	}
}

func (notifier *GitLabNotifier) GetAllProjectsMr() ([]*apis.MergeRequest, error) {
	var mrs []*apis.MergeRequest
	for _, projectId := range notifier.Projects {
		resultmrs, err := notifier.Api.GetMergeRequests(projectId, "opened")
		if err != nil {
			log.Error(err)
			return nil, err
		}
		mrs = append(mrs, resultmrs...)
	}
	return mrs, nil
}

// checkProjects is check notifier's projects is exist or not.
// If projects is empty, It will set all project to project list.
func (notifier *GitLabNotifier) checkProjects() error {
	if len(notifier.Projects) < 1 {
		log.Infof("Notifier' project is empty. Load all projects from gitlab.")
		err := notifier.setAllProjectId()
		if err != nil {
			return err
		}
		log.Infof("%d projects loaded.", len(notifier.Projects))
	}
	return nil
}

func (notifier *GitLabNotifier) setAllProjectId() error {
	projects, err := notifier.Api.GetProjects()
	if err != nil {
		log.Error(err)
		return err
	}
	for _, project := range projects {
		notifier.Projects = append(notifier.Projects, project.PathWithNamespace)
	}
	return nil
}
<|endoftext|>


<commit_before>/*
Package flect is a new inflection engine to replace [https://github.com/markbates/inflect](https://github.com/markbates/inflect) designed to be more modular, more readable, and easier to fix issues on than the original.
*/
package flect

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"unicode"
)

func init() {
	pwd, _ := os.Getwd()
	cfg := filepath.Join(pwd, "inflections.json")
	if p := os.Getenv("INFLECT_PATH"); p != "" {
		cfg = p
	}
	if _, err := os.Stat(cfg); err == nil {
		b, err := ioutil.ReadFile(cfg)
		if err != nil {
			fmt.Printf("could not read inflection file %s (%s)\n", cfg, err)
			return
		}
		if err = LoadReader(bytes.NewReader(b)); err != nil {
			fmt.Println(err)
		}
	}
}

//LoadReader loads rules from io.Reader param
func LoadReader(r io.Reader) error {
	m := map[string]interface{}{}

	err := json.NewDecoder(r).Decode(&m)
	if err != nil {
		return fmt.Errorf("could not decode inflection JSON from reader: %s", err)
	}
	pluralMoot.Lock()
	defer pluralMoot.Unlock()
	singularMoot.Lock()
	defer singularMoot.Unlock()

	for s, p := range m {
		if ps, ok := p.(string); ok {
			singleToPlural[s] = ps
			pluralToSingle[ps] = s
		}

		if pa, ok := p.([]interface{}); ok && s == "_acronyms" {
			for _, acronym := range pa {
				key := (acronym).(string)
				baseAcronyms[key] = true
			}
		}

	}

	return nil
}

var spaces = []rune{'_', ' ', ':', '-', '/'}

func isSpace(c rune) bool {
	for _, r := range spaces {
		if r == c {
			return true
		}
	}
	return unicode.IsSpace(c)
}

func xappend(a []string, ss ...string) []string {
	for _, s := range ss {
		s = strings.TrimSpace(s)
		for _, x := range spaces {
			s = strings.Trim(s, string(x))
		}
		if _, ok := baseAcronyms[strings.ToUpper(s)]; ok {
			s = strings.ToUpper(s)
		}
		if s != "" {
			a = append(a, s)
		}
	}
	return a
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
<commit_msg>moving acronyms key to a constant<commit_after>/*
Package flect is a new inflection engine to replace [https://github.com/markbates/inflect](https://github.com/markbates/inflect) designed to be more modular, more readable, and easier to fix issues on than the original.
*/
package flect

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"unicode"
)

const (
	//acronymsKey is the key we use to get acronyms from the inflections file
	//p.e:
	// #inflections.json
	// {
	// 	"house":"houses",
	// 	"_acronyms": ["TSA", "LSA"]
	// }
	acronymsKey = "_acronyms"
)

func init() {
	pwd, _ := os.Getwd()
	cfg := filepath.Join(pwd, "inflections.json")
	if p := os.Getenv("INFLECT_PATH"); p != "" {
		cfg = p
	}
	if _, err := os.Stat(cfg); err == nil {
		b, err := ioutil.ReadFile(cfg)
		if err != nil {
			fmt.Printf("could not read inflection file %s (%s)\n", cfg, err)
			return
		}
		if err = LoadReader(bytes.NewReader(b)); err != nil {
			fmt.Println(err)
		}
	}
}

//LoadReader loads rules from io.Reader param
func LoadReader(r io.Reader) error {
	m := map[string]interface{}{}

	err := json.NewDecoder(r).Decode(&m)
	if err != nil {
		return fmt.Errorf("could not decode inflection JSON from reader: %s", err)
	}
	pluralMoot.Lock()
	defer pluralMoot.Unlock()
	singularMoot.Lock()
	defer singularMoot.Unlock()

	for s, p := range m {
		if ps, ok := p.(string); ok {
			singleToPlural[s] = ps
			pluralToSingle[ps] = s
		}

		if pa, ok := p.([]interface{}); ok && s == acronymsKey {
			for _, acronym := range pa {
				key := (acronym).(string)
				baseAcronyms[key] = true
			}
		}

	}

	return nil
}

var spaces = []rune{'_', ' ', ':', '-', '/'}

func isSpace(c rune) bool {
	for _, r := range spaces {
		if r == c {
			return true
		}
	}
	return unicode.IsSpace(c)
}

func xappend(a []string, ss ...string) []string {
	for _, s := range ss {
		s = strings.TrimSpace(s)
		for _, x := range spaces {
			s = strings.Trim(s, string(x))
		}
		if _, ok := baseAcronyms[strings.ToUpper(s)]; ok {
			s = strings.ToUpper(s)
		}
		if s != "" {
			a = append(a, s)
		}
	}
	return a
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
<|endoftext|>


<commit_before>/*
Copyright 2016 IBM

Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Licensed Materials - Property of IBM
© Copyright IBM Corp. 2016
*/
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"time"
    "strings"

	"github.com/openblockchain/obc-peer/openchain/chaincode/shim"
)

var cpPrefix = "cp:"
var accountPrefix = "acct:"
var accountsKey = "accounts"

var recentLeapYear = 2016

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

func generateCUSIPSuffix(issueDate string, days int) (string, error) {

	t, err := msToTime(issueDate)
	if err != nil {
		return "", err
	}

	maturityDate := t.AddDate(0, 0, days)
	month := int(maturityDate.Month())
	day := maturityDate.Day()

	suffix := seventhDigit[month] + eigthDigit[day]
	return suffix, nil

}

const (
	millisPerSecond     = int64(time.Second / time.Millisecond)
	nanosPerMillisecond = int64(time.Millisecond / time.Nanosecond)
)

func msToTime(ms string) (time.Time, error) {
	msInt, err := strconv.ParseInt(ms, 10, 64)
	if err != nil {
		return time.Time{}, err
	}

	return time.Unix(msInt/millisPerSecond,
		(msInt%millisPerSecond)*nanosPerMillisecond), nil
}

type Owner struct {
	Company string    `json:"company"`
	Quantity int      `json:"quantity"`
}

type CP struct {
	CUSIP     string  `json:"cusip"`
	Ticker    string  `json:"ticker"`
	Par       float64 `json:"par"`
	Qty       int     `json:"qty"`
	Discount  float64 `json:"discount"`
	Maturity  int     `json:"maturity"`
	Owners    []Owner `json:"owner"`
	Issuer    string  `json:"issuer"`
	IssueDate string  `json:"issueDate"`
}

type Account struct {
	ID          string  `json:"id"`
	Prefix      string  `json:"prefix"`
	CashBalance float64 `json:"cashBalance"`
	AssetsIds   []string `json:"assetIds"`
}

type Transaction struct {
	CUSIP       string   `json:"cusip"`
	FromCompany string   `json:"fromCompany"`
	ToCompany   string   `json:"toCompany"`
	Quantity    int      `json:"quantity"`
	Discount    float64  `json:"discount"`
}

func (t *SimpleChaincode) init(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
    // Initialize the collection of commercial paper keys
    fmt.Println("Initializing paper keys collection")
	var blank []string
	blankBytes, _ := json.Marshal(&blank)
	err := stub.PutState("PaperKeys", blankBytes)
    if err != nil {
        fmt.Println("Failed to initialize paper key collection")
    }

	fmt.Println("Initialization complete")
	return nil, nil
}

func (t *SimpleChaincode) createAccounts(stub *shim.ChaincodeStub, args []string) ([]byte, error) {

	//  				0
	// "number of accounts to create"
	var err error
	numAccounts, err := strconv.Atoi(args[0])
	if err != nil {
		fmt.Println("error creating accounts with input")
		return nil, errors.New("createAccounts accepts a single integer argument")
	}
	//create a bunch of accounts
	var account Account
	counter := 1
	for counter <= numAccounts {
		var prefix string
		suffix := "000A"
		if counter < 10 {
			prefix = strconv.Itoa(counter) + "0" + suffix
		} else {
			prefix = strconv.Itoa(counter) + suffix
		}
		var assetIds []string
		account = Account{ID: "company" + strconv.Itoa(counter), Prefix: prefix, CashBalance: 10000000.0, AssetsIds: assetIds}
		accountBytes, err := json.Marshal(&account)
		if err != nil {
			fmt.Println("error creating account" + account.ID)
			return nil, errors.New("Error creating account " + account.ID)
		}
		err = stub.PutState(accountPrefix+account.ID, accountBytes)
		counter++
		fmt.Println("created account" + accountPrefix + account.ID)
	}

	fmt.Println("Accounts created")
	return nil, nil

}

func (t *SimpleChaincode) createAccount(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
    // Obtain the username to associate with the account
    if len(args) != 1 {
        fmt.Println("Error obtaining username")
        return nil, errors.New("createAccount accepts a single username argument")
    }
    username := args[0]

    // Build an account object for the user
    var assetIds []string
    suffix := "000A"
    prefix := username + suffix
    var account = Account{ID: username, Prefix: prefix, CashBalance: 10000000.0, AssetsIds: assetIds}
    accountBytes, err := json.Marshal(&account)
    if err != nil {
        fmt.Println("error creating account" + account.ID)
        return nil, errors.New("Error creating account " + account.ID)
    }

    fmt.Println("Attempting to get state of any existing account for " + account.ID)
    existingBytes, err := stub.GetState(accountPrefix + account.ID)
	if err == nil {

        var company Account
        err = json.Unmarshal(existingBytes, &company)
        if err != nil {
            fmt.Println("Error unmarshalling account " + account.ID + "\n--->: " + err.Error())

            if strings.Contains(err.Error(), "unexpected end") {
                fmt.Println("No data means existing account found for " + account.ID + ", initializing account.")
                err = stub.PutState(accountPrefix+account.ID, accountBytes)

                if err == nil {
                    fmt.Println("created account" + accountPrefix + account.ID)
                    return nil, nil
                } else {
                    fmt.Println("failed to create initialize account for " + account.ID)
                    return nil, errors.New("failed to initialize an account for " + account.ID + " => " + err.Error())
                }
            } else {
                return nil, errors.New("Error unmarshalling existing account " + account.ID)
            }
        } else {
            fmt.Println("Account already exists for " + account.ID + " " + company.ID)
		    return nil, errors.New("Can't reinitialize existing user " + account.ID)
        }
    } else {

        fmt.Println("No existing account found for " + account.ID + ", initializing account.")
        err = stub.PutState(accountPrefix+account.ID, accountBytes)

        if err == nil {
            fmt.Println("created account" + accountPrefix + account.ID)
            return nil, nil
        } else {
            fmt.Println("failed to create initialize account for " + account.ID)
            return nil, errors.New("failed to initialize an account for " + account.ID + " => " + err.Error())
        }

    }

}

func (t *SimpleChaincode) issueCommercialPaper(stub *shim.ChaincodeStub, args []string) ([]byte, error) {

	/*		0
		json
	  	{
			"ticker":  "string",
			"par": 0.00,
			"qty": 10,
			"discount": 7.5,
			"maturity": 30,
			"owners": [ // This one is not required
				{
					"company": "company1",
					"quantity": 5
				},
				{
					"company": "company3",
					"quantity": 3
				},
				{
					"company": "company4",
					"quantity": 2
				}
			],
			"issuer":"company2",
			"issueDate":"1456161763790"  (current time in milliseconds as a string)

		}
	*/
	//need one arg
	if len(args) != 1 {
		fmt.Println("error invalid arguments")
		return nil, errors.New("Incorrect number of arguments. Expecting commercial paper record")
	}

	var cp CP
	var err error
	var account Account

	fmt.Println("Unmarshalling CP")
	err = json.Unmarshal([]byte(args[0]), &cp)
	if err != nil {
		fmt.Println("error invalid paper issue")
		return nil, errors.New("Invalid commercial paper issue")
	}

	//generate the CUSIP
	//get account prefix
	fmt.Println("Getting state of - " + accountPrefix + cp.Issuer)
	accountBytes, err := stub.GetState(accountPrefix + cp.Issuer)
	if err != nil {
		fmt.Println("Error Getting state of - " + accountPrefix + cp.Issuer)
		return nil, errors.New("Error retrieving account " + cp.Issuer)
	}
	err = json.Unmarshal(accountBytes, &account)
	if err != nil {
		fmt.Println("Error Unmarshalling accountBytes")
		return nil, errors.New("Error retrieving account " + cp.Issuer)
	}

	account.AssetsIds = append(account.AssetsIds, cp.CUSIP)

	// Set the issuer to be the owner of all quantity
	var owner Owner
	owner.Company = cp.Issuer
	owner.Quantity = cp.Qty

	cp.Owners = append(cp.Owners, owner)

	suffix, err := generateCUSIPSuffix(cp.IssueDate, cp.Maturity)
	if err != nil {
		fmt.Println("Error generating cusip")
		return nil, errors.New("Error generating CUSIP")
	}

	fmt.Println("Marshalling CP bytes")
	cp.CUSIP = account.Prefix + suffix

	fmt.Println("Getting State on CP " + cp.CUSIP)
	cpRxBytes, err := stub.GetState(cpPrefix+cp.CUSIP)
	if cpRxBytes == nil {
		fmt.Println("CUSIP does not exist, creating it")
		cpBytes, err := json.Marshal(&cp)
		if err != nil {
			fmt.Println("Error marshalling cp")
			return nil, errors.New("Error issuing commercial paper")
		}
		err = stub.PutState(cpPrefix+cp.CUSIP, cpBytes)
		if err != nil {
			fmt.Println("Error issuing paper")
			return nil, errors.New("Error issuing commercial paper")
		}

		fmt.Println("Marshalling account bytes to write")
		accountBytesToWrite, err := json.Marshal(&account)
		if err != nil {
			fmt.Println("Error marshalling account")
			return nil, errors.New("Error issuing commercial paper")
		}
		err = stub.PutState(accountPrefix + cp.Issuer, accountBytesToWrite)
		if err != nil {
			fmt.Println("Error putting state on accountBytesToWrite")
			return nil, errors.New("Error issuing commercial paper")
		}

		// Update the paper keys by adding the new key
		fmt.Println("Getting Paper Keys")
		keysBytes, err := stub.GetState("PaperKeys")
		if err != nil {
			fmt.Println("Error retrieving paper keys")
			return nil, errors.New("Error retrieving paper keys")
		}
		var keys []string
		err = json.Unmarshal(keysBytes, &keys)
		if err != nil {
			fmt.Println("Error unmarshel keys")
			return nil, errors.New("Error unmarshalling paper keys ")
		}

		fmt.Println("Appending the new key to Paper Keys")
		foundKey := false
		for _, key := range keys {
			if key == cpPrefix+cp.CUSIP {
				foundKey = true
			}
		}
		if foundKey == false {
			keys = append(keys, cpPrefix+cp.CUSIP)
			keysBytesToWrite, err := json.Marshal(&keys)
			if err != nil {
				fmt.Println("Error marshalling keys")
				return nil, errors.New("Error marshalling the keys")
			}
			fmt.Println("Put state on PaperKeys")
			err = stub.PutState("PaperKeys", keysBytesToWrite)
			if err != nil {
				fmt.Println("Error writting keys back")
				return nil, errors.New("Error writing the keys back")
			}
		}

		fmt.Println("Issue commercial paper %+v\n", cp)
		return nil, nil
	} else {
		fmt.Println("CUSIP exists")

		var cprx CP
		fmt.Println("Unmarshalling CP " + cp.CUSIP)
		err = json.Unmarshal(cpRxBytes, &cprx)
		if err != nil {
			fmt.Println("Error unmarshalling cp " + cp.CUSIP)
			return nil, errors.New("Error unmarshalling cp " + cp.CUSIP)
		}

		cprx.Qty = cprx.Qty + cp.Qty

		for key, val := range cprx.Owners {
			if val.Company == cp.Issuer {
				cprx.Owners[key].Quantity += cp.Qty
				break
			}
		}

		cpWriteBytes, err := json.Marshal(&cprx)
		if err != nil {
			fmt.Println("Error marshalling cp")
			return nil, errors.New("Error issuing commercial paper")
		}
		err = stub.PutState(cpPrefix+cp.CUSIP, cpWriteBytes)
		if err != nil {
			fmt.Println("Error issuing paper")
			return nil, errors.New("Error issuing commercial paper")
		}

		fmt.Println("Updated commercial paper %+v\n", cprx)
		return nil, nil
	}
}

func GetAllCPs(stub *shim.ChaincodeStub) ([]CP, error){

	var allCPs []CP

	// Get list of all the keys
	keysBytes, err := stub.GetState("PaperKeys")
	if err != nil {
		fmt.Println("Error retrieving paper keys")
		return nil, errors.New("Error retrieving paper keys")
	}
	var keys []string
	err = json.Unmarshal(keysBytes, &keys)
	if err != nil {
		fmt.Println("Error unmarshalling paper keys")
		return nil, errors.New("Error unmarshalling paper keys")
	}

	// Get all the cps
	for _, value := range keys {
		cpBytes, err := stub.GetState(value)

		var cp CP
		err = json.Unmarshal(cpBytes, &cp)
		if err != nil {
			fmt.Println("Error retrieving cp " + value)
			return nil, errors.New("Error retrieving cp " + value)
		}

		fmt.Println("Appending CP" + value)
		allCPs = append(allCPs, cp)
	}

	return allCPs, nil
}

func GetCP(cpid string, stub *shim.ChaincodeStub) (CP, error){
	var cp CP

	cpBytes, err := stub.GetState(cpid)
	if err != nil {
		fmt.Println("Error retrieving cp " + cpid)
		return cp, errors.New("Error retrieving cp " + cpid)
	}

	err = json.Unmarshal(cpBytes, &cp)
	if err != nil {
		fmt.Println("Error unmarshalling cp " + cpid)
		return cp, errors.New("Error unmarshalling cp " + cpid)
	}

	return cp, nil
}

func GetCompany(companyID string, stub *shim.ChaincodeStub) (Account, error){
	var company Account
	companyBytes, err := stub.GetState(accountPrefix+companyID)
	if err != nil {
		fmt.Println("Account not found " + companyID)
		return company, errors.New("Account not found " + companyID)
	}

	err = json.Unmarshal(companyBytes, &company)
	if err != nil {
		fmt.Println("Error unmarshalling account " + companyID + "\n err:" + err.Error())
		return company, errors.New("Error unmarshalling account " + companyID)
	}

	return company, nil
}

// Still working on this one
func (t *SimpleChaincode) transferPaper(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	/*		0
		json
	  	{
			  "CUSIP": "",
			  "fromCompany":"",
			  "toCompany":"",
			  "quantity": 1
		}
	*/
	//need one arg
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting commercial paper record")
	}

	var tr Transaction

	fmt.Println("Unmarshalling Transaction")
	err := json.Unmarshal([]byte(args[0]), &tr)
	if err != nil {
		fmt.Println("Error Unmarshalling Transaction")
		return nil, errors.New("Invalid commercial paper issue")
	}

	fmt.Println("Getting State on CP " + tr.CUSIP)
	cpBytes, err := stub.GetState(cpPrefix+tr.CUSIP)
	if err != nil {
		fmt.Println("CUSIP not found")
		return nil, errors.New("CUSIP not found " + tr.CUSIP)
	}

	var cp CP
	fmt.Println("Unmarshalling CP " + tr.CUSIP)
	err = json.Unmarshal(cpBytes, &cp)
	if err != nil {
		fmt.Println("Error unmarshalling cp " + tr.CUSIP)
		return nil, errors.New("Error unmarshalling cp " + tr.CUSIP)
	}

	var fromCompany Account
	fmt.Println("Getting State on fromCompany " + tr.FromCompany)
	fromCompanyBytes, err := stub.GetState(accountPrefix+tr.FromCompany)
	if err != nil {
		fmt.Println("Account not found " + tr.FromCompany)
		return nil, errors.New("Account not found " + tr.FromCompany)
	}

	fmt.Println("Unmarshalling FromCompany ")
	err = json.Unmarshal(fromCompanyBytes, &fromCompany)
	if err != nil {
		fmt.Println("Error unmarshalling account " + tr.FromCompany)
		return nil, errors.New("Error unmarshalling account " + tr.FromCompany)
	}

	var toCompany Account
	fmt.Println("Getting State on ToCompany " + tr.ToCompany)
	toCompanyBytes, err := stub.GetState(accountPrefix+tr.ToCompany)
	if err != nil {
		fmt.Println("Account not found " + tr.ToCompany)
		return nil, errors.New("Account not found " + tr.ToCompany)
	}

	fmt.Println("Unmarshalling tocompany")
	err = json.Unmarshal(toCompanyBytes, &toCompany)
	if err != nil {
		fmt.Println("Error unmarshalling account " + tr.ToCompany)
		return nil, errors.New("Error unmarshalling account " + tr.ToCompany)
	}

	// Check for all the possible errors
	ownerFound := false
	quantity := 0
	for _, owner := range cp.Owners {
		if owner.Company == tr.FromCompany {
			ownerFound = true
			quantity = owner.Quantity
		}
	}

	// If fromCompany doesn't own this paper
	if ownerFound == false {
		fmt.Println("The company " + tr.FromCompany + "doesn't own any of this paper")
		return nil, errors.New("The company " + tr.FromCompany + "doesn't own any of this paper")
	} else {
		fmt.Println("The FromCompany does own this paper")
	}

	// If fromCompany doesn't own enough quantity of this paper
	if quantity < tr.Quantity {
		fmt.Println("The company " + tr.FromCompany + "doesn't own enough of this paper")
		return nil, errors.New("The company " + tr.FromCompany + "doesn't own enough of this paper")
	} else {
		fmt.Println("The FromCompany owns enough of this paper")
	}

	amountToBeTransferred := float64(tr.Quantity) * cp.Par
	amountToBeTransferred -= (amountToBeTransferred) * (cp.Discount / 100.0) * (float64(cp.Maturity) / 360.0)

	// If toCompany doesn't have enough cash to buy the papers
	if toCompany.CashBalance < amountToBeTransferred {
		fmt.Println("The company " + tr.ToCompany + "doesn't have enough cash to purchase the papers")
		return nil, errors.New("The company " + tr.ToCompany + "doesn't have enough cash to purchase the papers")
	} else {
		fmt.Println("The ToCompany has enough money to be transferred for this paper")
	}

	toCompany.CashBalance -= amountToBeTransferred
	fromCompany.CashBalance += amountToBeTransferred

	toOwnerFound := false
	for key, owner := range cp.Owners {
		if owner.Company == tr.FromCompany {
			fmt.Println("Reducing Quantity from the FromCompany")
			cp.Owners[key].Quantity -= tr.Quantity
//			owner.Quantity -= tr.Quantity
		}
		if owner.Company == tr.ToCompany {
			fmt.Println("Increasing Quantity from the ToCompany")
			toOwnerFound = true
			cp.Owners[key].Quantity += tr.Quantity
//			owner.Quantity += tr.Quantity
		}
	}

	if toOwnerFound == false {
		var newOwner Owner
		fmt.Println("As ToOwner was not found, appending the owner to the CP")
		newOwner.Quantity = tr.Quantity
		newOwner.Company = tr.ToCompany
		cp.Owners = append(cp.Owners, newOwner)
	}

	fromCompany.AssetsIds = append(fromCompany.AssetsIds, tr.CUSIP)

	// Write everything back
	// To Company
	toCompanyBytesToWrite, err := json.Marshal(&toCompany)
	if err != nil {
		fmt.Println("Error marshalling the toCompany")
		return nil, errors.New("Error marshalling the toCompany")
	}
	fmt.Println("Put state on toCompany")
	err = stub.PutState(accountPrefix+tr.ToCompany, toCompanyBytesToWrite)
	if err != nil {
		fmt.Println("Error writing the toCompany back")
		return nil, errors.New("Error writing the toCompany back")
	}

	// From company
	fromCompanyBytesToWrite, err := json.Marshal(&fromCompany)
	if err != nil {
		fmt.Println("Error marshalling the fromCompany")
		return nil, errors.New("Error marshalling the fromCompany")
	}
	fmt.Println("Put state on fromCompany")
	err = stub.PutState(accountPrefix+tr.FromCompany, fromCompanyBytesToWrite)
	if err != nil {
		fmt.Println("Error writing the fromCompany back")
		return nil, errors.New("Error writing the fromCompany back")
	}

	// cp
	cpBytesToWrite, err := json.Marshal(&cp)
	if err != nil {
		fmt.Println("Error marshalling the cp")
		return nil, errors.New("Error marshalling the cp")
	}
	fmt.Println("Put state on CP")
	err = stub.PutState(cpPrefix+tr.CUSIP, cpBytesToWrite)
	if err != nil {
		fmt.Println("Error writing the cp back")
		return nil, errors.New("Error writing the cp back")
	}

	fmt.Println("Successfully completed Invoke")
	return nil, nil
}

func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	//need one arg
	if len(args) < 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting ......")
	}

	if args[0] == "GetAllCPs" {
		fmt.Println("Getting all CPs")
		allCPs, err := GetAllCPs(stub)
		if err != nil {
			fmt.Println("Error from getallcps")
			return nil, err
		} else {
			allCPsBytes, err1 := json.Marshal(&allCPs)
			if err1 != nil {
				fmt.Println("Error marshalling allcps")
				return nil, err1
			}
			fmt.Println("All success, returning allcps")
			return allCPsBytes, nil
		}
	} else if args[0] == "GetCP" {
		fmt.Println("Getting particular cp")
		cp, err := GetCP(args[1], stub)
		if err != nil {
			fmt.Println("Error Getting particular cp")
			return nil, err
		} else {
			cpBytes, err1 := json.Marshal(&cp)
			if err1 != nil {
				fmt.Println("Error marshalling the cp")
				return nil, err1
			}
			fmt.Println("All success, returning the cp")
			return cpBytes, nil
		}
	} else if args[0] == "GetCompany" {
		fmt.Println("Getting the company")
		company, err := GetCompany(args[1], stub)
		if err != nil {
			fmt.Println("Error from getCompany")
			return nil, err
		} else {
			companyBytes, err1 := json.Marshal(&company)
			if err1 != nil {
				fmt.Println("Error marshalling the company")
				return nil, err1
			}
			fmt.Println("All success, returning the company")
			return companyBytes, nil
		}
	} else {
		fmt.Println("Generic Query call")
		bytes, err := stub.GetState(args[0])

		if err != nil {
			fmt.Println("Some error happenend")
			return nil, errors.New("Some Error happened")
		}

		fmt.Println("All success, returning from generic")
		return bytes, nil
	}
}

func (t *SimpleChaincode) Run(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	fmt.Println("run is running " + function)

	if function == "issueCommercialPaper" {
		fmt.Println("Firing issueCommercialPaper")
		//Create an asset with some value
		return t.issueCommercialPaper(stub, args)
	} else if function == "transferPaper" {
		fmt.Println("Firing cretransferPaperateAccounts")
		return t.transferPaper(stub, args)
	} else if function == "createAccounts" {
		fmt.Println("Firing createAccounts")
		return t.createAccounts(stub, args)
	} else if function == "createAccount" {
        fmt.Println("Firing createAccount")
        return t.createAccount(stub, args)
    } else if function == "init" {
        fmt.Println("Firing init")
        return t.init(stub, args)
    }

	return nil, errors.New("Received unknown function invocation")
}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Println("Error starting Simple chaincode: %s", err)
	}
}

//lookup tables for last two digits of CUSIP
var seventhDigit = map[int]string{
	1:  "A",
	2:  "B",
	3:  "C",
	4:  "D",
	5:  "E",
	6:  "F",
	7:  "G",
	8:  "H",
	9:  "J",
	10: "K",
	11: "L",
	12: "M",
	13: "N",
	14: "P",
	15: "Q",
	16: "R",
	17: "S",
	18: "T",
	19: "U",
	20: "V",
	21: "W",
	22: "X",
	23: "Y",
	24: "Z",
}

var eigthDigit = map[int]string{
	1:  "1",
	2:  "2",
	3:  "3",
	4:  "4",
	5:  "5",
	6:  "6",
	7:  "7",
	8:  "8",
	9:  "9",
	10: "A",
	11: "B",
	12: "C",
	13: "D",
	14: "E",
	15: "F",
	16: "G",
	17: "H",
	18: "J",
	19: "K",
	20: "L",
	21: "M",
	22: "N",
	23: "P",
	24: "Q",
	25: "R",
	26: "S",
	27: "T",
	28: "U",
	29: "V",
	30: "W",
	31: "X",
}
<commit_msg>Delete cp_cc.go<commit_after><|endoftext|>


<commit_before>package main

import (
	"gnd.la/template"
	"go/doc"
	htemplate "html/template"
	"strings"
)

const (
	constPrefix = "const-"
	varPrefix   = "var-"
)

func ConstId(name string) string {
	return constPrefix + name
}

func VarId(name string) string {
	return varPrefix + name
}

func FuncId(name string) string {
	return "func-" + name
}

func TypeId(name string) string {
	return "type-" + name
}

func MethodId(typ string, name string) string {
	return "type-" + typ + "-method-" + name
}

func trim(s string, t string) string {
	return strings.Trim(s, t)
}

func funcId(fn *doc.Func) string {
	if fn.Recv != "" {
		recv := fn.Recv
		if recv[0] == '*' {
			recv = recv[1:]
		}
		return MethodId(recv, fn.Name)
	}
	return FuncId(fn.Name)
}

func typeId(typ *doc.Type) string {
	return TypeId(typ.Name)
}

func fa(s string) htemplate.HTML {
	return htemplate.HTML("<i class=\"fa fa-" + s + "\"></i>")
}

func init() {
	template.AddFuncs(template.FuncMap{
		"trim":    trim,
		"func_id": funcId,
		"type_id": typeId,
		"fa":      fa,
	})
}
<commit_msg>Remove fa function<commit_after>package main

import (
	"gnd.la/template"
	"go/doc"
	"strings"
)

const (
	constPrefix = "const-"
	varPrefix   = "var-"
)

func ConstId(name string) string {
	return constPrefix + name
}

func VarId(name string) string {
	return varPrefix + name
}

func FuncId(name string) string {
	return "func-" + name
}

func TypeId(name string) string {
	return "type-" + name
}

func MethodId(typ string, name string) string {
	return "type-" + typ + "-method-" + name
}

func trim(s string, t string) string {
	return strings.Trim(s, t)
}

func funcId(fn *doc.Func) string {
	if fn.Recv != "" {
		recv := fn.Recv
		if recv[0] == '*' {
			recv = recv[1:]
		}
		return MethodId(recv, fn.Name)
	}
	return FuncId(fn.Name)
}

func typeId(typ *doc.Type) string {
	return TypeId(typ.Name)
}

func init() {
	template.AddFuncs(template.FuncMap{
		"trim":    trim,
		"func_id": funcId,
		"type_id": typeId,
	})
}
<|endoftext|>