<commit_before>/* Copyright 2012 Marc-Antoine Ruel. 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 main

import (
	"fmt"
	"log"
	"net/http"
	"testing"
)

type mockNodesTable struct {
	entries map[string]*Node
	cas     CasTable
	t       *testing.T
	log     *log.Logger
}

func (a *ApplicationMock) LoadNodesTable(rootDir string, cas CasTable) (NodesTable, error) {
	return loadNodesTable(rootDir, cas, a.GetLog())
	if a.nodes == nil {
		a.nodes = &mockNodesTable{make(map[string]*Node), a.cas, a.T, a.log}
	}
	return a.nodes, nil
}

func (m *mockNodesTable) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	m.log.Printf("mockNodesTable.ServeHTTP(%s)", r.URL.Path)
	fmt.Fprintf(w, "TODO")
	//w.Write(m.entries[r.URL.Path[1:]])
}

func (m *mockNodesTable) AddEntry(node *Node, name string) error {
	m.log.Printf("mockNodesTable.AddEntry(%s)", name)
	m.entries[name] = nil
	return nil
}

func (m *mockNodesTable) Enumerate() <-chan NodeEntry {
	m.log.Printf("mockNodesTable.Enumerate() %d", len(m.entries))
	c := make(chan NodeEntry)
	go func() {
		// TODO(maruel): Will blow up if mutated concurrently.
		for k, v := range m.entries {
			c <- NodeEntry{Path: k, Node: v, Entry: nil}
		}
		close(c)
	}()
	return c
}

func TestNodesTable(t *testing.T) {
	t.Parallel()
	tempData, err := makeTempDir("nodes")
	if err != nil {
		t.Fatalf("Failed to create tempdir", err)
	}
	defer removeTempDir(tempData)

	log := getLog(false)
	cas := &mockCasTable{make(map[string][]byte), false, t, log}
	_, err = loadNodesTable(tempData, cas, log)
	if err != nil {
		t.Fatal(err)
	}
	/*
		n.AddEntry()
		n.Enumerate()
		n.ServeHTTP()
	*/
}
<commit_msg>Work in progress to implement and test the mock of NodesTable<commit_after>/* Copyright 2012 Marc-Antoine Ruel. 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 main

import (
	"bufio"
	"bytes"
	"log"
	"net/http"
	"net/http/httptest"
	"testing"
)

type mockNodesTable struct {
	entries map[string]Node
	cas     CasTable
	t       *testing.T
	log     *log.Logger
}

func (a *ApplicationMock) LoadNodesTable(rootDir string, cas CasTable) (NodesTable, error) {
	return loadNodesTable(rootDir, cas, a.GetLog())
	if a.nodes == nil {
		a.nodes = &mockNodesTable{make(map[string]Node), a.cas, a.T, a.log}
	}
	return a.nodes, nil
}

func (m *mockNodesTable) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	m.log.Printf("mockNodesTable.ServeHTTP(%s)", r.URL.Path)
	_, ok := m.entries[r.URL.Path[1:]]
	if !ok {
		http.Error(w, "Yo dawg", http.StatusNotFound)
		return
	}
	// Defer to the cas file system.
	//w.Write(item.asJson)
}

func (m *mockNodesTable) AddEntry(node *Node, name string) error {
	m.log.Printf("mockNodesTable.AddEntry(%s)", name)
	m.entries[name] = *node
	/*
		now := time.Now().UTC()
		// Create one directory store per month.
		monthName := now.Format("2006-01")
		monthDir := path.Join(n.nodesDir, monthName)
		if err := os.MkdirAll(monthDir, 0750); err != nil && !os.IsExist(err) {
			return fmt.Errorf("Failed to create %s: %s\n", monthDir, err)
		}

		suffix := 0
		nodePath := ""
		for {
			nodeName := n.hostname + "_" + now.Format("2006-01-02_15-04-05") + "_" + name
			if suffix != 0 {
				nodeName += fmt.Sprintf("(%d)", suffix)
			}
			nodePath = path.Join(monthDir, nodeName)
			f, err := os.OpenFile(nodePath, os.O_WRONLY|os.O_EXCL|os.O_CREATE, 0640)
			if err != nil {
				// Try ad nauseam.
				suffix += 1
			} else {
				if _, err = f.Write(data); err != nil {
					return fmt.Errorf("Failed to write %s: %s", f.Name(), err)
				}
				n.log.Printf("Saved node: %s", path.Join(monthName, nodeName))
				break
			}
		}
	*/
	return nil
}

func (m *mockNodesTable) Enumerate() <-chan NodeEntry {
	m.log.Printf("mockNodesTable.Enumerate() %d", len(m.entries))
	c := make(chan NodeEntry)
	go func() {
		// TODO(maruel): Will blow up if mutated concurrently.
		for k, v := range m.entries {
			// The comment was discarded.
			c <- NodeEntry{Path: k, Node: &v, Entry: nil}
		}
		close(c)
	}()
	return c
}

func TestNodesTable(t *testing.T) {
	t.Parallel()
	tempData, err := makeTempDir("nodes")
	if err != nil {
		t.Fatalf("Failed to create tempdir", err)
	}
	defer removeTempDir(tempData)

	log := getLog(false)
	cas := &mockCasTable{make(map[string][]byte), false, t, log}
	load := func() (NodesTable, error) {
		return loadNodesTable(tempData, cas, log)
	}
	testNodesTableImpl(t, load)
}

/*
func TestNodesTableMock(t *testing.T) {
	t.Parallel()
	log := getLog(false)
	cas := &mockCasTable{make(map[string][]byte), false, t, log}
	nodes := &mockNodesTable{make(map[string]Node), cas, t, log}
	load := func() (NodesTable, error) {
		return nodes, nil
	}
	testNodesTableImpl(t, load)
}
*/

func testNodesTableImpl(t *testing.T, load func() (NodesTable, error)) {
	nodes, err := load()
	if err != nil {
		t.Fatal(err)
	}

	for _ = range nodes.Enumerate() {
		t.Fatal("Found unexpected value")
	}
	if err := nodes.AddEntry(&Node{"entry sha1", "comment"}, "name"); err != nil {
		t.Fatal(err)
	}
	count := 0
	for _ = range nodes.Enumerate() {
		count += 1
	}
	// TODO(maruel): The real implementation will return 2, the mock will return 1.
	if count == 0 {
		t.Fatalf("Found %d items", count)
	}

	{
		path := "/"
		req, err := http.ReadRequest(bufio.NewReader(bytes.NewBufferString("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n")))
		if err != nil {
			t.Errorf("%s", err)
		}
		resp := httptest.NewRecorder()
		nodes.ServeHTTP(resp, req)
		if resp.Code != 200 {
			t.Fatal(resp.Code)
		}
	}

	{
		path := "/foo"
		req, err := http.ReadRequest(bufio.NewReader(bytes.NewBufferString("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n")))
		if err != nil {
			t.Errorf("%s", err)
		}
		resp := httptest.NewRecorder()
		nodes.ServeHTTP(resp, req)
		if resp.Code != 404 {
			t.Fatal(resp.Code)
		}
	}
}
<|endoftext|>


<commit_before>package controllers

import (
	"github.com/Tsuguya/revmgo/app"
	"yarukoto/app/models/project"
	"github.com/revel/revel"
)

type Todo struct {
	*revel.Controller
	mgo.MongoController
}

func (c Todo) List() revel.Result {
    c.Response.ContentType = "application/json; charset=utf8"
    b := models.FindTodoListByProjectId(c.Database, "5467157be4b0c9468004aef6")
    Max := len(b) - 1
	return c.Render(b, Max)
}

<commit_msg>Add post process into todo controller<commit_after>package controllers

import (
	"github.com/Tsuguya/revmgo/app"
	"yarukoto/app/models/project"
	"github.com/revel/revel"
)

type Todo struct {
	*revel.Controller
	mgo.MongoController
}

func (c Todo) List() revel.Result {
    c.Response.ContentType = "application/json; charset=utf8"

    if c.Request.Method == "POST" {
        //b := models.FindTodoListByProjectId(c.Database, "5467157be4b0c9468004aef6")
        b := models.FindTodoListByProjectId(c.Database, c.Request.PostForm.Get("project_id"))
        Max := len(b) - 1
        return c.Render(b, Max)
    }

    return c.Render()
}

<|endoftext|>


<commit_before>
// LoL Cruncher - A Historical League of Legends Statistics Tracker
// Copyright (C) 2015  Jason Chu (1lann) 1lanncontact@gmail.com

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package controllers

import (
	"github.com/revel/revel"
	"cruncher/app/models/query"
	"strings"
)

type View struct {
	*revel.Controller
}

func (c View) Index() revel.Result {
	return c.Render()
}

func (c View) About() revel.Result {
	return c.Render()
}

func (c View) Request(region, name string) revel.Result {
	if !(region == "na" || region == "euw" || region == "eune" ||
			region == "lan" || region == "las" || region == "oce" ||
			region == "br" || region == "ru" || region == "kr" ||
			region == "tr") {
		c.Flash.Error("Sorry, that region isn't supported!")
		return c.Redirect(View.Index)
	}

	region = strings.ToLower(region)

	resolvedName, player, new, err := query.GetStats(name, region)
	if err != nil {
		if (err.Error() == "database error") {
			return c.RenderTemplate("errors/database.html")
		} else if (err.Error() == "database down") {
			return c.RenderTemplate("errors/down.html")
		} else if (err.Error() == "Not Found") {
			c.Flash.Error("Sorry, that summoner could not be found!")
			return c.Redirect(View.Index)
		} else {
			c.Flash.Error("Could not connect to Riot Games' servers! Try again later.")
			return c.Redirect(View.Index)
		}
	}

	if resolvedName != name {
		return c.Redirect("/" + region + "/" + resolvedName)
	}

	c.RenderArgs["new"] = new
	c.RenderArgs["player"] = player
	c.RenderArgs["name"] = resolvedName
	c.RenderArgs["titleName"] = resolvedName + " - LoL Cruncher"
	return c.Render()
}
<commit_msg>Trimming resolve names to avoid redirect loops<commit_after>
// LoL Cruncher - A Historical League of Legends Statistics Tracker
// Copyright (C) 2015  Jason Chu (1lann) 1lanncontact@gmail.com

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package controllers

import (
	"github.com/revel/revel"
	"cruncher/app/models/query"
	"strings"
)

type View struct {
	*revel.Controller
}

func (c View) Index() revel.Result {
	return c.Render()
}

func (c View) About() revel.Result {
	return c.Render()
}

func (c View) Request(region, name string) revel.Result {
	if !(region == "na" || region == "euw" || region == "eune" ||
			region == "lan" || region == "las" || region == "oce" ||
			region == "br" || region == "ru" || region == "kr" ||
			region == "tr") {
		c.Flash.Error("Sorry, that region isn't supported!")
		return c.Redirect(View.Index)
	}

	region = strings.ToLower(region)

	resolvedName, player, new, err := query.GetStats(name, region)
	if err != nil {
		if (err.Error() == "database error") {
			return c.RenderTemplate("errors/database.html")
		} else if (err.Error() == "database down") {
			return c.RenderTemplate("errors/down.html")
		} else if (err.Error() == "Not Found") {
			c.Flash.Error("Sorry, that summoner could not be found!")
			return c.Redirect(View.Index)
		} else {
			c.Flash.Error("Could not connect to Riot Games' servers! Try again later.")
			return c.Redirect(View.Index)
		}
	}

	if strings.Trim(resolvedName, " ") != strings.Trim(name, " ") {
		return c.Redirect("/" + region + "/" + strings.Trim(resolvedName, " "))
	}

	c.RenderArgs["new"] = new
	c.RenderArgs["player"] = player
	c.RenderArgs["name"] = resolvedName
	c.RenderArgs["titleName"] = resolvedName + " - LoL Cruncher"
	return c.Render()
}
<|endoftext|>


<commit_before>package glukit

import (
	"app/engine"
	"app/model"
	"app/store"
	"app/util"
	"appengine"
	"appengine/user"
	"encoding/json"
	"fmt"
	"lib/github.com/grd/stat"
	"net/http"
	"sort"
	"strconv"
	"time"
)

// Represents a DataResponse with an array of DataSeries and some metadata
type DataResponse struct {
	FirstName string       `json:"firstName"`
	LastName  string       `json:"lastName"`
	Data      []DataSeries `json:"data"`
	Picture   string       `json:"picture"`
	LastSync  time.Time    `json:"lastSync"`
}

// Represents a generic DataSeries structure with a series of DataPoints
type DataSeries struct {
	Name string            `json:"name"`
	Data []model.DataPoint `json:"data"`
	Type string            `json:"type"`
}

const (
	QUERY_PARAM_LIMIT = "limit"
	QUERY_PARAM_FROM  = "from"
	QUERY_PARAM_TO    = "to"
)

// content renders the most recent day's worth of data as json for the active user
func personalData(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)

	mostRecentWeekAsJson(writer, request, user.Email)
}

// demoContent renders the most recent day's worth of data as json for the demo user
func demoContent(writer http.ResponseWriter, request *http.Request) {
	mostRecentWeekAsJson(writer, request, DEMO_EMAIL)
}

// mostRecentWeekAsJson retrieves the most recent day's week worth of data for the user identified by
// the given email address and writes to the response writer as json
func mostRecentWeekAsJson(writer http.ResponseWriter, request *http.Request, email string) {
	context := appengine.NewContext(request)
	glukitUser, _, upperBound, err := store.GetUserData(context, email)
	lowerBound := upperBound.Add(model.DEFAULT_LOOKBACK_PERIOD)

	if err != nil && err == store.ErrNoImportedDataFound {
		context.Debugf("No imported data found for user [%s]", email)
		http.Error(writer, err.Error(), 204)
	} else if err != nil {
		util.Propagate(err)
	} else {
		reads, err := store.GetGlucoseReads(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}
		injections, err := store.GetInjections(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}
		carbs, err := store.GetCarbs(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}
		exercises, err := store.GetExercises(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}

		value := writer.Header()
		value.Add("Content-type", "application/json")

		response := DataResponse{FirstName: glukitUser.FirstName, LastName: glukitUser.LastName, Data: generateDataSeriesFromData(reads, injections, carbs, exercises), Picture: glukitUser.PictureUrl, LastSync: glukitUser.MostRecentRead.GetTime()}
		writeAsJson(writer, response)
	}
}

// find the steady sailor and retrieve his most recent day's worth of data.
func steadySailorData(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)

	steadySailorDataForEmail(writer, request, user.Email)
}

// find the steady sailor for the demo user and retrieve his most recent day's worth of data.
func demoSteadySailorData(writer http.ResponseWriter, request *http.Request) {
	steadySailorDataForEmail(writer, request, DEMO_EMAIL)
}

// find the steady sailor and retrieve his most recent day's worth of data.
func steadySailorDataForEmail(writer http.ResponseWriter, request *http.Request, recipientEmail string) {
	context := appengine.NewContext(request)
	steadySailor, _, upperBound, err := store.FindSteadySailor(context, recipientEmail)

	lowerBound := upperBound.Add(model.DEFAULT_LOOKBACK_PERIOD)
	if err != nil && err == store.ErrNoSteadySailorMatchFound {
		context.Debugf("No steady sailor match found for user [%s]", recipientEmail)
		http.Error(writer, err.Error(), 204)
	} else if err != nil {
		util.Propagate(err)
	} else {
		reads, err := store.GetGlucoseReads(context, steadySailor.Email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}

		value := writer.Header()
		value.Add("Content-type", "application/json")

		response := DataResponse{FirstName: steadySailor.FirstName, LastName: steadySailor.LastName, Data: generateDataSeriesFromData(reads, nil, nil, nil), Picture: steadySailor.PictureUrl, LastSync: steadySailor.MostRecentRead.GetTime()}
		writeAsJson(writer, response)
	}
}

// writeAsJson writes a DataResponse with its set of GlucoseReads, Injections, Carbs and Exercises as json. This is what is called from the javascript
// front-end to get the data.
func writeAsJson(writer http.ResponseWriter, response DataResponse) {
	enc := json.NewEncoder(writer)
	enc.Encode(response)
}

func generateDataSeriesFromData(reads []model.GlucoseRead, injections []model.Injection, carbs []model.Carb, exercises []model.Exercise) (dataSeries []DataSeries) {
	data := make([]DataSeries, 1)

	data[0] = DataSeries{"GlucoseReads", model.GlucoseReadSlice(reads).ToDataPointSlice(), "GlucoseReads"}
	var userEvents []model.DataPoint
	if injections != nil {
		userEvents = model.MergeDataPointArrays(userEvents, model.InjectionSlice(injections).ToDataPointSlice(reads))
	}

	if carbs != nil {
		userEvents = model.MergeDataPointArrays(userEvents, model.CarbSlice(carbs).ToDataPointSlice(reads))
	}

	// TODO: clean up exercise from all the app or restore it. We won't be using it at the moment as we don't think the exercise data
	// from the dexcom is good enough
	// if exercises != nil {
	// 	userEvents = model.MergeDataPointArrays(userEvents, model.ExerciseSlice(exercises).ToDataPointSlice(reads))
	// }

	sort.Sort(model.DataPointSlice(userEvents))

	data = append(data, DataSeries{"UserEvents", userEvents, "UserEvents"})

	return data
}

// dashboard renders the dashboard statistics as json
func dashboard(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)

	dashboardDataForUser(writer, request, user.Email)
}

// demodashboard renders the dashboard statistics as json for the demo user
func demoDashboard(writer http.ResponseWriter, request *http.Request) {
	dashboardDataForUser(writer, request, DEMO_EMAIL)
}

// dashboardDataForUser retrieves reads and generates dashboard statistics from them
func dashboardDataForUser(writer http.ResponseWriter, request *http.Request, email string) {
	context := appengine.NewContext(request)

	userProfile, _, upperBound, err := store.GetUserData(context, email)
	lowerBound := upperBound.Add(model.DEFAULT_LOOKBACK_PERIOD)

	if err != nil && err == store.ErrNoImportedDataFound {
		context.Debugf("No imported data found for user [%s]", email)
		http.Error(writer, err.Error(), 204)
	} else if err != nil {
		util.Propagate(err)
	} else {
		reads, err := store.GetGlucoseReads(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}

		writeDashboardDataAsJson(writer, request, reads, userProfile)
	}
}

// writedashboardDataAsJson calculates dashboard statistics from an array of GlucoseReads and writes it
// as json
func writeDashboardDataAsJson(writer http.ResponseWriter, request *http.Request, reads []model.GlucoseRead, userProfile *model.GlukitUser) {
	context := appengine.NewContext(request)
	value := writer.Header()
	value.Add("Content-type", "application/json")

	var dashboardData model.DashboardData
	if len(reads) > 0 {
		sort.Sort(model.ReadStatsSlice(reads))
		dashboardData.FirstName = userProfile.FirstName
		dashboardData.LastName = userProfile.LastName
		dashboardData.Picture = userProfile.PictureUrl
		dashboardData.LastSync = userProfile.MostRecentRead.GetTime()
		dashboardData.Average = stat.Mean(model.ReadStatsSlice(reads))
		dashboardData.High, _ = stat.Max(model.ReadStatsSlice(reads))
		dashboardData.Low, _ = stat.Min(model.ReadStatsSlice(reads))
		dashboardData.Median = stat.MedianFromSortedData(model.ReadStatsSlice(reads))
		dashboardData.Score = engine.CalculateUserFacingScore(userProfile.MostRecentScore)
		dashboardData.ScoreDetails = userProfile.MostRecentScore
		context.Debugf("Calculated user score of [%d] from internal score of [%d]", dashboardData.Score, userProfile.MostRecentScore.Value)
	}

	enc := json.NewEncoder(writer)
	enc.Encode(dashboardData)
}

func glukitScores(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)

	glukitScoresForEmail(writer, request, user.Email)
}

func glukitScoresForDemo(writer http.ResponseWriter, request *http.Request) {
	glukitScoresForEmail(writer, request, DEMO_EMAIL)
}

// glukitScoresForEmail is the endpoint to retrieve a list of glukitscores.
func glukitScoresForEmail(writer http.ResponseWriter, request *http.Request, email string) {
	context := appengine.NewContext(request)

	limit := request.FormValue(QUERY_PARAM_LIMIT)
	fromTimestamp := request.FormValue(QUERY_PARAM_FROM)
	toTimestamp := request.FormValue(QUERY_PARAM_TO)

	// The request must include at least one of from/to/limit to be considered valid
	// as leaving it too open would could open the door for costly queries
	if len(limit) == 0 && len(fromTimestamp) == 0 && len(toTimestamp) == 0 {
		http.Error(writer, fmt.Sprintf("Query must specify at least one of: %s, %s or %s.",
			QUERY_PARAM_LIMIT, QUERY_PARAM_FROM, QUERY_PARAM_TO), 400)
		return
	}

	var scanQuery store.GlukitScoreScanQuery
	if len(limit) > 0 {
		if limitValue, err := strconv.ParseInt(limit, 10, 32); err != nil {
			http.Error(writer, fmt.Sprintf("Invalid value for %s: [%v].", QUERY_PARAM_LIMIT, err), 400)
			return
		} else {
			limitVal := int(limitValue)
			scanQuery.Limit = &limitVal
		}
	}

	if len(fromTimestamp) > 0 {
		if fromValue, err := strconv.ParseInt(fromTimestamp, 10, 64); err != nil {
			http.Error(writer, fmt.Sprintf("Invalid value for %s: [%v].", QUERY_PARAM_FROM, err), 400)
			return
		} else {
			fromTime := time.Unix(fromValue, 0)
			scanQuery.From = &fromTime
		}
	}

	if len(toTimestamp) > 0 {
		if toValue, err := strconv.ParseInt(toTimestamp, 10, 64); err != nil {
			http.Error(writer, fmt.Sprintf("Invalid value for %s: [%v].", QUERY_PARAM_TO, err), 400)
			return
		} else {
			toTime := time.Unix(toValue, 0)
			scanQuery.To = &toTime
		}
	}

	glukitScores, err := store.GetGlukitScores(context, email, scanQuery)
	if err != nil {
		util.Propagate(err)
	}

	if len(glukitScores) < 1 {
		http.Error(writer, "No glukit scores calculated yet.", 204)
		return
	}

	value := writer.Header()
	value.Add("Content-type", "application/json")

	enc := json.NewEncoder(writer)
	enc.Encode(glukitScores)

}
<commit_msg>Change Dashboard Statistics to Only Look at the Last 24 Hours to Match UI.<commit_after>package glukit

import (
	"app/engine"
	"app/model"
	"app/store"
	"app/util"
	"appengine"
	"appengine/user"
	"encoding/json"
	"fmt"
	"lib/github.com/grd/stat"
	"net/http"
	"sort"
	"strconv"
	"time"
)

// Represents a DataResponse with an array of DataSeries and some metadata
type DataResponse struct {
	FirstName string       `json:"firstName"`
	LastName  string       `json:"lastName"`
	Data      []DataSeries `json:"data"`
	Picture   string       `json:"picture"`
	LastSync  time.Time    `json:"lastSync"`
}

// Represents a generic DataSeries structure with a series of DataPoints
type DataSeries struct {
	Name string            `json:"name"`
	Data []model.DataPoint `json:"data"`
	Type string            `json:"type"`
}

const (
	QUERY_PARAM_LIMIT = "limit"
	QUERY_PARAM_FROM  = "from"
	QUERY_PARAM_TO    = "to"
)

// content renders the most recent day's worth of data as json for the active user
func personalData(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)

	mostRecentWeekAsJson(writer, request, user.Email)
}

// demoContent renders the most recent day's worth of data as json for the demo user
func demoContent(writer http.ResponseWriter, request *http.Request) {
	mostRecentWeekAsJson(writer, request, DEMO_EMAIL)
}

// mostRecentWeekAsJson retrieves the most recent day's week worth of data for the user identified by
// the given email address and writes to the response writer as json
func mostRecentWeekAsJson(writer http.ResponseWriter, request *http.Request, email string) {
	context := appengine.NewContext(request)
	glukitUser, _, upperBound, err := store.GetUserData(context, email)
	lowerBound := upperBound.Add(model.DEFAULT_LOOKBACK_PERIOD)

	if err != nil && err == store.ErrNoImportedDataFound {
		context.Debugf("No imported data found for user [%s]", email)
		http.Error(writer, err.Error(), 204)
	} else if err != nil {
		util.Propagate(err)
	} else {
		reads, err := store.GetGlucoseReads(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}
		injections, err := store.GetInjections(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}
		carbs, err := store.GetCarbs(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}
		exercises, err := store.GetExercises(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}

		value := writer.Header()
		value.Add("Content-type", "application/json")

		response := DataResponse{FirstName: glukitUser.FirstName, LastName: glukitUser.LastName, Data: generateDataSeriesFromData(reads, injections, carbs, exercises), Picture: glukitUser.PictureUrl, LastSync: glukitUser.MostRecentRead.GetTime()}
		writeAsJson(writer, response)
	}
}

// find the steady sailor and retrieve his most recent day's worth of data.
func steadySailorData(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)

	steadySailorDataForEmail(writer, request, user.Email)
}

// find the steady sailor for the demo user and retrieve his most recent day's worth of data.
func demoSteadySailorData(writer http.ResponseWriter, request *http.Request) {
	steadySailorDataForEmail(writer, request, DEMO_EMAIL)
}

// find the steady sailor and retrieve his most recent day's worth of data.
func steadySailorDataForEmail(writer http.ResponseWriter, request *http.Request, recipientEmail string) {
	context := appengine.NewContext(request)
	steadySailor, _, upperBound, err := store.FindSteadySailor(context, recipientEmail)

	lowerBound := upperBound.Add(model.DEFAULT_LOOKBACK_PERIOD)
	if err != nil && err == store.ErrNoSteadySailorMatchFound {
		context.Debugf("No steady sailor match found for user [%s]", recipientEmail)
		http.Error(writer, err.Error(), 204)
	} else if err != nil {
		util.Propagate(err)
	} else {
		reads, err := store.GetGlucoseReads(context, steadySailor.Email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}

		value := writer.Header()
		value.Add("Content-type", "application/json")

		response := DataResponse{FirstName: steadySailor.FirstName, LastName: steadySailor.LastName, Data: generateDataSeriesFromData(reads, nil, nil, nil), Picture: steadySailor.PictureUrl, LastSync: steadySailor.MostRecentRead.GetTime()}
		writeAsJson(writer, response)
	}
}

// writeAsJson writes a DataResponse with its set of GlucoseReads, Injections, Carbs and Exercises as json. This is what is called from the javascript
// front-end to get the data.
func writeAsJson(writer http.ResponseWriter, response DataResponse) {
	enc := json.NewEncoder(writer)
	enc.Encode(response)
}

func generateDataSeriesFromData(reads []model.GlucoseRead, injections []model.Injection, carbs []model.Carb, exercises []model.Exercise) (dataSeries []DataSeries) {
	data := make([]DataSeries, 1)

	data[0] = DataSeries{"GlucoseReads", model.GlucoseReadSlice(reads).ToDataPointSlice(), "GlucoseReads"}
	var userEvents []model.DataPoint
	if injections != nil {
		userEvents = model.MergeDataPointArrays(userEvents, model.InjectionSlice(injections).ToDataPointSlice(reads))
	}

	if carbs != nil {
		userEvents = model.MergeDataPointArrays(userEvents, model.CarbSlice(carbs).ToDataPointSlice(reads))
	}

	// TODO: clean up exercise from all the app or restore it. We won't be using it at the moment as we don't think the exercise data
	// from the dexcom is good enough
	// if exercises != nil {
	// 	userEvents = model.MergeDataPointArrays(userEvents, model.ExerciseSlice(exercises).ToDataPointSlice(reads))
	// }

	sort.Sort(model.DataPointSlice(userEvents))

	data = append(data, DataSeries{"UserEvents", userEvents, "UserEvents"})

	return data
}

// dashboard renders the dashboard statistics as json
func dashboard(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)

	dashboardDataForUser(writer, request, user.Email)
}

// demodashboard renders the dashboard statistics as json for the demo user
func demoDashboard(writer http.ResponseWriter, request *http.Request) {
	dashboardDataForUser(writer, request, DEMO_EMAIL)
}

// dashboardDataForUser retrieves reads and generates dashboard statistics from them
func dashboardDataForUser(writer http.ResponseWriter, request *http.Request, email string) {
	context := appengine.NewContext(request)

	userProfile, _, upperBound, err := store.GetUserData(context, email)
	lowerBound := upperBound.Add(time.Duration(-1*24) * time.Hour)

	if err != nil && err == store.ErrNoImportedDataFound {
		context.Debugf("No imported data found for user [%s]", email)
		http.Error(writer, err.Error(), 204)
	} else if err != nil {
		util.Propagate(err)
	} else {
		reads, err := store.GetGlucoseReads(context, email, lowerBound, upperBound)
		if err != nil {
			util.Propagate(err)
		}

		writeDashboardDataAsJson(writer, request, reads, userProfile)
	}
}

// writedashboardDataAsJson calculates dashboard statistics from an array of GlucoseReads and writes it
// as json
func writeDashboardDataAsJson(writer http.ResponseWriter, request *http.Request, reads []model.GlucoseRead, userProfile *model.GlukitUser) {
	context := appengine.NewContext(request)
	value := writer.Header()
	value.Add("Content-type", "application/json")

	var dashboardData model.DashboardData
	if len(reads) > 0 {
		sort.Sort(model.ReadStatsSlice(reads))
		dashboardData.FirstName = userProfile.FirstName
		dashboardData.LastName = userProfile.LastName
		dashboardData.Picture = userProfile.PictureUrl
		dashboardData.LastSync = userProfile.MostRecentRead.GetTime()
		dashboardData.Average = stat.Mean(model.ReadStatsSlice(reads))
		dashboardData.High, _ = stat.Max(model.ReadStatsSlice(reads))
		dashboardData.Low, _ = stat.Min(model.ReadStatsSlice(reads))
		dashboardData.Median = stat.MedianFromSortedData(model.ReadStatsSlice(reads))
		dashboardData.Score = engine.CalculateUserFacingScore(userProfile.MostRecentScore)
		dashboardData.ScoreDetails = userProfile.MostRecentScore
		context.Debugf("Calculated user score of [%d] from internal score of [%d]", dashboardData.Score, userProfile.MostRecentScore.Value)
	}

	enc := json.NewEncoder(writer)
	enc.Encode(dashboardData)
}

func glukitScores(writer http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	user := user.Current(context)

	glukitScoresForEmail(writer, request, user.Email)
}

func glukitScoresForDemo(writer http.ResponseWriter, request *http.Request) {
	glukitScoresForEmail(writer, request, DEMO_EMAIL)
}

// glukitScoresForEmail is the endpoint to retrieve a list of glukitscores.
func glukitScoresForEmail(writer http.ResponseWriter, request *http.Request, email string) {
	context := appengine.NewContext(request)

	limit := request.FormValue(QUERY_PARAM_LIMIT)
	fromTimestamp := request.FormValue(QUERY_PARAM_FROM)
	toTimestamp := request.FormValue(QUERY_PARAM_TO)

	// The request must include at least one of from/to/limit to be considered valid
	// as leaving it too open would could open the door for costly queries
	if len(limit) == 0 && len(fromTimestamp) == 0 && len(toTimestamp) == 0 {
		http.Error(writer, fmt.Sprintf("Query must specify at least one of: %s, %s or %s.",
			QUERY_PARAM_LIMIT, QUERY_PARAM_FROM, QUERY_PARAM_TO), 400)
		return
	}

	var scanQuery store.GlukitScoreScanQuery
	if len(limit) > 0 {
		if limitValue, err := strconv.ParseInt(limit, 10, 32); err != nil {
			http.Error(writer, fmt.Sprintf("Invalid value for %s: [%v].", QUERY_PARAM_LIMIT, err), 400)
			return
		} else {
			limitVal := int(limitValue)
			scanQuery.Limit = &limitVal
		}
	}

	if len(fromTimestamp) > 0 {
		if fromValue, err := strconv.ParseInt(fromTimestamp, 10, 64); err != nil {
			http.Error(writer, fmt.Sprintf("Invalid value for %s: [%v].", QUERY_PARAM_FROM, err), 400)
			return
		} else {
			fromTime := time.Unix(fromValue, 0)
			scanQuery.From = &fromTime
		}
	}

	if len(toTimestamp) > 0 {
		if toValue, err := strconv.ParseInt(toTimestamp, 10, 64); err != nil {
			http.Error(writer, fmt.Sprintf("Invalid value for %s: [%v].", QUERY_PARAM_TO, err), 400)
			return
		} else {
			toTime := time.Unix(toValue, 0)
			scanQuery.To = &toTime
		}
	}

	glukitScores, err := store.GetGlukitScores(context, email, scanQuery)
	if err != nil {
		util.Propagate(err)
	}

	if len(glukitScores) < 1 {
		http.Error(writer, "No glukit scores calculated yet.", 204)
		return
	}

	value := writer.Header()
	value.Add("Content-type", "application/json")

	enc := json.NewEncoder(writer)
	enc.Encode(glukitScores)

}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"strconv"

	"encoding/json"

	"io/ioutil"

	"time"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

var logger = shim.NewLogger("ftLogger")

// cbsDB is a JSON file which emulates a private own database
var cbsDB = "/tmp/ibi_cbs.json"

// SampleChaincode struct required to implement the shim.Chaincode interface
type SampleChaincode struct {
}

// Init method is called when the chaincode is first deployed onto the blockchain network
func (t *SampleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if len(args) > 0 {
		return nil, errors.New("Incorrect number of arguments. Expecting 0")
	}

	var customerName string // Name of the customer
	var currentBalance int  // Current account balance of the customer
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	// Initialize the chaincode
	customerName = args[0]
	currentBalance, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for customer account balance")
	}

	logger.Info("Customer: %s Available Balance: %d", customerName, currentBalance)

	// Save the Customer info
	db := make(map[string]interface{})
	db["cName"] = customerName
	db["cBalance"] = currentBalance

	jsonDB, err := json.Marshal(db)
	if err != nil {
		logger.Error("Unable to initialize core private database")
		return nil, err
	}

	ioutil.WriteFile(cbsDB, jsonDB, 0777)

	// Write the state to the ledger
	err = stub.PutState("IBI-CC[init]: "+time.Now().String(), []byte(args[0]))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Query method is invoked whenever any read/get/query operation needs to be performed on the blockchain state.
func (t *SampleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	logger.Info("Query is running: " + function)

	// Handle different functions
	if function == "GetAccountBalance" { //read a variable
		return t.getAccountBalance(stub, args)
	}
	logger.Error("Query did not find func: " + function)

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

// Invoke method is invoked whenever the state of the blockchain is to be modified.
func (t *SampleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	logger.Info("Invoke is running: " + function)

	// Handle different functions
	switch function {
	case "Init":
		return t.Init(stub, "init", args)
	case "Deposit":
		return t.depositFund(stub, args)
	case "Withdraw":
		return t.withdrawFund(stub, args)
	default:
		logger.Error("Invoke did not find func: " + function)
	}

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

func (t *SampleChaincode) getAccountBalance(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running getAccountBalance")
	var name, jsonResp string
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
	}

	name = args[0]
	valAsbytes, err := ioutil.ReadFile(cbsDB)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to get account balance for " + name + "\"}"
		return nil, errors.New(jsonResp)
	}

	return valAsbytes, nil
}

func (t *SampleChaincode) depositFund(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running depositFund")

	var name, jsonResp string
	var value, currentBalance, newBalance int
	var err error
	var db = make(map[string]interface{})

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the customer and value to set")
	}

	name = args[0]
	value, err = strconv.Atoi(args[1])
	if err != nil {
		jsonResp = "{\"Error\":\"Invalid input argument for deposit amount: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	valAsBytes, err := ioutil.ReadFile(cbsDB)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to connect to DB: + " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	err = json.Unmarshal(valAsBytes, db)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to retrieve account details: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	if db["cName"].(string) != name {
		jsonResp = "{\"Error\":\"Invalid customer name!\"}"
		return nil, errors.New(jsonResp)
	}

	currentBalance, err = strconv.Atoi(db["cBalance"].(string))
	if err != nil {
		jsonResp = "{\"Error\":\"Internal error in fund deposit: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	newBalance = value + currentBalance

	db["cBalance"] = strconv.Itoa(newBalance)

	jsonDB, err := json.Marshal(db)
	if err != nil {
		jsonResp = "{\"Error\":\"Error in fund deposit: " + err.Error() + "\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	err = ioutil.WriteFile(cbsDB, jsonDB, 0777)
	if err != nil {
		jsonResp = "{\"Error\":\"Error in DB commit: " + err.Error() + "\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	return nil, nil
}

func (t *SampleChaincode) withdrawFund(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running withdrawFund")

	var name, jsonResp string
	var value, currentBalance, newBalance int
	var err error
	var db = make(map[string]interface{})

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the customer and value to set")
	}

	name = args[0]
	value, err = strconv.Atoi(args[1])
	if err != nil {
		jsonResp = "{\"Error\":\"Invalid input argument for withdraw amount: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	valAsBytes, err := ioutil.ReadFile(cbsDB)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to connect to DB: + " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	err = json.Unmarshal(valAsBytes, db)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to retrieve account details: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	if db["cName"].(string) != name {
		jsonResp = "{\"Error\":\"Invalid customer name!\"}"
		return nil, errors.New(jsonResp)
	}

	currentBalance, err = strconv.Atoi(db["cBalance"].(string))
	if err != nil {
		jsonResp = "{\"Error\":\"Internal error in fund withdraw: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	if value > currentBalance {
		jsonResp = "{\"Error\":\"Insufficient Fund in account. Aborting...\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	newBalance = value + currentBalance

	db["cBalance"] = strconv.Itoa(newBalance)

	jsonDB, err := json.Marshal(db)
	if err != nil {
		jsonResp = "{\"Error\":\"Error in fund withdraw: " + err.Error() + "\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	err = ioutil.WriteFile(cbsDB, jsonDB, 0777)
	if err != nil {
		jsonResp = "{\"Error\":\"Error in DB commit: " + err.Error() + "\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	return nil, nil
}

func main() {
	lld, _ := shim.LogLevel("DEBUG")
	fmt.Println(lld)

	logger.SetLevel(lld)
	fmt.Println(logger.IsEnabledFor(lld))
	err := shim.Start(new(SampleChaincode))
	if err != nil {
		fmt.Println("Could not start SampleChaincode")
	} else {
		fmt.Println("SampleChaincode successfully started")
	}
}
<commit_msg>Fix a bug in Init()<commit_after>package main

import (
	"errors"
	"fmt"
	"strconv"

	"encoding/json"

	"io/ioutil"

	"time"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

var logger = shim.NewLogger("ftLogger")

// cbsDB is a JSON file which emulates a private own database
var cbsDB = "/tmp/ibi_cbs.json"

// SampleChaincode struct required to implement the shim.Chaincode interface
type SampleChaincode struct {
}

// Init method is called when the chaincode is first deployed onto the blockchain network
func (t *SampleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var customerName string // Name of the customer
	var currentBalance int  // Current account balance of the customer
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	// Initialize the chaincode
	customerName = args[0]
	currentBalance, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for customer account balance")
	}

	logger.Info("Customer: %s Available Balance: %d", customerName, currentBalance)

	// Save the Customer info
	db := make(map[string]interface{})
	db["cName"] = customerName
	db["cBalance"] = currentBalance

	jsonDB, err := json.Marshal(db)
	if err != nil {
		logger.Error("Unable to initialize core private database")
		return nil, err
	}

	ioutil.WriteFile(cbsDB, jsonDB, 0777)

	// Write the state to the ledger
	err = stub.PutState("IBI-CC[init]: "+time.Now().String(), []byte(args[0]))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Query method is invoked whenever any read/get/query operation needs to be performed on the blockchain state.
func (t *SampleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	logger.Info("Query is running: " + function)

	// Handle different functions
	if function == "GetAccountBalance" { //read a variable
		return t.getAccountBalance(stub, args)
	}
	logger.Error("Query did not find func: " + function)

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

// Invoke method is invoked whenever the state of the blockchain is to be modified.
func (t *SampleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	logger.Info("Invoke is running: " + function)

	// Handle different functions
	switch function {
	case "Init":
		return t.Init(stub, "init", args)
	case "Deposit":
		return t.depositFund(stub, args)
	case "Withdraw":
		return t.withdrawFund(stub, args)
	default:
		logger.Error("Invoke did not find func: " + function)
	}

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

func (t *SampleChaincode) getAccountBalance(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running getAccountBalance")
	var name, jsonResp string
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
	}

	name = args[0]
	valAsbytes, err := ioutil.ReadFile(cbsDB)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to get account balance for " + name + "\"}"
		return nil, errors.New(jsonResp)
	}

	return valAsbytes, nil
}

func (t *SampleChaincode) depositFund(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running depositFund")

	var name, jsonResp string
	var value, currentBalance, newBalance int
	var err error
	var db = make(map[string]interface{})

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the customer and value to set")
	}

	name = args[0]
	value, err = strconv.Atoi(args[1])
	if err != nil {
		jsonResp = "{\"Error\":\"Invalid input argument for deposit amount: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	valAsBytes, err := ioutil.ReadFile(cbsDB)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to connect to DB: + " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	err = json.Unmarshal(valAsBytes, db)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to retrieve account details: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	if db["cName"].(string) != name {
		jsonResp = "{\"Error\":\"Invalid customer name!\"}"
		return nil, errors.New(jsonResp)
	}

	currentBalance, err = strconv.Atoi(db["cBalance"].(string))
	if err != nil {
		jsonResp = "{\"Error\":\"Internal error in fund deposit: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	newBalance = value + currentBalance

	db["cBalance"] = strconv.Itoa(newBalance)

	jsonDB, err := json.Marshal(db)
	if err != nil {
		jsonResp = "{\"Error\":\"Error in fund deposit: " + err.Error() + "\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	err = ioutil.WriteFile(cbsDB, jsonDB, 0777)
	if err != nil {
		jsonResp = "{\"Error\":\"Error in DB commit: " + err.Error() + "\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	return nil, nil
}

func (t *SampleChaincode) withdrawFund(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running withdrawFund")

	var name, jsonResp string
	var value, currentBalance, newBalance int
	var err error
	var db = make(map[string]interface{})

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the customer and value to set")
	}

	name = args[0]
	value, err = strconv.Atoi(args[1])
	if err != nil {
		jsonResp = "{\"Error\":\"Invalid input argument for withdraw amount: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	valAsBytes, err := ioutil.ReadFile(cbsDB)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to connect to DB: + " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	err = json.Unmarshal(valAsBytes, db)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to retrieve account details: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	if db["cName"].(string) != name {
		jsonResp = "{\"Error\":\"Invalid customer name!\"}"
		return nil, errors.New(jsonResp)
	}

	currentBalance, err = strconv.Atoi(db["cBalance"].(string))
	if err != nil {
		jsonResp = "{\"Error\":\"Internal error in fund withdraw: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	if value > currentBalance {
		jsonResp = "{\"Error\":\"Insufficient Fund in account. Aborting...\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	newBalance = value + currentBalance

	db["cBalance"] = strconv.Itoa(newBalance)

	jsonDB, err := json.Marshal(db)
	if err != nil {
		jsonResp = "{\"Error\":\"Error in fund withdraw: " + err.Error() + "\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	err = ioutil.WriteFile(cbsDB, jsonDB, 0777)
	if err != nil {
		jsonResp = "{\"Error\":\"Error in DB commit: " + err.Error() + "\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	return nil, nil
}

func main() {
	lld, _ := shim.LogLevel("DEBUG")
	fmt.Println(lld)

	logger.SetLevel(lld)
	fmt.Println(logger.IsEnabledFor(lld))
	err := shim.Start(new(SampleChaincode))
	if err != nil {
		fmt.Println("Could not start SampleChaincode")
	} else {
		fmt.Println("SampleChaincode successfully started")
	}
}
<|endoftext|>


<commit_before>package csvutil
/*
*  File: reader.go
*  Author: Bryan Matsuo [bmatsuo@soe.ucsc.edu]
*  Created: Sat May 28 23:53:36 PDT 2011
*  Description: CSV reader library.
*
*   This file is part of csvutil.
*
*   csvutil is free software: you can redistribute it and/or modify
*   it under the terms of the GNU Lesser Public License as published by
*   the Free Software Foundation, either version 3 of the License, or
*   (at your option) any later version.
*
*   csvutil is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU Lesser Public License for more details.
*
*   You should have received a copy of the GNU Lesser Public License
*   along with csvutil.  If not, see <http://www.gnu.org/licenses/>.
*/
import (
	"io"
	"bufio"
	"strings"
	"os"
)

//  A reader object for CSV data utilizing the bufio package.
type Reader struct {
	Sep int "Field separator character."
	Trim bool "Remove excess whitespace from field values."
	Cutset string "Set of characters to trim."
    LastRow Row "The last row read by the Reader."
	r io.Reader "Base reader object."
	br *bufio.Reader "For reading lines."
    bufSize int "Initial size of internal line buffers."
}

//  A simple row structure for rows read by a csvutil.Reader that
//  encapsulates any read error enountered along with any data read
//  prior to encountering an error.
type Row struct {
	Fields []string "CSV row field data"
	Error os.Error "Error encountered reading"
}

func mkrow(fields []string, err os.Error) Row {
	var r Row
	r.Fields = fields
	r.Error = err
	return r
}

//  An object for iterating over the rows of a Reader.
//      rit = reader.RowIterAuto()
//      for r := range reader.RowsChan {
//          if r.Error != nil {
//              panic(r.Error)
//          }
//          var fields []string = r.Fields
//          // Process the desired entries of "fields".
//          rit.Next()
//      }
//  The (*Reader) RowIterAuto() (*RowReaderIterator) method creates a
//  new iterator object and immediately reads a row from the Reader.
//  If this behavior is not desired, use the underlying alternate method
//  (*Reader) RowIter() (*RowReaderIterator).
type ReaderRowIterator struct {
    stopped bool
    RowsChan <-chan Row
    control chan<- bool
}

//  A ReaderRowIterator meant for reading until the end of the
//  data stream of the corresponding Reader's io.Reader.
//      rit = reader.RowIterAuto()
//      for r := range reader.RowsChan {
//          if r.Error != nil {
//              panic(r.Error)
//          }
//          var fields []string = r.Fields
//          // Process the desired entries of "fields".
//      }
//  This iteration using a range statement as above, it is not safe to
//  break out of the loop. This generally causes the 'loss' of at least
//  one row.
//
//  For iterating rows in a way such that the iteration can be stopped
//  safely, use ReaderRowIterator objects instead.
type ReaderRowIteratorAuto struct {
    stopped bool
    RowsChan <-chan Row
}

//  Tell the iterator to get another row from the Reader.
func (csvri *ReaderRowIterator) Next() {
    if csvri.stopped {
        panic("stopped")
    }
    csvri.control <- true
}

//  Tell the iterator to stop fetching rows and exit its goroutine.
//  Calling the (*ReaderRowIterator) Break() method is not necessary,
//  but to avoid doing so will cause the iterating goroutine to sleep
//  for the duration of the program.
func (csvri *ReaderRowIterator) Break() {
    if csvri.stopped {
        return
    }
    close(csvri.control)
    csvri.stopped = true
}

//  Create a new reader object.
func NewReader(r io.Reader) *Reader {
	var csvr *Reader = new(Reader).Reset()
	csvr.r = r
	csvr.br = bufio.NewReader(r)
    csvr.bufSize = 80
	return csvr
}

//  Create a new reader with a buffer of a specified size.
func NewReaderSize(r io.Reader, size int) *Reader {
	var csvr *Reader = new(Reader).Reset()
	csvr.r = r
	var err os.Error
	csvr.br, err = bufio.NewReaderSize(r, size)
	if err != nil { panic(err) }
    csvr.bufSize = size
	return csvr
}

// Create a new row iterator and return it.
func (csvr *Reader) RowIter() (*ReaderRowIterator) {
    ri := new(ReaderRowIterator)
    throughChan := make(chan Row)
    controlChan := make (chan bool)
    ri.RowsChan = throughChan
    ri.control = controlChan
	var read_rows = func (r chan<- Row, c <-chan bool) {
        defer func() {
            if x:=recover(); x!=nil {
                /* Do nothing. */
            }
        } ()
		for true {
            cont, ok := <-c
            if !ok || !cont {
                break
            }
            csvr.LastRow = Row{Fields:nil, Error:nil}
			var row Row = csvr.ReadRow()
			if row.Fields == nil {
				if row.Error == os.EOF {
					break
				} else {
					panic(row.Error)
				}
			}
            csvr.LastRow = row
			r <- row
		}
		close(r)
	}
	go read_rows(throughChan, controlChan)
	return ri
}
//  For convenience, return a new ReaderRowIterator rit that has
//  already already been the target of (*ReaderRowIterator) Next().
func (csvr *Reader) RowIterStarted() (rit *ReaderRowIterator) {
    rit = csvr.RowIter()
    rit.Next()
    return rit
}

// Create a new ReaderRowIteratorAuto object and return it.
func (csvr *Reader) RowIterAuto() (*ReaderRowIteratorAuto) {
    ri := new(ReaderRowIteratorAuto)
    throughChan := make(chan Row)
    ri.RowsChan = throughChan
	var read_rows = func (r chan<- Row) {
        defer func() {
            if x:=recover(); x!=nil {
                /* Do nothing. */
            }
        } ()
		for true {
            csvr.LastRow = Row{Fields:nil, Error:nil}
			var row Row = csvr.ReadRow()
			if row.Fields == nil {
				if row.Error == os.EOF {
					break
				} else {
					panic(row.Error)
				}
			}
            csvr.LastRow = row
			r <- row
		}
		close(r)
	}
	go read_rows(throughChan)
	return ri
}

//  Read up to a new line and return a slice of string slices
func (csvr *Reader) ReadRow() Row {
	/* Read one row of the CSV and and return an array of the fields. */
    var(
        r Row
        line, readLine, ln []byte
        err os.Error
        isPrefix bool
    )
	r = Row{Fields:nil, Error:nil}
    csvr.LastRow = r
    isPrefix = true
    for isPrefix {
        readLine, isPrefix, err = csvr.br.ReadLine()
	    r.Fields = nil
	    r.Error = err
	    if err == os.EOF { return r }
	    if err != nil { return r }
	    if isPrefix {
            readLen := len(readLine)
            if line == nil {
                line = make([]byte, 0, 2*readLen)
            }
            ln = make([]byte, readLen)
            copy(ln, readLine)
            line = append(line, ln...)
        } else {
            // isPrefix is false here. The loop will break next iteration.
            if line == nil {
                line = readLine
            }
        }
    }
	r.Fields = strings.FieldsFunc(
			string(line),
			func (c int) bool { return c == csvr.Sep } )
	if csvr.Trim {
		for i:=0 ; i<len(r.Fields) ; i++ {
			r.Fields[i] = strings.Trim(r.Fields[i], csvr.Cutset)
		}
	}
    csvr.LastRow = r
	return r
}

//  Read rows into a preallocated buffer. Any error encountered is
//  returned. Returns the number of rows read in a single value return
//  context any errors encountered (including os.EOF).
func (csvr *Reader) ReadRows(rbuf [][]string) (int, os.Error) {
    var(
        err os.Error
        numRead int = 0
        n int = len(rbuf)
    )
    for i:=0 ; i<n ; i++ {
        r := csvr.ReadRow()
        numRead++
        if r.Error != nil {
            err = r.Error
            if r.Fields != nil {
                rbuf[i] = r.Fields
            }
            break
        }
        rbuf[i] = r.Fields
    }
    return numRead, err
}

//  Convenience methor to read at most n rows from csvr. Simple allocates
//  a row slice rs and calls csvr.ReadRows(rs). Returns the actual number
//  of rows read and any error that occurred (and halted reading).
func (csvr *Reader) ReadNRows(n int) (int, os.Error) {
    rows := make([][]string, n)
    return csvr.ReadRows(rows)
}

//  Reads any remaining rows of CSV data in the underlying io.Reader.
//  Uses resizing when a preallocated buffer of rows fills. Up to 16
//  rows can be read without any doubling occuring.
func (csvr *Reader) RemainingRows() (rows [][]string, err os.Error) {
    return csvr.RemainingRowsSize(16)
}

//  Like csvr.RemainingRows(), but allows specification of the initial
//  row buffer capacity.
func (csvr *Reader) RemainingRowsSize(size int) (rows [][]string, err os.Error) {
    err = nil
    var rbuf [][]string = make([][]string, 0, size)
    rit := csvr.RowIterAuto()
    for r := range rit.RowsChan {
        /*
        if cap(rbuf) == len(rbuf) {
            newbuf := make([][]string, len(rbuf), 2*len(rbuf))
            copy(rbuf,newbuf)
            rbuf = newbuf
        }
        */
        if r.Error != nil {
            err = r.Error
            if r.Fields != nil {
                rbuf = append(rbuf, r.Fields)
            }
            break
        }
        rbuf = append(rbuf, r.Fields)
    }
    return rbuf, err
}

//  A function routine for setting all the configuration variables of a
//  csvutil.Reader in a single line.
func (csvr *Reader) Configure(sep int, trim bool, cutset string) *Reader {
	csvr.Sep = sep
	csvr.Trim = trim
	csvr.Cutset = cutset
	return csvr
}

//  Reset a Reader's configuration to the defaults. This is mostly meant
//  for internal use but is safe for general use.
func (csvr *Reader) Reset() *Reader {
	return csvr.Configure(DEFAULT_SEP, DEFAULT_TRIM, DEFAULT_CUTSET)
}

/* Comply with the reader interface. */
/*
func (csvr*Reader) Read(b []byte) (n int, err os.Error) {
	return csvr.r.Read(b)
}
*/
<commit_msg>Fix some erroneous reader.go documentation.<commit_after>package csvutil
/*
*  File: reader.go
*  Author: Bryan Matsuo [bmatsuo@soe.ucsc.edu]
*  Created: Sat May 28 23:53:36 PDT 2011
*  Description: CSV reader library.
*
*   This file is part of csvutil.
*
*   csvutil is free software: you can redistribute it and/or modify
*   it under the terms of the GNU Lesser Public License as published by
*   the Free Software Foundation, either version 3 of the License, or
*   (at your option) any later version.
*
*   csvutil is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU Lesser Public License for more details.
*
*   You should have received a copy of the GNU Lesser Public License
*   along with csvutil.  If not, see <http://www.gnu.org/licenses/>.
*/
import (
	"io"
	"bufio"
	"strings"
	"os"
)

//  A reader object for CSV data utilizing the bufio package.
type Reader struct {
	Sep int "Field separator character."
	Trim bool "Remove excess whitespace from field values."
	Cutset string "Set of characters to trim."
    LastRow Row "The last row read by the Reader."
	r io.Reader "Base reader object."
	br *bufio.Reader "For reading lines."
    bufSize int "Initial size of internal line buffers."
}

//  A simple row structure for rows read by a csvutil.Reader that
//  encapsulates any read error enountered along with any data read
//  prior to encountering an error.
type Row struct {
	Fields []string "CSV row field data"
	Error os.Error "Error encountered reading"
}

func mkrow(fields []string, err os.Error) Row {
	var r Row
	r.Fields = fields
	r.Error = err
	return r
}

//  An object for iterating over the rows of a Reader.
//      rit = reader.RowIterStarted()
//      for r := range reader.RowsChan {
//          if r.Error != nil {
//              rit.Break()
//              panic(r.Error)
//          }
//          var fields []string = r.Fields
//          if !fieldsOk(fields) {
//              rit.Break()
//              break
//          }
//          // Process the desired entries of "fields".
//          rit.Next()
//      }
//  This itererator is safe to break out of. For iterators meant for
//  parsing an entire stream, see the ReaderRowIteratorAuto type.
type ReaderRowIterator struct {
    stopped bool
    RowsChan <-chan Row
    control chan<- bool
}

//  A ReaderRowIteratorAuto is meant for reading until encountering the
//  end of the data stream corresponding to a Reader's underlying
//  io.Reader.
//      rit = reader.RowIterAuto()
//      for r := range reader.RowsChan {
//          if r.Error != nil {
//              panic(r.Error)
//          }
//          var fields []string = r.Fields
//          // Process the desired entries of "fields".
//      }
//  This iteration using a range statement as above, it is not safe to
//  break out of the loop. This generally causes the 'loss' of at least
//  one row.
//
//  For iterating rows in a way such that the iteration can be stopped
//  safely, use ReaderRowIterator objects instead.
type ReaderRowIteratorAuto struct {
    stopped bool
    RowsChan <-chan Row
}

//  Tell the iterator to get another row from the Reader.
func (csvri *ReaderRowIterator) Next() {
    if csvri.stopped {
        panic("stopped")
    }
    csvri.control <- true
}

//  Tell the iterator to stop fetching rows and exit its goroutine.
//  Calling the (*ReaderRowIterator) Break() method is not necessary,
//  but to avoid doing so will cause the iterating goroutine to sleep
//  for the duration of the program.
func (csvri *ReaderRowIterator) Break() {
    if csvri.stopped {
        return
    }
    close(csvri.control)
    csvri.stopped = true
}

//  Create a new reader object.
func NewReader(r io.Reader) *Reader {
	var csvr *Reader = new(Reader).Reset()
	csvr.r = r
	csvr.br = bufio.NewReader(r)
    csvr.bufSize = 80
	return csvr
}

//  Create a new reader with a buffer of a specified size.
func NewReaderSize(r io.Reader, size int) *Reader {
	var csvr *Reader = new(Reader).Reset()
	csvr.r = r
	var err os.Error
	csvr.br, err = bufio.NewReaderSize(r, size)
	if err != nil { panic(err) }
    csvr.bufSize = size
	return csvr
}

// Create a new row iterator and return it.
func (csvr *Reader) RowIter() (*ReaderRowIterator) {
    ri := new(ReaderRowIterator)
    throughChan := make(chan Row)
    controlChan := make (chan bool)
    ri.RowsChan = throughChan
    ri.control = controlChan
	var read_rows = func (r chan<- Row, c <-chan bool) {
        defer func() {
            if x:=recover(); x!=nil {
                /* Do nothing. */
            }
        } ()
		for true {
            cont, ok := <-c
            if !ok || !cont {
                break
            }
            csvr.LastRow = Row{Fields:nil, Error:nil}
			var row Row = csvr.ReadRow()
			if row.Fields == nil {
				if row.Error == os.EOF {
					break
				} else {
					panic(row.Error)
				}
			}
            csvr.LastRow = row
			r <- row
		}
		close(r)
	}
	go read_rows(throughChan, controlChan)
	return ri
}
//  For convenience, return a new ReaderRowIterator rit that has
//  already already been the target of (*ReaderRowIterator) Next().
func (csvr *Reader) RowIterStarted() (rit *ReaderRowIterator) {
    rit = csvr.RowIter()
    rit.Next()
    return rit
}

// Create a new ReaderRowIteratorAuto object and return it.
func (csvr *Reader) RowIterAuto() (*ReaderRowIteratorAuto) {
    ri := new(ReaderRowIteratorAuto)
    throughChan := make(chan Row)
    ri.RowsChan = throughChan
	var read_rows = func (r chan<- Row) {
        defer func() {
            if x:=recover(); x!=nil {
                /* Do nothing. */
            }
        } ()
		for true {
            csvr.LastRow = Row{Fields:nil, Error:nil}
			var row Row = csvr.ReadRow()
			if row.Fields == nil {
				if row.Error == os.EOF {
					break
				} else {
					panic(row.Error)
				}
			}
            csvr.LastRow = row
			r <- row
		}
		close(r)
	}
	go read_rows(throughChan)
	return ri
}

//  Read up to a new line and return a slice of string slices
func (csvr *Reader) ReadRow() Row {
	/* Read one row of the CSV and and return an array of the fields. */
    var(
        r Row
        line, readLine, ln []byte
        err os.Error
        isPrefix bool
    )
	r = Row{Fields:nil, Error:nil}
    csvr.LastRow = r
    isPrefix = true
    for isPrefix {
        readLine, isPrefix, err = csvr.br.ReadLine()
	    r.Fields = nil
	    r.Error = err
	    if err == os.EOF { return r }
	    if err != nil { return r }
	    if isPrefix {
            readLen := len(readLine)
            if line == nil {
                line = make([]byte, 0, 2*readLen)
            }
            ln = make([]byte, readLen)
            copy(ln, readLine)
            line = append(line, ln...)
        } else {
            // isPrefix is false here. The loop will break next iteration.
            if line == nil {
                line = readLine
            }
        }
    }
	r.Fields = strings.FieldsFunc(
			string(line),
			func (c int) bool { return c == csvr.Sep } )
	if csvr.Trim {
		for i:=0 ; i<len(r.Fields) ; i++ {
			r.Fields[i] = strings.Trim(r.Fields[i], csvr.Cutset)
		}
	}
    csvr.LastRow = r
	return r
}

//  Read rows into a preallocated buffer. Any error encountered is
//  returned. Returns the number of rows read in a single value return
//  context any errors encountered (including os.EOF).
func (csvr *Reader) ReadRows(rbuf [][]string) (int, os.Error) {
    var(
        err os.Error
        numRead int = 0
        n int = len(rbuf)
    )
    for i:=0 ; i<n ; i++ {
        r := csvr.ReadRow()
        numRead++
        if r.Error != nil {
            err = r.Error
            if r.Fields != nil {
                rbuf[i] = r.Fields
            }
            break
        }
        rbuf[i] = r.Fields
    }
    return numRead, err
}

//  Convenience methor to read at most n rows from csvr. Simple allocates
//  a row slice rs and calls csvr.ReadRows(rs). Returns the actual number
//  of rows read and any error that occurred (and halted reading).
func (csvr *Reader) ReadNRows(n int) (int, os.Error) {
    rows := make([][]string, n)
    return csvr.ReadRows(rows)
}

//  Reads any remaining rows of CSV data in the underlying io.Reader.
//  Uses resizing when a preallocated buffer of rows fills. Up to 16
//  rows can be read without any doubling occuring.
func (csvr *Reader) RemainingRows() (rows [][]string, err os.Error) {
    return csvr.RemainingRowsSize(16)
}

//  Like csvr.RemainingRows(), but allows specification of the initial
//  row buffer capacity.
func (csvr *Reader) RemainingRowsSize(size int) (rows [][]string, err os.Error) {
    err = nil
    var rbuf [][]string = make([][]string, 0, size)
    rit := csvr.RowIterAuto()
    for r := range rit.RowsChan {
        /*
        if cap(rbuf) == len(rbuf) {
            newbuf := make([][]string, len(rbuf), 2*len(rbuf))
            copy(rbuf,newbuf)
            rbuf = newbuf
        }
        */
        if r.Error != nil {
            err = r.Error
            if r.Fields != nil {
                rbuf = append(rbuf, r.Fields)
            }
            break
        }
        rbuf = append(rbuf, r.Fields)
    }
    return rbuf, err
}

//  A function routine for setting all the configuration variables of a
//  csvutil.Reader in a single line.
func (csvr *Reader) Configure(sep int, trim bool, cutset string) *Reader {
	csvr.Sep = sep
	csvr.Trim = trim
	csvr.Cutset = cutset
	return csvr
}

//  Reset a Reader's configuration to the defaults. This is mostly meant
//  for internal use but is safe for general use.
func (csvr *Reader) Reset() *Reader {
	return csvr.Configure(DEFAULT_SEP, DEFAULT_TRIM, DEFAULT_CUTSET)
}

/* Comply with the reader interface. */
/*
func (csvr*Reader) Read(b []byte) (n int, err os.Error) {
	return csvr.r.Read(b)
}
*/
<|endoftext|>


<commit_before>package wav

import (
	"bufio"
	"encoding/binary"
	"errors"
	"math"
	"time"

	"github.com/youpy/go-riff"
	"github.com/zaf/g711"
)

type Reader struct {
	r         *riff.Reader
	riffChunk *riff.RIFFChunk
	format    *WavFormat
	*WavData
}

func NewReader(r riff.RIFFReader) *Reader {
	riffReader := riff.NewReader(r)
	return &Reader{r: riffReader}
}

func (r *Reader) Format() (format *WavFormat, err error) {
	if r.format == nil {
		format, err = r.readFormat()
		if err != nil {
			return
		}
		r.format = format
	} else {
		format = r.format
	}

	return
}

func (r *Reader) Duration() (time.Duration, error) {
	format, err := r.Format()
	if err != nil {
		return 0.0, err
	}

	err = r.loadWavData()
	if err != nil {
		return 0.0, err
	}

	sec := float64(r.WavData.Size) / float64(format.BlockAlign) / float64(format.SampleRate)

	return time.Duration(sec*1000000000) * time.Nanosecond, nil
}

func (r *Reader) Read(p []byte) (n int, err error) {
	err = r.loadWavData()
	if err != nil {
		return n, err
	}

	return r.WavData.Read(p)
}

func (r *Reader) ReadSamples(params ...uint32) (samples []Sample, err error) {
	var bytes []byte
	var numSamples, b, n int

	if len(params) > 0 {
		numSamples = int(params[0])
	} else {
		numSamples = 2048
	}

	format, err := r.Format()
	if err != nil {
		return
	}

	numChannels := int(format.NumChannels)
	blockAlign := int(format.BlockAlign)
	bitsPerSample := int(format.BitsPerSample)

	bytes = make([]byte, numSamples*blockAlign)
	n, err = r.Read(bytes)

	if err != nil {
		return
	}

	numSamples = n / blockAlign
	r.WavData.pos += uint32(numSamples * blockAlign)
	samples = make([]Sample, numSamples)
	offset := 0

	for i := 0; i < numSamples; i++ {
		for j := 0; j < numChannels; j++ {
			soffset := offset + (j * bitsPerSample / 8)

			switch format.AudioFormat {
			case AudioFormatIEEEFloat:
				bits :=
					uint32((int(bytes[soffset+3]) << 24) +
						(int(bytes[soffset+2]) << 16) +
						(int(bytes[soffset+1]) << 8) +
						int(bytes[soffset]))
				samples[i].Values[j] = int(math.MaxInt32 * math.Float32frombits(bits))

			case AudioFormatALaw:
				var val uint
				pcm := g711.DecodeAlaw(bytes[soffset : soffset+(bitsPerSample/8)])
				for b = 0; b < len(pcm); b++ {
					val += uint(pcm[b]) << uint(b*8)
				}

				samples[i].Values[j] = toInt(val, bitsPerSample*2)

			case AudioFormatMULaw:
				var val uint
				pcm := g711.DecodeUlaw(bytes[soffset : soffset+(bitsPerSample/8)])
				for b = 0; b < len(pcm); b++ {
					val += uint(pcm[b]) << uint(b*8)
				}

				samples[i].Values[j] = toInt(val, bitsPerSample*2)

			default:
				var val uint
				for b = 0; b*8 < bitsPerSample; b++ {
					val += uint(bytes[soffset+b]) << uint(b*8)
				}

				samples[i].Values[j] = toInt(val, bitsPerSample)
			}
		}

		offset += blockAlign
	}

	return
}

func (r *Reader) IntValue(sample Sample, channel uint) int {
	return sample.Values[channel]
}

func (r *Reader) FloatValue(sample Sample, channel uint) float64 {
	return float64(r.IntValue(sample, channel)) / math.Pow(2, float64(r.format.BitsPerSample)-1)
}

func (r *Reader) readFormat() (fmt *WavFormat, err error) {
	var riffChunk *riff.RIFFChunk

	fmt = new(WavFormat)

	if r.riffChunk == nil {
		riffChunk, err = r.r.Read()
		if err != nil {
			return
		}

		r.riffChunk = riffChunk
	} else {
		riffChunk = r.riffChunk
	}

	fmtChunk := findChunk(riffChunk, "fmt ")

	if fmtChunk == nil {
		err = errors.New("Format chunk is not found")
		return
	}

	err = binary.Read(fmtChunk, binary.LittleEndian, fmt)
	if err != nil {
		return
	}

	return
}

func (r *Reader) loadWavData() error {
	if r.WavData == nil {
		data, err := r.readData()
		if err != nil {
			return err
		}
		r.WavData = data
	}

	return nil
}

func (r *Reader) readData() (data *WavData, err error) {
	var riffChunk *riff.RIFFChunk

	if r.riffChunk == nil {
		riffChunk, err = r.r.Read()
		if err != nil {
			return
		}

		r.riffChunk = riffChunk
	} else {
		riffChunk = r.riffChunk
	}

	dataChunk := findChunk(riffChunk, "data")
	if dataChunk == nil {
		err = errors.New("Data chunk is not found")
		return
	}

	data = &WavData{bufio.NewReader(dataChunk), dataChunk.ChunkSize, 0}

	return
}

func findChunk(riffChunk *riff.RIFFChunk, id string) (chunk *riff.Chunk) {
	for _, ch := range riffChunk.Chunks {
		if string(ch.ChunkID[:]) == id {
			chunk = ch
			break
		}
	}

	return
}

func toInt(value uint, bits int) int {
	var result int

	switch bits {
	case 32:
		result = int(int32(value))
	case 16:
		result = int(int16(value))
	case 8:
		result = int(value)
	default:
		msb := uint(1 << (uint(bits) - 1))

		if value >= msb {
			result = -int((1 << uint(bits)) - value)
		} else {
			result = int(value)
		}
	}

	return result
}
<commit_msg>error messages prefixed with a lowercase letter<commit_after>package wav

import (
	"bufio"
	"encoding/binary"
	"errors"
	"math"
	"time"

	"github.com/youpy/go-riff"
	"github.com/zaf/g711"
)

type Reader struct {
	r         *riff.Reader
	riffChunk *riff.RIFFChunk
	format    *WavFormat
	*WavData
}

func NewReader(r riff.RIFFReader) *Reader {
	riffReader := riff.NewReader(r)
	return &Reader{r: riffReader}
}

func (r *Reader) Format() (format *WavFormat, err error) {
	if r.format == nil {
		format, err = r.readFormat()
		if err != nil {
			return
		}
		r.format = format
	} else {
		format = r.format
	}

	return
}

func (r *Reader) Duration() (time.Duration, error) {
	format, err := r.Format()
	if err != nil {
		return 0.0, err
	}

	err = r.loadWavData()
	if err != nil {
		return 0.0, err
	}

	sec := float64(r.WavData.Size) / float64(format.BlockAlign) / float64(format.SampleRate)

	return time.Duration(sec*1000000000) * time.Nanosecond, nil
}

func (r *Reader) Read(p []byte) (n int, err error) {
	err = r.loadWavData()
	if err != nil {
		return n, err
	}

	return r.WavData.Read(p)
}

func (r *Reader) ReadSamples(params ...uint32) (samples []Sample, err error) {
	var bytes []byte
	var numSamples, b, n int

	if len(params) > 0 {
		numSamples = int(params[0])
	} else {
		numSamples = 2048
	}

	format, err := r.Format()
	if err != nil {
		return
	}

	numChannels := int(format.NumChannels)
	blockAlign := int(format.BlockAlign)
	bitsPerSample := int(format.BitsPerSample)

	bytes = make([]byte, numSamples*blockAlign)
	n, err = r.Read(bytes)

	if err != nil {
		return
	}

	numSamples = n / blockAlign
	r.WavData.pos += uint32(numSamples * blockAlign)
	samples = make([]Sample, numSamples)
	offset := 0

	for i := 0; i < numSamples; i++ {
		for j := 0; j < numChannels; j++ {
			soffset := offset + (j * bitsPerSample / 8)

			switch format.AudioFormat {
			case AudioFormatIEEEFloat:
				bits :=
					uint32((int(bytes[soffset+3]) << 24) +
						(int(bytes[soffset+2]) << 16) +
						(int(bytes[soffset+1]) << 8) +
						int(bytes[soffset]))
				samples[i].Values[j] = int(math.MaxInt32 * math.Float32frombits(bits))

			case AudioFormatALaw:
				var val uint
				pcm := g711.DecodeAlaw(bytes[soffset : soffset+(bitsPerSample/8)])
				for b = 0; b < len(pcm); b++ {
					val += uint(pcm[b]) << uint(b*8)
				}

				samples[i].Values[j] = toInt(val, bitsPerSample*2)

			case AudioFormatMULaw:
				var val uint
				pcm := g711.DecodeUlaw(bytes[soffset : soffset+(bitsPerSample/8)])
				for b = 0; b < len(pcm); b++ {
					val += uint(pcm[b]) << uint(b*8)
				}

				samples[i].Values[j] = toInt(val, bitsPerSample*2)

			default:
				var val uint
				for b = 0; b*8 < bitsPerSample; b++ {
					val += uint(bytes[soffset+b]) << uint(b*8)
				}

				samples[i].Values[j] = toInt(val, bitsPerSample)
			}
		}

		offset += blockAlign
	}

	return
}

func (r *Reader) IntValue(sample Sample, channel uint) int {
	return sample.Values[channel]
}

func (r *Reader) FloatValue(sample Sample, channel uint) float64 {
	return float64(r.IntValue(sample, channel)) / math.Pow(2, float64(r.format.BitsPerSample)-1)
}

func (r *Reader) readFormat() (fmt *WavFormat, err error) {
	var riffChunk *riff.RIFFChunk

	fmt = new(WavFormat)

	if r.riffChunk == nil {
		riffChunk, err = r.r.Read()
		if err != nil {
			return
		}

		r.riffChunk = riffChunk
	} else {
		riffChunk = r.riffChunk
	}

	fmtChunk := findChunk(riffChunk, "fmt ")

	if fmtChunk == nil {
		err = errors.New("format chunk is not found")
		return
	}

	err = binary.Read(fmtChunk, binary.LittleEndian, fmt)
	if err != nil {
		return
	}

	return
}

func (r *Reader) loadWavData() error {
	if r.WavData == nil {
		data, err := r.readData()
		if err != nil {
			return err
		}
		r.WavData = data
	}

	return nil
}

func (r *Reader) readData() (data *WavData, err error) {
	var riffChunk *riff.RIFFChunk

	if r.riffChunk == nil {
		riffChunk, err = r.r.Read()
		if err != nil {
			return
		}

		r.riffChunk = riffChunk
	} else {
		riffChunk = r.riffChunk
	}

	dataChunk := findChunk(riffChunk, "data")
	if dataChunk == nil {
		err = errors.New("data chunk is not found")
		return
	}

	data = &WavData{bufio.NewReader(dataChunk), dataChunk.ChunkSize, 0}

	return
}

func findChunk(riffChunk *riff.RIFFChunk, id string) (chunk *riff.Chunk) {
	for _, ch := range riffChunk.Chunks {
		if string(ch.ChunkID[:]) == id {
			chunk = ch
			break
		}
	}

	return
}

func toInt(value uint, bits int) int {
	var result int

	switch bits {
	case 32:
		result = int(int32(value))
	case 16:
		result = int(int16(value))
	case 8:
		result = int(value)
	default:
		msb := uint(1 << (uint(bits) - 1))

		if value >= msb {
			result = -int((1 << uint(bits)) - value)
		} else {
			result = int(value)
		}
	}

	return result
}
<|endoftext|>


<commit_before>package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/hmac"
    "crypto/sha256"
    "flag"
    "log"
)

var (
    // 32 byte key for AES256, made from crypto/rand
    key     = []byte{0x98, 0x39, 0xea, 0x42, 0xd0, 0x3e, 0x36, 0x6b, 0xe3, 0x7b, 0x91, 0x6, 0x50, 0x5b, 0x7f, 0xc9, 0x93, 0x56, 0xaa, 0xa8, 0x96, 0x33, 0x7, 0xd7, 0xf7, 0x50, 0xa5, 0x3a, 0xdc, 0x8e, 0xe2, 0x9f}
    iv      = []byte("batman and robin") // 16 bytes
    message = flag.String("message", "Batman and Robin are coming", "The message to use")
)

func main() {
    flag.Parse()
    block, err := aes.NewCipher(key)
    if err != nil {
        log.Fatalf("Failed making AES block cipher: %s", err)
    }
    bytes := []byte(*message)
    stream := cipher.NewCTR(block, iv)
    stream.XORKeyStream(bytes, bytes)
    hash := hmac.New(sha256.New, key)
    hash.Write(bytes)
    log.Printf("message: %s", *message)
    log.Printf("encrypted message (raw bytes): %v", bytes)
    log.Printf("HMAC: %x", hash.Sum(nil))
}
<commit_msg>Cleanup hmac example<commit_after>package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/hmac"
    "crypto/sha256"
    "flag"
    "log"
)

var (
    // 32 byte key for AES256, made from crypto/rand
    key     = []byte{0x98, 0x39, 0xea, 0x42, 0xd0, 0x3e, 0x36, 0x6b, 0xe3, 0x7b, 0x91, 0x6, 0x50, 0x5b, 0x7f, 0xc9, 0x93, 0x56, 0xaa, 0xa8, 0x96, 0x33, 0x7, 0xd7, 0xf7, 0x50, 0xa5, 0x3a, 0xdc, 0x8e, 0xe2, 0x9f}
    iv      = []byte("batman and robin") // 16 bytes
    message = flag.String("message", "Batman and Robin are coming", "The message to use")
)

func main() {
    flag.Parse()
    block, err := aes.NewCipher(key)
    if err != nil {
        log.Fatalf("failed making AES block cipher: %s", err)
    }
    bytes := []byte(*message)
    stream := cipher.NewCTR(block, iv)
    stream.XORKeyStream(bytes, bytes)
    hash := hmac.New(sha256.New, key)
    hash.Write(bytes)
    log.Printf("message: %s", *message)
    log.Printf("encrypted message (raw bytes): %v", bytes)
    log.Printf("HMAC: %x", hash.Sum(nil))
}
<|endoftext|>


<commit_before>// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium

package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"

	"github.com/cilium/cilium/pkg/bpf"
	"github.com/cilium/cilium/pkg/command"
	"github.com/cilium/cilium/pkg/common"
	"github.com/cilium/cilium/pkg/maps/recorder"
)

// bpfRecorderListCmd represents the bpf_recorder_list command
var bpfRecorderListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "List PCAP recorder entries",
	Run: func(cmd *cobra.Command, args []string) {
		common.RequireRootPrivilege("cilium bpf recorder list")
		maps := make([]interface{}, 2)
		maps[0] = recorder.CaptureMap4
		if getIpv6EnableStatus() {
			maps[1] = recorder.CaptureMap6
		}
		dumpRecorderEntries(maps)
	},
}

func init() {
	bpfRecorderCmd.AddCommand(bpfRecorderListCmd)
	command.AddOutputOption(bpfRecorderListCmd)
}

func dumpRecorderEntries(maps []interface{}, args ...interface{}) {
	entries := make([]recorder.MapRecord, 0)

	for _, m := range maps {
		if m == nil {
			continue
		}
		path, err := m.(recorder.CaptureMap).Path()
		if err == nil {
			err = m.(recorder.CaptureMap).Open()
		}
		if err != nil {
			if os.IsNotExist(err) {
				fmt.Fprintf(os.Stderr, "Unable to open %s: %s. Skipping.\n", path, err)
				continue
			}
			Fatalf("Unable to open %s: %s", path, err)
		}
		defer m.(recorder.CaptureMap).Close()
		if command.OutputOption() {
			callback := func(key bpf.MapKey, value bpf.MapValue) {
				record := recorder.MapRecord{Key: key.(recorder.RecorderKey), Value: value.(recorder.RecorderEntry)}
				entries = append(entries, record)
			}
			if err = m.(recorder.CaptureMap).DumpWithCallback(callback); err != nil {
				Fatalf("Error while collecting BPF map entries: %s", err)
			}
		} else {
			out, err := m.(recorder.CaptureMap).DumpEntries()
			if err != nil {
				Fatalf("Error while dumping BPF Map: %s", err)
			}
			fmt.Println(out)
		}
	}
	if command.OutputOption() {
		if err := command.PrintOutput(entries); err != nil {
			os.Exit(1)
		}
	}
}
<commit_msg>cli: fix panic while running bpf recorder list.<commit_after>// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium

package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"

	"github.com/cilium/cilium/pkg/bpf"
	"github.com/cilium/cilium/pkg/command"
	"github.com/cilium/cilium/pkg/common"
	"github.com/cilium/cilium/pkg/maps/recorder"
)

// bpfRecorderListCmd represents the bpf_recorder_list command
var bpfRecorderListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "List PCAP recorder entries",
	Run: func(_ *cobra.Command, _ []string) {
		common.RequireRootPrivilege("cilium bpf recorder list")
		maps := []recorder.CaptureMap{recorder.CaptureMap4()}
		if getIpv6EnableStatus() {
			maps = append(maps, recorder.CaptureMap6())
		}
		dumpRecorderEntries(maps)
	},
}

func init() {
	bpfRecorderCmd.AddCommand(bpfRecorderListCmd)
	command.AddOutputOption(bpfRecorderListCmd)
}

func dumpRecorderEntries(maps []recorder.CaptureMap) {
	entries := make([]recorder.MapRecord, 0)

	for _, m := range maps {
		if m == nil {
			continue
		}
		path, err := m.Path()
		if err == nil {
			err = m.Open()
		}
		if err != nil {
			if os.IsNotExist(err) {
				fmt.Fprintf(os.Stderr, "Unable to open %s: %s. Skipping.\n", path, err)
				continue
			}
			Fatalf("Unable to open %s: %s", path, err)
		}
		defer m.Close()
		if command.OutputOption() {
			callback := func(key bpf.MapKey, value bpf.MapValue) {
				record := recorder.MapRecord{Key: key.(recorder.RecorderKey), Value: value.(recorder.RecorderEntry)}
				entries = append(entries, record)
			}
			if err = m.DumpWithCallback(callback); err != nil {
				Fatalf("Error while collecting BPF map entries: %s", err)
			}
		} else {
			out, err := m.DumpEntries()
			if err != nil {
				Fatalf("Error while dumping BPF Map: %s", err)
			}
			fmt.Println(out)
		}
	}
	if command.OutputOption() {
		if err := command.PrintOutput(entries); err != nil {
			os.Exit(1)
		}
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package btcwire_test

import (
	"bytes"
	"github.com/conformal/btcwire"
	"io/ioutil"
	"testing"
)

// BenchmarkWriteVarInt1 performs a benchmark on how long it takes to write
// a single byte variable length integer.
func BenchmarkWriteVarInt1(b *testing.B) {
	for i := 0; i < b.N; i++ {
		btcwire.TstWriteVarInt(ioutil.Discard, 0, 1)
	}
}

// BenchmarkWriteVarInt3 performs a benchmark on how long it takes to write
// a three byte variable length integer.
func BenchmarkWriteVarInt3(b *testing.B) {
	for i := 0; i < b.N; i++ {
		btcwire.TstWriteVarInt(ioutil.Discard, 0, 65535)
	}
}

// BenchmarkWriteVarInt5 performs a benchmark on how long it takes to write
// a five byte variable length integer.
func BenchmarkWriteVarInt5(b *testing.B) {
	for i := 0; i < b.N; i++ {
		btcwire.TstWriteVarInt(ioutil.Discard, 0, 4294967295)
	}
}

// BenchmarkWriteVarInt9 performs a benchmark on how long it takes to write
// a nine byte variable length integer.
func BenchmarkWriteVarInt9(b *testing.B) {
	for i := 0; i < b.N; i++ {
		btcwire.TstWriteVarInt(ioutil.Discard, 0, 18446744073709551615)
	}
}

// BenchmarkReadVarInt1 performs a benchmark on how long it takes to write
// a single byte variable length integer.
func BenchmarkReadVarInt1(b *testing.B) {
	buf := []byte{0x01}
	for i := 0; i < b.N; i++ {
		btcwire.TstReadVarInt(bytes.NewBuffer(buf), 0)
	}
}

// BenchmarkReadVarInt3 performs a benchmark on how long it takes to write
// a three byte variable length integer.
func BenchmarkReadVarInt3(b *testing.B) {
	buf := []byte{0x0fd, 0xff, 0xff}
	for i := 0; i < b.N; i++ {
		btcwire.TstReadVarInt(bytes.NewBuffer(buf), 0)
	}
}

// BenchmarkReadVarInt5 performs a benchmark on how long it takes to write
// a five byte variable length integer.
func BenchmarkReadVarInt5(b *testing.B) {
	buf := []byte{0xfe, 0xff, 0xff, 0xff, 0xff}
	for i := 0; i < b.N; i++ {
		btcwire.TstReadVarInt(bytes.NewBuffer(buf), 0)
	}
}

// BenchmarkReadVarInt9 performs a benchmark on how long it takes to write
// a nine byte variable length integer.
func BenchmarkReadVarInt9(b *testing.B) {
	buf := []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
	for i := 0; i < b.N; i++ {
		btcwire.TstReadVarInt(bytes.NewBuffer(buf), 0)
	}
}
<commit_msg>Correct benchmark comments.<commit_after>// Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package btcwire_test

import (
	"bytes"
	"github.com/conformal/btcwire"
	"io/ioutil"
	"testing"
)

// BenchmarkWriteVarInt1 performs a benchmark on how long it takes to write
// a single byte variable length integer.
func BenchmarkWriteVarInt1(b *testing.B) {
	for i := 0; i < b.N; i++ {
		btcwire.TstWriteVarInt(ioutil.Discard, 0, 1)
	}
}

// BenchmarkWriteVarInt3 performs a benchmark on how long it takes to write
// a three byte variable length integer.
func BenchmarkWriteVarInt3(b *testing.B) {
	for i := 0; i < b.N; i++ {
		btcwire.TstWriteVarInt(ioutil.Discard, 0, 65535)
	}
}

// BenchmarkWriteVarInt5 performs a benchmark on how long it takes to write
// a five byte variable length integer.
func BenchmarkWriteVarInt5(b *testing.B) {
	for i := 0; i < b.N; i++ {
		btcwire.TstWriteVarInt(ioutil.Discard, 0, 4294967295)
	}
}

// BenchmarkWriteVarInt9 performs a benchmark on how long it takes to write
// a nine byte variable length integer.
func BenchmarkWriteVarInt9(b *testing.B) {
	for i := 0; i < b.N; i++ {
		btcwire.TstWriteVarInt(ioutil.Discard, 0, 18446744073709551615)
	}
}

// BenchmarkReadVarInt1 performs a benchmark on how long it takes to read
// a single byte variable length integer.
func BenchmarkReadVarInt1(b *testing.B) {
	buf := []byte{0x01}
	for i := 0; i < b.N; i++ {
		btcwire.TstReadVarInt(bytes.NewBuffer(buf), 0)
	}
}

// BenchmarkReadVarInt3 performs a benchmark on how long it takes to read
// a three byte variable length integer.
func BenchmarkReadVarInt3(b *testing.B) {
	buf := []byte{0x0fd, 0xff, 0xff}
	for i := 0; i < b.N; i++ {
		btcwire.TstReadVarInt(bytes.NewBuffer(buf), 0)
	}
}

// BenchmarkReadVarInt5 performs a benchmark on how long it takes to read
// a five byte variable length integer.
func BenchmarkReadVarInt5(b *testing.B) {
	buf := []byte{0xfe, 0xff, 0xff, 0xff, 0xff}
	for i := 0; i < b.N; i++ {
		btcwire.TstReadVarInt(bytes.NewBuffer(buf), 0)
	}
}

// BenchmarkReadVarInt9 performs a benchmark on how long it takes to read
// a nine byte variable length integer.
func BenchmarkReadVarInt9(b *testing.B) {
	buf := []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
	for i := 0; i < b.N; i++ {
		btcwire.TstReadVarInt(bytes.NewBuffer(buf), 0)
	}
}
<|endoftext|>