<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	. "gopkg.in/check.v1"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"strings"
	"vip/test"
)

var (
	_ = Suite(&UploadSuite{})
)

type UploadSuite struct{}

func (s *UploadSuite) SetUpSuite(c *C) {
	setUpSuite(c)
}

func (s *UploadSuite) SetUpTest(c *C) {
	setUpTest(c)

	storage = test.NewStore()
}

func (s *UploadSuite) TestUpload(c *C) {
	authToken = "lalalatokenlalala"

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)

	var u UploadResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
	c.Assert(len(u.Url), Not(Equals), 0)

	uri, err := url.Parse(u.Url)
	c.Assert(err, IsNil)

	c.Assert(uri.Scheme, Equals, "http")
	c.Assert(uri.Host, Equals, "localhost:8080")
	c.Assert(uri.Path[1:13], Equals, "samplebucket")
	c.Assert(strings.HasSuffix(uri.Path, "-2448x3264"), Equals, true)
	c.Assert(recorder.HeaderMap["Content-Type"][0], Equals, "application/json")
}

func (s *UploadSuite) TestUploadWarmup(c *C) {
	authToken = "lalalatokenlalala"

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("X-Vip-Warmup", "s=3,s=100&c=true")
	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)

	var u UploadResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
}

func (s *UploadSuite) TestEmptyUpload(c *C) {
	authToken = "lalalatokenlalala"
	os.Setenv("ALLOWED_ORIGIN", "")

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f := &bytes.Reader{}
	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)

	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)
	c.Assert(recorder.Code, Equals, http.StatusBadRequest)

	var u ErrorResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
	c.Assert(u.Msg, Equals, "File must have size greater than 0")
}

func (s *UploadSuite) TestUnauthorizedUpload(c *C) {
	authToken = "lalalatokenlalala"

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))

	f, err := os.Open("./test/awesome.jpeg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/awesome.jpeg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Content-Type", "image/jpeg")

	m.ServeHTTP(recorder, req)

	fmt.Println(recorder.Body)
	c.Assert(recorder.Code, Equals, http.StatusUnauthorized)
}

func (s *UploadSuite) TestSetOriginData(c *C) {
	authToken = "heyheyheyimatoken"
	origins = []string{"localhost", "*.vokal.io"}

	recorder := httptest.NewRecorder()

	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))

	f, err := os.Open("./test/awesome.jpeg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/awesome.jpeg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Origin", "http://images.vokal.io")
	req.Header.Set("Content-Type", "image/jpeg")

	m.ServeHTTP(recorder, req)
	c.Assert(recorder.Code, Equals, http.StatusCreated)
}

//Check Content-Length of JPG File
func (s *UploadSuite) TestContentLengthJpg(c *C) {
	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	fstat, err := os.Stat("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	data, err := processFile(f, "image/jpeg", "")
	c.Assert(err, IsNil)
	c.Assert(data.Length, Not(Equals), fstat.Size())
}

//Check Content-Length of PNG File
func (s *UploadSuite) TestContentLengthPng(c *C) {
	f, err := os.Open("./test/test_inspiration.png")
	c.Assert(err, IsNil)

	fstat, err := os.Stat("./test/test_inspiration.png")
	c.Assert(err, IsNil)

	data, err := processFile(f, "image/png", "")
	c.Assert(err, IsNil)
	c.Assert(data.Length, Equals, fstat.Size())
}
<commit_msg>Remove print<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	. "gopkg.in/check.v1"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"strings"
	"vip/test"
)

var (
	_ = Suite(&UploadSuite{})
)

type UploadSuite struct{}

func (s *UploadSuite) SetUpSuite(c *C) {
	setUpSuite(c)
}

func (s *UploadSuite) SetUpTest(c *C) {
	setUpTest(c)

	storage = test.NewStore()
}

func (s *UploadSuite) TestUpload(c *C) {
	authToken = "lalalatokenlalala"

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)

	var u UploadResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
	c.Assert(len(u.Url), Not(Equals), 0)

	uri, err := url.Parse(u.Url)
	c.Assert(err, IsNil)

	c.Assert(uri.Scheme, Equals, "http")
	c.Assert(uri.Host, Equals, "localhost:8080")
	c.Assert(uri.Path[1:13], Equals, "samplebucket")
	c.Assert(strings.HasSuffix(uri.Path, "-2448x3264"), Equals, true)
	c.Assert(recorder.HeaderMap["Content-Type"][0], Equals, "application/json")
}

func (s *UploadSuite) TestUploadWarmup(c *C) {
	authToken = "lalalatokenlalala"

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("X-Vip-Warmup", "s=3,s=100&c=true")
	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)

	var u UploadResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
}

func (s *UploadSuite) TestEmptyUpload(c *C) {
	authToken = "lalalatokenlalala"
	os.Setenv("ALLOWED_ORIGIN", "")

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f := &bytes.Reader{}
	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)

	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)
	c.Assert(recorder.Code, Equals, http.StatusBadRequest)

	var u ErrorResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
	c.Assert(u.Msg, Equals, "File must have size greater than 0")
}

func (s *UploadSuite) TestUnauthorizedUpload(c *C) {
	authToken = "lalalatokenlalala"

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))

	f, err := os.Open("./test/awesome.jpeg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/awesome.jpeg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Content-Type", "image/jpeg")

	m.ServeHTTP(recorder, req)

	c.Assert(recorder.Code, Equals, http.StatusUnauthorized)
}

func (s *UploadSuite) TestSetOriginData(c *C) {
	authToken = "heyheyheyimatoken"
	origins = []string{"localhost", "*.vokal.io"}

	recorder := httptest.NewRecorder()

	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))

	f, err := os.Open("./test/awesome.jpeg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/awesome.jpeg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Origin", "http://images.vokal.io")
	req.Header.Set("Content-Type", "image/jpeg")

	m.ServeHTTP(recorder, req)
	c.Assert(recorder.Code, Equals, http.StatusCreated)
}

//Check Content-Length of JPG File
func (s *UploadSuite) TestContentLengthJpg(c *C) {
	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	fstat, err := os.Stat("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	data, err := processFile(f, "image/jpeg", "")
	c.Assert(err, IsNil)
	c.Assert(data.Length, Not(Equals), fstat.Size())
}

//Check Content-Length of PNG File
func (s *UploadSuite) TestContentLengthPng(c *C) {
	f, err := os.Open("./test/test_inspiration.png")
	c.Assert(err, IsNil)

	fstat, err := os.Stat("./test/test_inspiration.png")
	c.Assert(err, IsNil)

	data, err := processFile(f, "image/png", "")
	c.Assert(err, IsNil)
	c.Assert(data.Length, Equals, fstat.Size())
}
<|endoftext|>


<commit_before>package slide

import (
    "github.com/gorilla/mux"
    "fmt"
    "net/http"
    "strconv"
    "bsm/api/character"
)

func Retrieve(w http.ResponseWriter, r *http.Request) (interface{}, error) {
    id, ok := mux.Vars(r)["id"]
    if !ok || id == "" {
        return nil, fmt.Errorf("Missing ID")
    }

    iId, err := strconv.ParseInt(id,0,0)
    if err != nil {
        return nil, fmt.Errorf("Non-numeric ID: %s", id)
    }

    switch int64(iId) {
        case 0:
            ts := NewTitleSlide(
                "Title Slide",
                "Title Slide",
                "A slide with a title",
            )
            ts.id = int64(iId)
            return ts, nil
        case 1:
            is := NewImageSlide(
                "Image Slide",
                "Image Slide",
                "https://placehold.it/300?text=image",
                "An image caption",
            )
            is.id = int64(iId)
            return is, nil
        case 2:
            ns := NewNarrationSlide(
                "Narration Slide",
                character.NewCharacter(
                    "Narrarator",
                    "https://placehold.it/64?text=narr",
                ),
                "Lorem ipsum dolor sit amet.",
            )
            ns.id = int64(iId)
            return ns, nil
    }

    return nil, fmt.Errorf("Invalid slide")
}<commit_msg>unimpliment api/slide/retrieve, not needed<commit_after>package slide

import (
    "fmt"
    "net/http"
)

// returns an error.  There are no current plans to impliment this function.
func Retrieve(w http.ResponseWriter, r *http.Request) (interface{}, error) {
    return nil, fmt.Errorf("Not implimented")
}<|endoftext|>


<commit_before>package zoom // Use this file for /user endpoints

// CreateUserPath - v2 path for creating a user
const CreateUserPath = "/users"

type CreateUserInfo struct {
	Email     string   `json:"email"`
	Type      UserType `json:"type"`
	FirstName string   `json:"first_name,omitempty"`
	LastName  string   `json:"last_name,omitempty"`
	Password  string   `json:"password,omitempty"`
}

// CreateUserOptions are the options to create a user with
type CreateUserOptions struct {
	Action   CreateUserAction `json:"action"`
	UserInfo CreateUserInfo   `json:"user_info"`
}

// CreateUser calls POST /users/{userId}/meetings
func CreateUser(opts CreateUserOptions) (User, error) {
	return defaultClient.CreateUser(opts)
}

// CreateUser calls POST /users
// https://marketplace.zoom.us/docs/api-reference/zoom-api/users/usercreate
func (c *Client) CreateUser(opts CreateUserOptions) (User, error) {
	var ret = User{}
	return ret, c.requestV2(requestV2Opts{
		Method:         Post,
		Path:           CreateUserPath,
		DataParameters: &opts,
		Ret:            &ret,
	})
}
<commit_msg>Add a comment to CreateUserInfo<commit_after>package zoom // Use this file for /user endpoints

// CreateUserPath - v2 path for creating a user
const CreateUserPath = "/users"

// CreateUserInfo are details about a user to create
type CreateUserInfo struct {
	Email     string   `json:"email"`
	Type      UserType `json:"type"`
	FirstName string   `json:"first_name,omitempty"`
	LastName  string   `json:"last_name,omitempty"`
	Password  string   `json:"password,omitempty"`
}

// CreateUserOptions are the options to create a user with
type CreateUserOptions struct {
	Action   CreateUserAction `json:"action"`
	UserInfo CreateUserInfo   `json:"user_info"`
}

// CreateUser calls POST /users/{userId}/meetings
func CreateUser(opts CreateUserOptions) (User, error) {
	return defaultClient.CreateUser(opts)
}

// CreateUser calls POST /users
// https://marketplace.zoom.us/docs/api-reference/zoom-api/users/usercreate
func (c *Client) CreateUser(opts CreateUserOptions) (User, error) {
	var ret = User{}
	return ret, c.requestV2(requestV2Opts{
		Method:         Post,
		Path:           CreateUserPath,
		DataParameters: &opts,
		Ret:            &ret,
	})
}
<|endoftext|>


<commit_before>package users

import (
	"encoding/json"

	deis "github.com/deis/controller-sdk-go"
	"github.com/deis/controller-sdk-go/api"
)

// List users registered with the controller.
func List(c *deis.Client, results int) (api.Users, int, error) {
	body, count, err := c.LimitedRequest("/v2/users/", results)

	if err != nil {
		return []api.User{}, -1, err
	}

	var users []api.User
	if err = json.Unmarshal([]byte(body), &users); err != nil {
		return []api.User{}, -1, err
	}

	return users, count, nil
}
<commit_msg>feat(keys, users): add more godoc fixes (#56)<commit_after>// Package users provides methods for viewing users.
package users

import (
	"encoding/json"

	deis "github.com/deis/controller-sdk-go"
	"github.com/deis/controller-sdk-go/api"
)

// List lists users registered with the controller.
func List(c *deis.Client, results int) (api.Users, int, error) {
	body, count, err := c.LimitedRequest("/v2/users/", results)

	if err != nil {
		return []api.User{}, -1, err
	}

	var users []api.User
	if err = json.Unmarshal([]byte(body), &users); err != nil {
		return []api.User{}, -1, err
	}

	return users, count, nil
}
<|endoftext|>


<commit_before>package endpoint

import (
	"encoding/json"
	"fmt"

	"github.com/pkg/errors"

	"github.com/zrepl/zrepl/zfs"
)

// An instance of this type returned by MakeJobID guarantees
// that that instance's JobID.String() can be used in a ZFS dataset name and hold tag.
type JobID struct {
	jid string
}

func MakeJobID(s string) (JobID, error) {
	if len(s) == 0 {
		return JobID{}, fmt.Errorf("must not be empty string")
	}

	if err := zfs.ComponentNamecheck(s); err != nil {
		return JobID{}, errors.Wrap(err, "muse be usable as a dataset path component")
	}

	if _, err := stepBookmarkNameImpl("pool/ds", 0xface601d, s); err != nil {
		// note that this might still fail due to total maximum name length, but we can't enforce that
		return JobID{}, errors.Wrap(err, "must be usable for a step bookmark")
	}

	if _, err := stepHoldTagImpl(s); err != nil {
		return JobID{}, errors.Wrap(err, "must be usable for a step hold tag")
	}

	if _, err := lastReceivedHoldImpl(s); err != nil {
		return JobID{}, errors.Wrap(err, "must be usabel as a last-recieved-hold tag")
	}

	// FIXME replication cursor bookmark name

	_, err := zfs.NewDatasetPath(s)
	if err != nil {
		return JobID{}, fmt.Errorf("must be usable in a ZFS dataset path: %s", err)
	}

	return JobID{s}, nil
}

func MustMakeJobID(s string) JobID {
	jid, err := MakeJobID(s)
	if err != nil {
		panic(err)
	}
	return jid
}

func (j JobID) expectInitialized() {
	if j.jid == "" {
		panic("use of unitialized JobID")
	}
}

func (j JobID) String() string {
	j.expectInitialized()
	return j.jid
}

var _ json.Marshaler = JobID{}
var _ json.Unmarshaler = (*JobID)(nil)

func (j JobID) MarshalJSON() ([]byte, error) { return json.Marshal(j.jid) }

func (j *JobID) UnmarshalJSON(b []byte) error {
	return json.Unmarshal(b, &j.jid)
}

func (j JobID) MustValidate() { j.expectInitialized() }
<commit_msg>endpoint: fix typos in jobid.go<commit_after>package endpoint

import (
	"encoding/json"
	"fmt"

	"github.com/pkg/errors"

	"github.com/zrepl/zrepl/zfs"
)

// JobID instances returned by MakeJobID() guarantee their JobID.String()
// can be used in ZFS dataset names and hold tags.
type JobID struct {
	jid string
}

func MakeJobID(s string) (JobID, error) {
	if len(s) == 0 {
		return JobID{}, fmt.Errorf("must not be empty string")
	}

	if err := zfs.ComponentNamecheck(s); err != nil {
		return JobID{}, errors.Wrap(err, "must be usable as a dataset path component")
	}

	if _, err := stepBookmarkNameImpl("pool/ds", 0xface601d, s); err != nil {
		// note that this might still fail due to total maximum name length, but we can't enforce that
		return JobID{}, errors.Wrap(err, "must be usable for a step bookmark")
	}

	if _, err := stepHoldTagImpl(s); err != nil {
		return JobID{}, errors.Wrap(err, "must be usable for a step hold tag")
	}

	if _, err := lastReceivedHoldImpl(s); err != nil {
		return JobID{}, errors.Wrap(err, "must be usable as a last-received-hold tag")
	}

	// FIXME replication cursor bookmark name

	_, err := zfs.NewDatasetPath(s)
	if err != nil {
		return JobID{}, fmt.Errorf("must be usable in a ZFS dataset path: %s", err)
	}

	return JobID{s}, nil
}

func MustMakeJobID(s string) JobID {
	jid, err := MakeJobID(s)
	if err != nil {
		panic(err)
	}
	return jid
}

func (j JobID) expectInitialized() {
	if j.jid == "" {
		panic("use of uninitialized JobID")
	}
}

func (j JobID) String() string {
	j.expectInitialized()
	return j.jid
}

var _ json.Marshaler = JobID{}
var _ json.Unmarshaler = (*JobID)(nil)

func (j JobID) MarshalJSON() ([]byte, error) { return json.Marshal(j.jid) }

func (j *JobID) UnmarshalJSON(b []byte) error {
	return json.Unmarshal(b, &j.jid)
}

func (j JobID) MustValidate() { j.expectInitialized() }
<|endoftext|>


<commit_before>package object

// Meeting :

import (
  "strings"
  "fmt"

)

type Meeting struct {
  Title string
  Spon string
  Pr []string
  Start string
  End string
}

func (meeting Meeting) init(Pr []string, St string, Et string, Title string) {
  meeting.Pr = Pr
  meeting.Start = St
  meeting.End = Et
  meeting.Title = Title
}

func (meeting Meeting) CopyMeeting (ano_meeting Meeting) {
  meeting.Pr = ano_meeting.Pr
  meeting.Start = ano_meeting.Start
  meeting.End = ano_meeting.End
  meeting.Title = ano_meeting.Title
}

func (meeting Meeting) GetParticipator() []string {
    return meeting.Pr
}

func (meeting Meeting) SetParticipator(prs []string) {
  var length = len(prs)
  for i := 0; i < length; i++ {
    meeting.Pr[i]= prs[i]
  }
}

func (meeting Meeting) GetStartTime() string {
  return meeting.Start
}

func (meeting Meeting) SetStartTime() (St string) {
  meeting.Start = St
}

func (meeting Meeting) GetSponsor() string{
  return meeting.Spon
}

func (meeting Meeting) SetSponsor(Sp string) {
  meeting.Spon = Sp
}

func (meeting Meeting) GetEndTime() string {
  return meeting.End
}

func (meeting Meeting) SetEndTime() (Et string) {
  meeting.End = Et
}

func (meeting Meeting) GetTitle() string {
  return meeting.Title
}

func (meeting Meeting) SetTitle(Title string) {
  meeting.Title = Title
}

func (meeting Meeting) IsParticipator(Un string) bool {
  var i int
  for i= 0; i< len(meeting.Pr); i++ {
    if strings.EqualFold(meeting.Pr[i], Un)== true {
        return true
    }
  }
  return false
}

func (meeting Meeting) DeleteParticipator(Un string) {
  var i int
  num := len(meeting.Pr)
  for i= 0; i< num; i++ {
    if strings.EqualFold(meeting.Pr[i], un) == true {
      meeting.Pr = append(meeting.Pr[:i], meeting.Pr[i+1:]...)
      break
    }
  }
  num = len(meeting.Pr)
  if num == 0 {
    //delete meeting
  }
}

func (meeting Meeting) AddParticipator(Un string) bool {
  // if time not overlap
  var i int
  var flag bool
  flag = true
  num := len(meeting.Pr)
  for i= 0; i< num; i++ {
    if strings.EqualFold(meeting.Pr[i], un) == true {
      flag = false
      fmt.Println("AddParticipator failed! The user has already in!")
      return false
    }
  }
  if flag == true {
    meeting.Pr = append(meeting.Pr, un)
    return true
  }
  return false
}

<commit_msg>Update meeting.go<commit_after>package entity

// Meeting :

import (
  "strings"
  "fmt"
  "time"

)

type Meeting struct {
  Title string
  Spon string
  Pr []string
  Start string
  End string
}

func (meeting Meeting) Init(Pr []string, St string, Et string, Title string) {
  meeting.Pr = Pr
  meeting.Start = St
  meeting.End = Et
  meeting.Title = Title
}

func (meeting Meeting) CopyMeeting (ano_meeting Meeting) {
  meeting.Pr = ano_meeting.Pr
  meeting.Start = ano_meeting.Start
  meeting.End = ano_meeting.End
  meeting.Title = ano_meeting.Title
}

func (meeting Meeting) GetParticipator() []string {
    return meeting.Pr
}

func (meeting Meeting) SetParticipator(prs []string) {
  var length = len(prs)
  for i := 0; i < length; i++ {
    meeting.Pr[i]= prs[i]
  }
}

func (meeting Meeting) GetStartTime() string {
  return meeting.Start
}

func (meeting Meeting) SetStartTime() (St string) {
  meeting.Start = St
}

func (meeting Meeting) GetSponsor() string{
  return meeting.Spon
}

func (meeting Meeting) SetSponsor(Sp string) {
  meeting.Spon = Sp
}

func (meeting Meeting) GetEndTime() string {
  return meeting.End
}

func (meeting Meeting) SetEndTime() (Et string) {
  meeting.End = Et
}

func (meeting Meeting) GetTitle() string {
  return meeting.Title
}

func (meeting Meeting) SetTitle(Title string) {
  meeting.Title = Title
}

func (meeting Meeting) IsParticipator(Un string) bool {
  if Un == "" {
    fmt.Println("Null Participator Name!")
    return false
  }
  var i int
  for i= 0; i< len(meeting.Pr); i++ {
    if strings.EqualFold(meeting.Pr[i], Un)== true {
      return true
    }
  }
  return false
}

func CheckIfMeetingTimeOverlap(startTime string, endTime string) bool {
  meetingsList := getAllMeetings();
  for tit, meeting := range meetingsList; {
    if meeting.Start < endTime && meeting.Start > startTime {
      return true
    } else if meeting.End < endTime && meeting.End > startTime{
      return true
    }
  }
  return false
}

func CheckIfPrTimeOverlap(Un string, startTime string, endTime string) bool {
  flag := CheckIfMeetingTimeOverlap(startTime, endTime)
  if flag == true {
    return true
  } else {
    meetingsList := getAllMeetings();
    for tit, meeting := range meetingsList; {
      for pr := meeting.Pr {
        if pr == Un || meeting.spon == Un {
          if meeting.Start < endTime && meeting.Start > startTime {
            return true
          } else if meeting.End < endTime && meeting.End > startTime{
            return true
          }
        }
      }
    }
  }
  return false
}

func (meeting Meeting) DeleteParticipator(Un string) {
  if Un == "" {
    fmt.Println("Null Participator Name!")
    return
  }
  var i int
  num := len(meeting.Pr)
  for i= 0; i< num; i++ {
    if strings.EqualFold(meeting.Pr[i], un) == true {
      meeting.Pr = append(meeting.Pr[:i], meeting.Pr[i+1:]...)
      break
    }
  }
  num = len(meeting.Pr)
  if num == 0 {
    DeleteMeeting(meeting.Title)
  }
}

func (meeting Meeting) AddParticipator(Un string) bool {
  if Un == "" {
    fmt.Println("Null Participator Name!")
    return false
  }
  var i int
  var flag bool
  flag = true
  num := len(meeting.Pr)
  for i= 0; i< num; i++ {
    if strings.EqualFold(meeting.Pr[i], un) == true {
      flag = false
      fmt.Println("AddParticipator failed! The user has already in!")
      return false
    }
  }
  if flag == true {
      // if time not overlap
    isOverlap := checkIfPrTimeOverlap(Un, meetings.Start, meetings.End)
    if isOverlap == true {
      fmt.Println("Overlap\n")
      return false
    }
    meeting.Pr = append(meeting.Pr, un)
    return true
  }
  return false
}

func QueryMeetingByTitle(Title string) Meeting {
  meetingsList := getAllMeetings();
  var count int
  for title, meeting := range meetingsList; i++ {
    if title == Title {
      fmt.Println("The meeting you search exits!\n")
      return meeting
    }
  }

  fmt.Println("No such meeting!\n")
  return nil
}

func DeleteMeeting(Title string) {

}

func ClearMeeting() {

}

<|endoftext|>


<commit_before>package env

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

//Read the preexisting config file into a Config struct to be used later on in the program. Need to work on adding the read config into the struck
func ReadConfig(configfile string) *Config {
	configfilebyte, err := ioutil.ReadFile(configfile)
	if err != nil {
		fmt.Println(err)
	}
	configfilestring := strings.SplitAfter(string(configfilebyte[:]), "\r\n")
	configstruct := new(Config)
	configstruct.configtostruct(configfilestring)
	//fmt.Println(configfilestring)
	//configparams := []string{"client", "clientver", "protover", "url", "port"}
	//for a := range configparams {
	//b := stringsearch(configfilestring, configparams[a])
	//fmt.Println(b)

	//}
	return configstruct
}

func (h *Config) configtostruct(configstring []string) *Config {
	h.Client = stringsearch(configstring, "client")
	h.Clientver, _ = strconv.Atoi(stringsearch(configstring, "clientver"))
	h.Protover, _ = strconv.Atoi(stringsearch(configstring, "protover"))
	h.Url = stringsearch(configstring, "url")
	h.Port, _ = strconv.Atoi(stringsearch(configstring, "port"))
	return h
}

func stringsearch(searchstrings []string, substring string) string {
	for g := range searchstrings {
		result := strings.Contains(searchstrings[g], substring)
		if result == true {
			configlinesplit := strings.SplitAfter(searchstrings[g], "=")
			//configlinesplit = strings.TrimSpace(configlinesplit)
			//fmt.Println(strings.TrimSpace(configlinesplit[1]))
			return strings.TrimSpace(configlinesplit[1])
		}
	}
	return ""
}
<commit_msg>Return "" needs to be fixed<commit_after>package env

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

//Read the preexisting config file into a Config struct to be used later on in the program. Need to work on adding the read config into the struck
func ReadConfig(configfile string) *Config {
	configfilebyte, err := ioutil.ReadFile(configfile)
	if err != nil {
		fmt.Println(err)
	}
	configfilestring := strings.SplitAfter(string(configfilebyte[:]), "\r\n")
	configstruct := new(Config)
	configstruct.configtostruct(configfilestring)
	//fmt.Println(configfilestring)
	//configparams := []string{"client", "clientver", "protover", "url", "port"}
	//for a := range configparams {
	//b := stringsearch(configfilestring, configparams[a])
	//fmt.Println(b)

	//}
	return configstruct
}

func (h *Config) configtostruct(configstring []string) *Config {
	h.Client = stringsearch(configstring, "client")
	h.Clientver, _ = strconv.Atoi(stringsearch(configstring, "clientver"))
	h.Protover, _ = strconv.Atoi(stringsearch(configstring, "protover"))
	h.Url = stringsearch(configstring, "url")
	h.Port, _ = strconv.Atoi(stringsearch(configstring, "port"))
	return h
}

func stringsearch(searchstrings []string, substring string) string {
	for g := range searchstrings {
		result := strings.Contains(searchstrings[g], substring)
		if result == true {
			configlinesplit := strings.SplitAfter(searchstrings[g], "=")
			//configlinesplit = strings.TrimSpace(configlinesplit)
			//fmt.Println(strings.TrimSpace(configlinesplit[1]))
			return strings.TrimSpace(configlinesplit[1])
		}
	}
	//if I didn't like you so much I would slap the taste from your mouth -- jak
	return ""
}
<|endoftext|>


<commit_before>package utils

import (
	"fmt"
	"reflect"

	"github.com/weixinhost/litedb"
)

func ParseWhereMap(wheres interface{}) (string, []interface{}) {

	whereMap := make(map[string]interface{}, 0)
	valList := make([]interface{}, 0)

	if reflect.ValueOf(wheres).IsValid() {
		if reflect.TypeOf(wheres).Kind() == reflect.Map {
			whereMap = wheres.(map[string]interface{})
		}
	}

	where := "1 "

	for k, v := range whereMap {

		vs := litedb.ToStr(v)
		if reflect.TypeOf(v).Kind() != reflect.Map {
			where = where + fmt.Sprintf(" AND `%s` = ? ", k)
			valList = append(valList, vs)
		}
	}

	for k, v := range whereMap {

		if reflect.TypeOf(v).Kind() == reflect.Map {

			vi := v.(map[string]interface{})

			t, ok1 := vi["type"]

			vv, ok2 := vi["value"]

			if ok1 && ok2 {

				switch t.(string) {

				case "=":
					{

						where = where + fmt.Sprintf(" AND `%s` = ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case ">":
					{

						where = where + fmt.Sprintf(" AND `%s` > ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}
				case "<":
					{

						where = where + fmt.Sprintf(" AND `%s` < ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case "<=":
					{

						where = where + fmt.Sprintf(" AND `%s` <= ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case ">=":
					{

						where = where + fmt.Sprintf(" AND `%s` >= ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case "<>":
					{

						where = where + fmt.Sprintf(" AND `%s` <> ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case "not in":
					{

						valsStr := ""

						for j := 0; j < len(vv.([]interface{})); j++ {
							valsStr = valsStr + "?"

							if j < len(vv.([]interface{}))-1 {
								valsStr = valsStr + ","
							}
						}
						where = where + fmt.Sprintf(" AND `%s` NOT IN(%s) ", k, valsStr)
						valList = append(valList, vv.([]interface{})...)

						break
					}

				case "in":
					{

						valsStr := ""

						for j := 0; j < len(vv.([]interface{})); j++ {
							valsStr = valsStr + "?"

							if j < len(vv.([]interface{}))-1 {
								valsStr = valsStr + ","
							}
						}
						where = where + fmt.Sprintf(" AND `%s` IN(%s) ", k, valsStr)
						valList = append(valList, vv.([]interface{})...)
						break
					}

				}
			}
		}
	}

	if len(where) > 2 {
		where = string([]byte(where)[6:])
	}

	return where, valList
}
<commit_msg>Update parse.go<commit_after>package utils

import (
	"fmt"
	"reflect"
	"strings"

	"github.com/weixinhost/litedb"
)

func ParseWhereMap(wheres interface{}) (string, []interface{}) {

	whereMap := make(map[string]interface{}, 0)
	valList := make([]interface{}, 0)

	if reflect.ValueOf(wheres).IsValid() {
		if reflect.TypeOf(wheres).Kind() == reflect.Map {
			whereMap = wheres.(map[string]interface{})
		}
	}

	where := "1 "

	for k, v := range whereMap {

		vs := litedb.ToStr(v)
		if reflect.TypeOf(v).Kind() != reflect.Map {
			where = where + fmt.Sprintf(" AND `%s` = ? ", k)
			valList = append(valList, vs)
		}
	}

	for k, v := range whereMap {

		if reflect.TypeOf(v).Kind() == reflect.Map {

			vi := v.(map[string]interface{})

			t, ok1 := vi["type"]

			vv, ok2 := vi["value"]

			if ok1 && ok2 {

				tStr := strings.ToLower(t.(string))

				switch tStr {

				case "=":
					{

						where = where + fmt.Sprintf(" AND `%s` = ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case ">":
					{

						where = where + fmt.Sprintf(" AND `%s` > ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}
				case "<":
					{

						where = where + fmt.Sprintf(" AND `%s` < ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case "<=":
					{

						where = where + fmt.Sprintf(" AND `%s` <= ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case ">=":
					{

						where = where + fmt.Sprintf(" AND `%s` >= ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case "<>":
					{

						where = where + fmt.Sprintf(" AND `%s` <> ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}
				case "like":
					{

						where = where + fmt.Sprintf(" AND `%s` LIKE ? ", k)
						valList = append(valList, litedb.ToStr(vv))

						break
					}

				case "not in":
					{

						valsStr := ""

						for j := 0; j < len(vv.([]interface{})); j++ {
							valsStr = valsStr + "?"

							if j < len(vv.([]interface{}))-1 {
								valsStr = valsStr + ","
							}
						}
						where = where + fmt.Sprintf(" AND `%s` NOT IN(%s) ", k, valsStr)
						valList = append(valList, vv.([]interface{})...)

						break
					}

				case "in":
					{

						valsStr := ""

						for j := 0; j < len(vv.([]interface{})); j++ {
							valsStr = valsStr + "?"

							if j < len(vv.([]interface{}))-1 {
								valsStr = valsStr + ","
							}
						}
						where = where + fmt.Sprintf(" AND `%s` IN(%s) ", k, valsStr)
						valList = append(valList, vv.([]interface{})...)
						break
					}

				}
			}
		}
	}

	if len(where) > 2 {
		where = string([]byte(where)[6:])
	}

	return where, valList
}
<|endoftext|>


<commit_before>// Copyright 2013 Unknown
//
// 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 utils

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"regexp"
	"strings"
	"unicode"
	"unicode/utf8"
)

// IsExist returns if a file or directory exists
func IsExist(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}

var readmePat = regexp.MustCompile(`^[Rr][Ee][Aa][Dd][Mm][Ee](?:$|\.)`)

func IsDocFile(n string) bool {
	if strings.HasSuffix(n, ".go") && n[0] != '_' && n[0] != '.' {
		return true
	}
	return readmePat.MatchString(n)
}

// A link describes the (HTML) link information for an identifier.
// The zero value of a link represents "no link".
//
type Link struct {
	Path, Name, Comment string // package path, identifier name, and comments.
}

func isLetter(l uint8) bool {
	return (l >= 'A' && l <= 'Z') || (l >= 'a' && l <= 'z')
}

// FormatCode highlights keywords and adds HTML links to them.
func FormatCode(w io.Writer, code string, links []*Link) {
	length := len(code) // Length of whole code.
	if length == 0 {
		return
	}

	strTag := uint8(0)      // Indicates what kind of string is chekcing.
	isString := false       // Indicates if right now is checking string.
	isComment := false      // Indicates if right now is checking comments.
	isBlockComment := false // Indicates if right now is checking block comments.
	last := 0               // Start index of the word.
	pos := 0                // Current index.

	for {
		// Cut words.
	CutWords:
		for {
			if !isLetter(code[pos]) {
				if !isComment {
					switch {
					case (code[pos] == '\'' || code[pos] == '"' || code[pos] == '`') && code[pos-1] != '\\': // String.
						if !isString {
							// Set string tag.
							strTag = code[pos]
							isString = true
						} else {
							// Check string tag.
							if code[pos] == strTag {
								// Handle string highlight.
								break CutWords
							}
						}
					case !isString && code[pos] == '/': //&& (pos > 0) && code[pos+1] == '/':
						isComment = true
					case !isString && code[pos] > 47 && code[pos] < 58: // Number
					case !isString && code[pos] == '_' && code[pos-1] != ' ': // _
					case !isString && (code[pos] != '.' || code[pos] == '\n'):
						break CutWords
					}
				} else {
					if isBlockComment {
						// End of block comments.
						if code[pos] == '/' && code[pos-1] == '*' {
							break CutWords
						}
					} else {
						switch {
						case code[pos] == '*' && code[pos-1] == '/':
							// Start of block comments.
							isBlockComment = true
						case code[pos] == '\n':
							break CutWords
						}
					}
				}
			}

			if pos == length-1 {
				break CutWords
			}
			pos++
		}

		seg := code[last : pos+1]
	CheckLink:
		switch {
		case isComment:
			isComment = false
			isBlockComment = false
			fmt.Fprintf(w, `<span class="com">%s</span>`, seg)
		case isString:
			isString = false
			fmt.Fprintf(w, `<span class="str">%s</span>`, seg)
		case pos-last > 1:
			// Check if the last word of the paragraphy.
			l := len(seg)
			if pos+1 == length {
				l++
			}

			// Check keywords.
			switch seg[:l-1] {
			case "return", "break":
				fmt.Fprintf(w, `<span class="ret">%s</span>%s`, seg[:l-1], seg[l-1:])
				break CheckLink
			case "var", "func", "range", "for", "if", "else", "type", "struct":
				fmt.Fprintf(w, `<span class="key">%s</span>%s`, seg[:l-1], seg[l-1:])
				break CheckLink
			case "true", "false", "nil":
				fmt.Fprintf(w, `<span class="boo">%s</span>%s`, seg[:l-1], seg[l-1:])
				break CheckLink
			case "new", "append", "make", "panic", "recover", "len", "cap", "copy":
				fmt.Fprintf(w, `<span class="bui">%s</span>%s`, seg[:l-1], seg[l-1:])
				break CheckLink
			}

			// Check links.
			link, ok := findType(seg[:l-1], links)
			if ok {
				switch {
				case len(link.Path) == 0 && len(link.Name) > 0:
					// Exported types in current package.
					fmt.Fprintf(w, `<a class="int" title="%s" href="#%s">%s</a>%s`,
						link.Comment, link.Name, link.Name, seg[l-1:])
				case len(link.Path) > 0 && len(link.Name) > 0:
					fmt.Fprintf(w, `<a class="ext" title="%s" target="_blank" href="%s">%s</a>%s`,
						link.Comment, link.Path, link.Name, seg[l-1:])
				}
			} else {
				fmt.Fprintf(w, "%s", seg)
			}
		default:
			fmt.Fprintf(w, "%s", seg)
		}

		last = pos + 1
		pos++
		// End of code.
		if pos == length {
			fmt.Fprintf(w, "%s", code[last:])
			return
		}
	}
}

func findType(name string, links []*Link) (*Link, bool) {
	// This is for functions and types from imported packages.
	i := strings.Index(name, ".")
	var left, right string
	if i > -1 {
		left = name[:i+1]
		right = name[i+1:]
	}

	for _, l := range links {
		if i == -1 {
			// Exported types in current package.
			if l.Name == name {
				return l, true
			}
		} else {
			// Functions and types from imported packages.
			if l.Name == left {
				return &Link{Name: name, Path: "/" + l.Path + "#" + right}, true
			}
		}
	}
	return nil, false
}

var badSynopsisPrefixes = []string{
	"Autogenerated by Thrift Compiler",
	"Automatically generated ",
	"Auto-generated by ",
	"Copyright ",
	"COPYRIGHT ",
	`THE SOFTWARE IS PROVIDED "AS IS"`,
	"TODO: ",
	"vim:",
}

// Synopsis extracts the first sentence from s. All runs of whitespace are
// replaced by a single space.
func Synopsis(s string) string {

	parts := strings.SplitN(s, "\n\n", 2)
	s = parts[0]

	var buf []byte
	const (
		other = iota
		period
		space
	)
	last := space
Loop:
	for i := 0; i < len(s); i++ {
		b := s[i]
		switch b {
		case ' ', '\t', '\r', '\n':
			switch last {
			case period:
				break Loop
			case other:
				buf = append(buf, ' ')
				last = space
			}
		case '.':
			last = period
			buf = append(buf, b)
		default:
			last = other
			buf = append(buf, b)
		}
	}

	// Ensure that synopsis fits an App Engine datastore text property.
	const m = 400
	if len(buf) > m {
		buf = buf[:m]
		if i := bytes.LastIndex(buf, []byte{' '}); i >= 0 {
			buf = buf[:i]
		}
		buf = append(buf, " ..."...)
	}

	s = string(buf)

	r, n := utf8.DecodeRuneInString(s)
	if n < 0 || unicode.IsPunct(r) || unicode.IsSymbol(r) {
		// ignore Markdown headings, editor settings, Go build constraints, and * in poorly formatted block comments.
		s = ""
	} else {
		for _, prefix := range badSynopsisPrefixes {
			if strings.HasPrefix(s, prefix) {
				s = ""
				break
			}
		}
	}

	return s
}
<commit_msg>improve code view highlight<commit_after>// Copyright 2013 Unknown
//
// 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 utils

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"regexp"
	"strings"
	"unicode"
	"unicode/utf8"
)

// IsExist returns if a file or directory exists
func IsExist(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}

var readmePat = regexp.MustCompile(`^[Rr][Ee][Aa][Dd][Mm][Ee](?:$|\.)`)

func IsDocFile(n string) bool {
	if strings.HasSuffix(n, ".go") && n[0] != '_' && n[0] != '.' {
		return true
	}
	return readmePat.MatchString(n)
}

// A link describes the (HTML) link information for an identifier.
// The zero value of a link represents "no link".
//
type Link struct {
	Path, Name, Comment string // package path, identifier name, and comments.
}

func isLetter(l uint8) bool {
	return (l >= 'A' && l <= 'Z') || (l >= 'a' && l <= 'z')
}

// FormatCode highlights keywords and adds HTML links to them.
func FormatCode(w io.Writer, code string, links []*Link) {
	length := len(code) // Length of whole code.
	if length == 0 {
		return
	}

	strTag := uint8(0)      // Indicates what kind of string is chekcing.
	isString := false       // Indicates if right now is checking string.
	isComment := false      // Indicates if right now is checking comments.
	isBlockComment := false // Indicates if right now is checking block comments.
	last := 0               // Start index of the word.
	pos := 0                // Current index.

	for {
		// Cut words.
	CutWords:
		for {
			if !isLetter(code[pos]) {
				if !isComment {
					switch {
					case (code[pos] == '\'' || code[pos] == '"' || code[pos] == '`') && code[pos-1] != '\\': // String.
						if !isString {
							// Set string tag.
							strTag = code[pos]
							isString = true
						} else {
							// Check string tag.
							if code[pos] == strTag {
								// Handle string highlight.
								break CutWords
							}
						}
					case !isString && code[pos] == '/': //&& (pos > 0) && code[pos+1] == '/':
						isComment = true
					case !isString && code[pos] > 47 && code[pos] < 58: // Number
					case !isString && code[pos] == '_' && code[pos-1] != ' ': // _
					case !isString && (code[pos] != '.' || code[pos] == '\n'):
						break CutWords
					}
				} else {
					if isBlockComment {
						// End of block comments.
						if code[pos] == '/' && code[pos-1] == '*' {
							break CutWords
						}
					} else {
						switch {
						case code[pos] == '*' && code[pos-1] == '/':
							// Start of block comments.
							isBlockComment = true
						case code[pos] == '\n':
							break CutWords
						}
					}
				}
			}

			if pos == length-1 {
				break CutWords
			}
			pos++
		}

		seg := code[last : pos+1]
	CheckLink:
		switch {
		case isComment:
			isComment = false
			isBlockComment = false
			fmt.Fprintf(w, `<span class="com">%s</span>`, seg)
		case isString:
			isString = false
			fmt.Fprintf(w, `<span class="str">%s</span>`, seg)
		case pos-last > 1:
			// Check if the last word of the paragraphy.
			l := len(seg)
			keyword := seg
			if !isLetter(seg[l-1]) {
				keyword = seg[:l-1]
			} else {
				l++
			}

			// Check keywords.
			switch keyword {
			case "return", "break":
				fmt.Fprintf(w, `<span class="ret">%s</span>%s`, keyword, seg[l-1:])
				break CheckLink
			case "func", "range", "for", "if", "else", "type", "struct", "select", "case", "var", "const":
				fmt.Fprintf(w, `<span class="key">%s</span>%s`, keyword, seg[l-1:])
				break CheckLink
			case "true", "false", "nil":
				fmt.Fprintf(w, `<span class="boo">%s</span>%s`, keyword, seg[l-1:])
				break CheckLink
			case "new", "append", "make", "panic", "recover", "len", "cap", "copy":
				fmt.Fprintf(w, `<span class="bui">%s</span>%s`, keyword, seg[l-1:])
				break CheckLink
			}

			// Check links.
			link, ok := findType(seg[:l-1], links)
			if ok {
				switch {
				case len(link.Path) == 0 && len(link.Name) > 0:
					// Exported types in current package.
					fmt.Fprintf(w, `<a class="int" title="%s" href="#%s">%s</a>%s`,
						link.Comment, link.Name, link.Name, seg[l-1:])
				case len(link.Path) > 0 && len(link.Name) > 0:
					fmt.Fprintf(w, `<a class="ext" title="%s" target="_blank" href="%s">%s</a>%s`,
						link.Comment, link.Path, link.Name, seg[l-1:])
				}
			} else {
				fmt.Fprintf(w, "%s", seg)
			}
		default:
			fmt.Fprintf(w, "%s", seg)
		}

		last = pos + 1
		pos++
		// End of code.
		if pos == length {
			fmt.Fprintf(w, "%s", code[last:])
			return
		}
	}
}

func findType(name string, links []*Link) (*Link, bool) {
	// This is for functions and types from imported packages.
	i := strings.Index(name, ".")
	var left, right string
	if i > -1 {
		left = name[:i+1]
		right = name[i+1:]
	}

	for _, l := range links {
		if i == -1 {
			// Exported types in current package.
			if l.Name == name {
				return l, true
			}
		} else {
			// Functions and types from imported packages.
			if l.Name == left {
				return &Link{Name: name, Path: "/" + l.Path + "#" + right}, true
			}
		}
	}
	return nil, false
}

var badSynopsisPrefixes = []string{
	"Autogenerated by Thrift Compiler",
	"Automatically generated ",
	"Auto-generated by ",
	"Copyright ",
	"COPYRIGHT ",
	`THE SOFTWARE IS PROVIDED "AS IS"`,
	"TODO: ",
	"vim:",
}

// Synopsis extracts the first sentence from s. All runs of whitespace are
// replaced by a single space.
func Synopsis(s string) string {

	parts := strings.SplitN(s, "\n\n", 2)
	s = parts[0]

	var buf []byte
	const (
		other = iota
		period
		space
	)
	last := space
Loop:
	for i := 0; i < len(s); i++ {
		b := s[i]
		switch b {
		case ' ', '\t', '\r', '\n':
			switch last {
			case period:
				break Loop
			case other:
				buf = append(buf, ' ')
				last = space
			}
		case '.':
			last = period
			buf = append(buf, b)
		default:
			last = other
			buf = append(buf, b)
		}
	}

	// Ensure that synopsis fits an App Engine datastore text property.
	const m = 400
	if len(buf) > m {
		buf = buf[:m]
		if i := bytes.LastIndex(buf, []byte{' '}); i >= 0 {
			buf = buf[:i]
		}
		buf = append(buf, " ..."...)
	}

	s = string(buf)

	r, n := utf8.DecodeRuneInString(s)
	if n < 0 || unicode.IsPunct(r) || unicode.IsSymbol(r) {
		// ignore Markdown headings, editor settings, Go build constraints, and * in poorly formatted block comments.
		s = ""
	} else {
		for _, prefix := range badSynopsisPrefixes {
			if strings.HasPrefix(s, prefix) {
				s = ""
				break
			}
		}
	}

	return s
}
<|endoftext|>


<commit_before>// +-------------------------------------------------------------------------
// | Copyright (C) 2016 Yunify, Inc.
// +-------------------------------------------------------------------------
// | Licensed under the Apache License, Version 2.0 (the "License");
// | you may not use this work except in compliance with the License.
// | You may obtain a copy of the License in the LICENSE file, or 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 utils

var capitalizedToCapitalizedWordsMap = map[string]string{
	"Dns":     "DNS",
	"Dyn":     "DYN",
	"Eip":     "EIP",
	"Keypair": "KeyPair",
	"Vxnet":   "VxNet",
}

var lowerCaseToLowercaseWordsMap = map[string]string{
	"lastest": "latest", // Fix typo
}

var lowerCaseToCapitalizedWordsMap = map[string]string{
	"acl":           "ACL",
	"cors":          "CORS",
	"cpu":           "CPU",
	"datadir":       "DataDir",
	"dhcp":          "DHCP",
	"dns":           "DNS",
	"dyn":           "DYN",
	"eip":           "EIP",
	"eips":          "EIPs",
	"http":          "HTTP",
	"icp":           "ICP",
	"id":            "ID",
	"ids":           "IDs",
	"innodb":        "InnoDB",
	"io":            "IO",
	"ip":            "IP",
	"ips":           "IPs",
	"ipset":         "IPSet",
	"ipsets":        "IPSets",
	"keypair":       "KeyPair",
	"keypairs":      "KeyPairs",
	"lastest":       "Latest", // Fix typo
	"loadbalancer":  "LoadBalancer",
	"loadbalancers": "LoadBalancers",
	"md5":           "MD5",
	"newsid":        "NewSID",
	"nic":           "NIC",
	"os":            "OS",
	"opt":           "OPT",
	"qingstor":      "QingStor",
	"qingcloud":     "QingCloud",
	"qs":            "QS",
	"rdb":           "RDB",
	"rdbs":          "RDBs",
	"sql":           "SQL",
	"tmp":           "TMP",
	"tmpdir":        "TMPDir",
	"topslave":      "TopSlave",
	"trx":           "TRX",
	"ui":            "UI",
	"uri":           "URI",
	"url":           "URL",
	"usb":           "USB",
	"vcpus":         "VCPUs",
	"vxnet":         "VxNet",
	"vxnets":        "VxNets",
}

var abbreviateWordsMap = []string{
	"ACL",
	"CORS",
	"CPU",
	"DHCP",
	"DNS",
	"DYN",
	"EIP",
	"ETag",
	"IaaS",
	"ICP",
	"ID",
	"IO",
	"IP",
	"IPSets",
	"MD5",
	"NIC",
	"OAuth",
	"OS",
	"OPT",
	"QingStor",
	"QingCloud",
	"QS",
	"RDB",
	"SQL",
	"SSO",
	"TMP",
	"TMPDir",
	"TRX",
	"UI",
	"URL",
	"VCPUs",
	"VxNet",
}
<commit_msg>utils: Add UUID into words map<commit_after>// +-------------------------------------------------------------------------
// | Copyright (C) 2016 Yunify, Inc.
// +-------------------------------------------------------------------------
// | Licensed under the Apache License, Version 2.0 (the "License");
// | you may not use this work except in compliance with the License.
// | You may obtain a copy of the License in the LICENSE file, or 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 utils

var capitalizedToCapitalizedWordsMap = map[string]string{
	"Dns":     "DNS",
	"Dyn":     "DYN",
	"Eip":     "EIP",
	"Keypair": "KeyPair",
	"Vxnet":   "VxNet",
}

var lowerCaseToLowercaseWordsMap = map[string]string{
	"lastest": "latest", // Fix typo
}

var lowerCaseToCapitalizedWordsMap = map[string]string{
	"acl":           "ACL",
	"cors":          "CORS",
	"cpu":           "CPU",
	"datadir":       "DataDir",
	"dhcp":          "DHCP",
	"dns":           "DNS",
	"dyn":           "DYN",
	"eip":           "EIP",
	"eips":          "EIPs",
	"http":          "HTTP",
	"icp":           "ICP",
	"id":            "ID",
	"ids":           "IDs",
	"innodb":        "InnoDB",
	"io":            "IO",
	"ip":            "IP",
	"ips":           "IPs",
	"ipset":         "IPSet",
	"ipsets":        "IPSets",
	"keypair":       "KeyPair",
	"keypairs":      "KeyPairs",
	"lastest":       "Latest", // Fix typo
	"loadbalancer":  "LoadBalancer",
	"loadbalancers": "LoadBalancers",
	"md5":           "MD5",
	"newsid":        "NewSID",
	"nic":           "NIC",
	"os":            "OS",
	"opt":           "OPT",
	"qingstor":      "QingStor",
	"qingcloud":     "QingCloud",
	"qs":            "QS",
	"rdb":           "RDB",
	"rdbs":          "RDBs",
	"sql":           "SQL",
	"tmp":           "TMP",
	"tmpdir":        "TMPDir",
	"topslave":      "TopSlave",
	"trx":           "TRX",
	"ui":            "UI",
	"uri":           "URI",
	"url":           "URL",
	"usb":           "USB",
	"uuid":          "UUID",
	"vcpus":         "VCPUs",
	"vxnet":         "VxNet",
	"vxnets":        "VxNets",
}

var abbreviateWordsMap = []string{
	"ACL",
	"CORS",
	"CPU",
	"DHCP",
	"DNS",
	"DYN",
	"EIP",
	"ETag",
	"IaaS",
	"ICP",
	"ID",
	"IO",
	"IP",
	"IPSets",
	"MD5",
	"NIC",
	"OAuth",
	"OS",
	"OPT",
	"QingStor",
	"QingCloud",
	"QS",
	"RDB",
	"SQL",
	"SSO",
	"TMP",
	"TMPDir",
	"TRX",
	"UI",
	"URL",
	"UUID",
	"VCPUs",
	"VxNet",
}
<|endoftext|>


<commit_before>// Package toggle implements condition variables usable in selects
//
// A toggle consists of two channels, r and w. A read from r will succeed iff
// there was a send to w since the last read. A send to w will never block.
// When w is closed, r is closed and all associated resources are released,
// but only after a potential value written to w was read.
package toggle

func create(last bool) (chan interface{}, chan interface{}) {
	r, w := make(chan interface{}), make(chan interface{})

	go func() {
		var v interface{}
		var ok bool
		for {
			v, ok = <-w
			if !ok {
				w = nil
			}
		L:
			for {
				select {
				case V, ok := <-w:
					if last {
						v = V
					}
					if !ok {
						w = nil
					}
				case r <- v:
					v = nil
					break L
				}
			}

			if w == nil {
				close(r)
				return
			}
		}
	}()

	return r, w
}

// First returns a new toggle, that yields the first value written to w since
// the last read.
func First() (r <-chan interface{}, w chan<- interface{}) {
	return create(false)
}

// Last returns a new toggle, that yields the last value written to w since the
// last read.
func Last() (r <-chan interface{}, w chan<- interface{}) {
	return create(true)
}
<commit_msg>toggle: Add import comment<commit_after>// Package toggle implements condition variables usable in selects
//
// A toggle consists of two channels, r and w. A read from r will succeed iff
// there was a send to w since the last read. A send to w will never block.
// When w is closed, r is closed and all associated resources are released,
// but only after a potential value written to w was read.
package toggle // import "merovius.de/go-misc/toggle"

func create(last bool) (chan interface{}, chan interface{}) {
	r, w := make(chan interface{}), make(chan interface{})

	go func() {
		var v interface{}
		var ok bool
		for {
			v, ok = <-w
			if !ok {
				w = nil
			}
		L:
			for {
				select {
				case V, ok := <-w:
					if last {
						v = V
					}
					if !ok {
						w = nil
					}
				case r <- v:
					v = nil
					break L
				}
			}

			if w == nil {
				close(r)
				return
			}
		}
	}()

	return r, w
}

// First returns a new toggle, that yields the first value written to w since
// the last read.
func First() (r <-chan interface{}, w chan<- interface{}) {
	return create(false)
}

// Last returns a new toggle, that yields the last value written to w since the
// last read.
func Last() (r <-chan interface{}, w chan<- interface{}) {
	return create(true)
}
<|endoftext|>


<commit_before>/**
 * This program simply reads a plaintext file containing URLs of RSS or Atom feeds,
 * one per line, and issues a request to a running CENO Reader to follow each.
 */

package main

import (
    "fmt"
    "os"
    "strings"
    "bytes"
    "encoding/json"
    "io/ioutil"
    "net/http"
    "time"
    "strconv"
)

const FOLLOW_URL string = "http://localhost:3096/follow"

func sendFollowRequest(feedUrl string) {
    marshalled, _ := json.Marshal(map[string]string{
        "url": feedUrl,
    })
    reader := bytes.NewReader(marshalled)
    request, err := http.NewRequest("POST", FOLLOW_URL, reader)
    if err != nil {
        fmt.Println("Could not construct request to follow " + feedUrl)
        fmt.Println(err)
    } else {
        request.Header.Set("Content-Type", "application/json")
        client := &http.Client{}
        response, reqErr := client.Do(request)
        if reqErr != nil {
            fmt.Println("Encountered an error requesting to follow " + feedUrl)
            fmt.Println(reqErr)
        } else {
            fmt.Println("Successfully issued request to follow " + feedUrl)
            responseText, _ := ioutil.ReadAll(response.Body)
            fmt.Println(string(responseText))
            response.Body.Close()
        }
    }
}

func main() {
    if len(os.Args) != 3 {
        fmt.Printf("Usage: %s <sources.list> <minutes to sleep between requests>\n", os.Args[0])
        return
    }
    contentBytes, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println("Could not open " + os.Args[1])
        fmt.Println(err)
        return
    }
    minutes, convertErr := strconv.Atoi(os.Args[2])
    if convertErr != nil {
      fmt.Println("The second argument must be an integer, the number of minutes to sleep between follow requests.")
      fmt.Println(convertErr)
      return
    }
    lines := strings.Split(string(contentBytes), "\n")
    for _, line := range lines {
        if len(line) > 0 {
            fmt.Println("\nFollowing " + line)
            sendFollowRequest(line)
            // Add some rate limiting in there so we don't choke the database
            <-time.After(time.Duration(minutes) * time.Minute)
        }
    }
}
<commit_msg>Have the follower tool support sending a title<commit_after>/**
 * This program simply reads a plaintext file containing URLs of RSS or Atom feeds,
 * one per line, and issues a request to a running CENO Reader to follow each.
 */

package main

import (
    "fmt"
    "os"
    "strings"
    "bytes"
    "encoding/json"
    "io/ioutil"
    "net/http"
    "time"
    "strconv"
)

const FOLLOW_URL string = "http://localhost:3096/follow"

func sendFollowRequest(feedUrl, title string) {
    marshalled, _ := json.Marshal(map[string]string{
        "url": feedUrl,
        "title": title,
    })
    reader := bytes.NewReader(marshalled)
    request, err := http.NewRequest("POST", FOLLOW_URL, reader)
    if err != nil {
        fmt.Println("Could not construct request to follow " + feedUrl)
        fmt.Println(err)
    } else {
        request.Header.Set("Content-Type", "application/json")
        client := &http.Client{}
        response, reqErr := client.Do(request)
        if reqErr != nil {
            fmt.Println("Encountered an error requesting to follow " + feedUrl)
            fmt.Println(reqErr)
        } else {
            fmt.Println("Successfully issued request to follow " + feedUrl)
            responseText, _ := ioutil.ReadAll(response.Body)
            fmt.Println(string(responseText))
            response.Body.Close()
        }
    }
}

func main() {
    if len(os.Args) != 3 {
        fmt.Printf("Usage: %s <sources.list> <minutes to sleep between requests>\n", os.Args[0])
        return
    }
    contentBytes, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println("Could not open " + os.Args[1])
        fmt.Println(err)
        return
    }
    minutes, convertErr := strconv.Atoi(os.Args[2])
    if convertErr != nil {
      fmt.Println("The second argument must be an integer, the number of minutes to sleep between follow requests.")
      fmt.Println(convertErr)
      return
    }
    lines := strings.Split(string(contentBytes), "\n")
    for _, line := range lines {
        if len(line) > 0 {
            parts := strings.Split(line, " ")
            if len(parts) == 1 {
              fmt.Println("Could not create a follow request for", parts[0])
              fmt.Println("Each line in the sources file should contain a URL and a title. E.g. http://site.com site")
              continue
            }
            title := strings.Join(parts[1:], " ")
            fmt.Printf("\nFollowing %s\nTitle: %s\n", parts[0], title)
            sendFollowRequest(parts[0], title)
            // Add some rate limiting in there so we don't choke the database
            <-time.After(time.Duration(minutes) * time.Minute)
        }
    }
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/bobziuchkovski/writ"
)

type Codegen struct {
	baseSubCommand

	CodegenAll    CodegenAll
	CodegenEnum   CodegenEnum
	CodegenReader CodegenReader

	OutputFile     string
	OutputFileTest string
	EnumOutputFile string
}

func (c *Codegen) Run(p writ.Path, positional []string) {
	c.CodegenAll.Run(p, positional)
}

func (c *Codegen) Name() string {
	return "codegen"
}

func codegenPackageNameOrErr(positional []string) string {
	if len(positional) > 1 {
		errAndQuit("More than one positional argument provided, expecting only package")
	}
	if len(positional) == 0 {
		return "."
	}
	return positional[0]
}

func (c *Codegen) Description() string {
	return "Automatically generates code to satisfy PropertyReader and generate Enum boilerplate"
}

func (c *Codegen) HelpText() string {
	return c.Name() +

		` automatically generates boilerplate PropertyReader and enums based
on structs in your package.

Running this command and not any of its subcommands is equivalent to running
'codegen all'. If PKGNAME parameter is missing, "." is assumed.

See 'boardgame-util/lib/codegen' for more on its behavior.

The defaults are set reasonably so that you can use go:generate very easily by
including 'boardgame-util codegen' after the go generate magic string.

See examplepkg/ for a very simple example.`

}

func (c *Codegen) SubcommandObjects() []SubcommandObject {
	return []SubcommandObject{
		&c.CodegenAll,
		&c.CodegenReader,
		&c.CodegenEnum,
	}
}

func (c *Codegen) Usage() string {
	return "PKGNAME"
}

func (c *Codegen) WritOptions() []*writ.Option {

	return []*writ.Option{
		{
			Names: []string{"out"},
			Decoder: writ.NewDefaulter(
				writ.NewOptionDecoder(&c.OutputFile),
				"auto_reader.go",
			),
			Description: "Defines which file to render output to. WARNING: it will be overwritten!",
		},
		{
			Names: []string{"outtest"},
			Decoder: writ.NewDefaulter(
				writ.NewOptionDecoder(&c.OutputFileTest),
				"auto_reader_test.go",
			),
			Description: "For structs in files that end in _test.go, what is the filename they should be exported to?",
		},
		{
			Names: []string{"enumout"},
			Decoder: writ.NewDefaulter(
				writ.NewOptionDecoder(&c.EnumOutputFile),
				"auto_enum.go",
			),
			Description: "Where to output the auto-enum file. WARNING: it will be overwritten!",
		},
	}
}
<commit_msg>Made the `codegen` help print out the precise magic string to generate (break it up so it doesn't ACTUALLY trigger go generate in this package). Part of #655.<commit_after>package main

import (
	"github.com/bobziuchkovski/writ"
)

type Codegen struct {
	baseSubCommand

	CodegenAll    CodegenAll
	CodegenEnum   CodegenEnum
	CodegenReader CodegenReader

	OutputFile     string
	OutputFileTest string
	EnumOutputFile string
}

func (c *Codegen) Run(p writ.Path, positional []string) {
	c.CodegenAll.Run(p, positional)
}

func (c *Codegen) Name() string {
	return "codegen"
}

func codegenPackageNameOrErr(positional []string) string {
	if len(positional) > 1 {
		errAndQuit("More than one positional argument provided, expecting only package")
	}
	if len(positional) == 0 {
		return "."
	}
	return positional[0]
}

func (c *Codegen) Description() string {
	return "Automatically generates code to satisfy PropertyReader and generate Enum boilerplate"
}

func (c *Codegen) HelpText() string {
	return c.Name() +

		` automatically generates boilerplate PropertyReader and enums based
on structs in your package.

Running this command and not any of its subcommands is equivalent to running
'codegen all'. If PKGNAME parameter is missing, "." is assumed.

See 'boardgame-util/lib/codegen' for more on its behavior.

The defaults are set reasonably so that you can use it easily with go generate
by including the following line in your package:

` + "//go:" + "generate boardgame-util codegen" + `

See examplepkg/ for a very simple example.`

}

func (c *Codegen) SubcommandObjects() []SubcommandObject {
	return []SubcommandObject{
		&c.CodegenAll,
		&c.CodegenReader,
		&c.CodegenEnum,
	}
}

func (c *Codegen) Usage() string {
	return "PKGNAME"
}

func (c *Codegen) WritOptions() []*writ.Option {

	return []*writ.Option{
		{
			Names: []string{"out"},
			Decoder: writ.NewDefaulter(
				writ.NewOptionDecoder(&c.OutputFile),
				"auto_reader.go",
			),
			Description: "Defines which file to render output to. WARNING: it will be overwritten!",
		},
		{
			Names: []string{"outtest"},
			Decoder: writ.NewDefaulter(
				writ.NewOptionDecoder(&c.OutputFileTest),
				"auto_reader_test.go",
			),
			Description: "For structs in files that end in _test.go, what is the filename they should be exported to?",
		},
		{
			Names: []string{"enumout"},
			Decoder: writ.NewDefaulter(
				writ.NewOptionDecoder(&c.EnumOutputFile),
				"auto_enum.go",
			),
			Description: "Where to output the auto-enum file. WARNING: it will be overwritten!",
		},
	}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/elastic/libbeat/common"
	"github.com/fsouza/go-dockerclient"
	"time"
)

type EventGenerator struct {
	networkStats map[string]NetworkData
}

func (d *EventGenerator) getContainerEvent(container *docker.APIContainers, stats *docker.Stats) common.MapStr {
	event := common.MapStr{
		"timestamp":      common.Time(stats.Read),
		"type":           "container",
		"containerID":    container.ID,
		"containerNames": container.Names,
		"container": common.MapStr{
			"id":         container.ID,
			"command":    container.Command,
			"created":    time.Unix(container.Created, 0),
			"image":      container.Image,
			"labels":     container.Labels,
			"names":      container.Names,
			"ports":      d.convertContainerPorts(&container.Ports),
			"sizeRootFs": container.SizeRootFs,
			"sizeRw":     container.SizeRw,
			"status":     container.Status,
		},
	}
	return event
}

func (d *EventGenerator) getCpuEvent(container *docker.APIContainers, stats *docker.Stats) common.MapStr {

	calculator := CPUCalculator{
		CPUData{stats.PreCPUStats.CPUUsage.PercpuUsage, stats.PreCPUStats.CPUUsage.TotalUsage, stats.PreCPUStats.CPUUsage.UsageInKernelmode, stats.PreCPUStats.CPUUsage.UsageInUsermode},
		CPUData{stats.CPUStats.CPUUsage.PercpuUsage, stats.CPUStats.CPUUsage.TotalUsage, stats.CPUStats.CPUUsage.UsageInKernelmode, stats.CPUStats.CPUUsage.UsageInUsermode},
	}

	event := common.MapStr{
		"timestamp":      common.Time(stats.Read),
		"type":           "cpu",
		"containerID":    container.ID,
		"containerNames": container.Names,
		"cpu": common.MapStr{
			"percpuUsage":       calculator.perCpuUsage(),
			"totalUsage":        calculator.totalUsage(),
			"usageInKernelmode": calculator.usageInKernelmode(),
			"usageInUsermode":   calculator.usageInUsermode(),
		},
	}

	return event
}

func (d *EventGenerator) getNetworkEvent(container *docker.APIContainers, stats *docker.Stats) common.MapStr {
	newNetworkData := NetworkData{
		stats.Read,
		stats.Network.RxBytes,
		stats.Network.RxDropped,
		stats.Network.RxErrors,
		stats.Network.RxPackets,
		stats.Network.TxBytes,
		stats.Network.TxDropped,
		stats.Network.TxErrors,
		stats.Network.TxPackets,
	}

	var event common.MapStr

	oldNetworkData, ok := d.networkStats[container.ID]

	if ok {
		calculator := NetworkCalculator{oldNetworkData, newNetworkData}
		event = common.MapStr{
			"timestamp":      common.Time(stats.Read),
			"type":           "net",
			"containerID":    container.ID,
			"containerNames": container.Names,
			"net": common.MapStr{
				"rxBytes_ps":   calculator.getRxBytesPerSecond(),
				"rxDropped_ps": calculator.getRxDroppedPerSecond(),
				"rxErrors_ps":  calculator.getRxErrorsPerSecond(),
				"rxPackets_ps": calculator.getRxPacketsPerSecond(),
				"txBytes_ps":   calculator.getTxBytesPerSecond(),
				"txDropped_ps": calculator.getTxDroppedPerSecond(),
				"txErrors_ps":  calculator.getTxErrorsPerSecond(),
				"txPackets_ps": calculator.getTxPacketsPerSecond(),
			},
		}
	} else {
		event = common.MapStr{
			"timestamp":      common.Time(stats.Read),
			"type":           "net",
			"containerID":    container.ID,
			"containerNames": container.Names,
			"net": common.MapStr{
				"rxBytes":   0,
				"rxDropped": 0,
				"rxErrors":  0,
				"rxPackets": 0,
				"txBytes":   0,
				"txDropped": 0,
				"txErrors":  0,
				"txPackets": 0,
			},
		}
	}

	d.networkStats[container.ID] = newNetworkData
	return event
}

func (d *EventGenerator) getMemoryEvent(container *docker.APIContainers, stats *docker.Stats) common.MapStr {
	event := common.MapStr{
		"timestamp":      common.Time(stats.Read),
		"type":           "memory",
		"containerID":    container.ID,
		"containerNames": container.Names,
		"memory": common.MapStr{
			"failcnt":  stats.MemoryStats.Failcnt,
			"limit":    stats.MemoryStats.Limit,
			"maxUsage": stats.MemoryStats.MaxUsage,
			"usage":    stats.MemoryStats.Usage,
			"usage_p":  (float64(stats.MemoryStats.Usage) / float64(stats.MemoryStats.Limit)) * 100,
		},
	}

	return event
}

func (d *EventGenerator) convertContainerPorts(ports *[]docker.APIPort) []map[string]interface{} {
	var outputPorts []map[string]interface{}
	for _, port := range *ports {
		outputPort := common.MapStr{
			"ip":          port.IP,
			"privatePort": port.PrivatePort,
			"publicPort":  port.PublicPort,
			"type":        port.Type,
		}
		outputPorts = append(outputPorts, outputPort)
	}

	return outputPorts
}

func (d *EventGenerator) cleanOldStats(containers []docker.APIContainers) {
	found := false
	for containerStatKey, _ := range d.networkStats {
		for _, container := range containers {
			if container.ID == containerStatKey {
				found = true
				continue
			}
		}
		if !found {
			delete(d.networkStats, containerStatKey)
		}
	}
}
<commit_msg>resolve network suffix field issue<commit_after>package main

import (
	"github.com/elastic/libbeat/common"
	"github.com/fsouza/go-dockerclient"
	"time"
)

type EventGenerator struct {
	networkStats map[string]NetworkData
}

func (d *EventGenerator) getContainerEvent(container *docker.APIContainers, stats *docker.Stats) common.MapStr {
	event := common.MapStr{
		"timestamp":      common.Time(stats.Read),
		"type":           "container",
		"containerID":    container.ID,
		"containerNames": container.Names,
		"container": common.MapStr{
			"id":         container.ID,
			"command":    container.Command,
			"created":    time.Unix(container.Created, 0),
			"image":      container.Image,
			"labels":     container.Labels,
			"names":      container.Names,
			"ports":      d.convertContainerPorts(&container.Ports),
			"sizeRootFs": container.SizeRootFs,
			"sizeRw":     container.SizeRw,
			"status":     container.Status,
		},
	}
	return event
}

func (d *EventGenerator) getCpuEvent(container *docker.APIContainers, stats *docker.Stats) common.MapStr {

	calculator := CPUCalculator{
		CPUData{stats.PreCPUStats.CPUUsage.PercpuUsage, stats.PreCPUStats.CPUUsage.TotalUsage, stats.PreCPUStats.CPUUsage.UsageInKernelmode, stats.PreCPUStats.CPUUsage.UsageInUsermode},
		CPUData{stats.CPUStats.CPUUsage.PercpuUsage, stats.CPUStats.CPUUsage.TotalUsage, stats.CPUStats.CPUUsage.UsageInKernelmode, stats.CPUStats.CPUUsage.UsageInUsermode},
	}

	event := common.MapStr{
		"timestamp":      common.Time(stats.Read),
		"type":           "cpu",
		"containerID":    container.ID,
		"containerNames": container.Names,
		"cpu": common.MapStr{
			"percpuUsage":       calculator.perCpuUsage(),
			"totalUsage":        calculator.totalUsage(),
			"usageInKernelmode": calculator.usageInKernelmode(),
			"usageInUsermode":   calculator.usageInUsermode(),
		},
	}

	return event
}

func (d *EventGenerator) getNetworkEvent(container *docker.APIContainers, stats *docker.Stats) common.MapStr {
	newNetworkData := NetworkData{
		stats.Read,
		stats.Network.RxBytes,
		stats.Network.RxDropped,
		stats.Network.RxErrors,
		stats.Network.RxPackets,
		stats.Network.TxBytes,
		stats.Network.TxDropped,
		stats.Network.TxErrors,
		stats.Network.TxPackets,
	}

	var event common.MapStr

	oldNetworkData, ok := d.networkStats[container.ID]

	if ok {
		calculator := NetworkCalculator{oldNetworkData, newNetworkData}
		event = common.MapStr{
			"timestamp":      common.Time(stats.Read),
			"type":           "net",
			"containerID":    container.ID,
			"containerNames": container.Names,
			"net": common.MapStr{
				"rxBytes_ps":   calculator.getRxBytesPerSecond(),
				"rxDropped_ps": calculator.getRxDroppedPerSecond(),
				"rxErrors_ps":  calculator.getRxErrorsPerSecond(),
				"rxPackets_ps": calculator.getRxPacketsPerSecond(),
				"txBytes_ps":   calculator.getTxBytesPerSecond(),
				"txDropped_ps": calculator.getTxDroppedPerSecond(),
				"txErrors_ps":  calculator.getTxErrorsPerSecond(),
				"txPackets_ps": calculator.getTxPacketsPerSecond(),
			},
		}
	} else {
		event = common.MapStr{
			"timestamp":      common.Time(stats.Read),
			"type":           "net",
			"containerID":    container.ID,
			"containerNames": container.Names,
			"net": common.MapStr{
				"rxBytes_ps":   0,
				"rxDropped_ps": 0,
				"rxErrors_ps":  0,
				"rxPackets_ps": 0,
				"txBytes_ps":   0,
				"txDropped_ps": 0,
				"txErrors_ps":  0,
				"txPackets_ps": 0,
			},
		}
	}

	d.networkStats[container.ID] = newNetworkData
	return event
}

func (d *EventGenerator) getMemoryEvent(container *docker.APIContainers, stats *docker.Stats) common.MapStr {
	event := common.MapStr{
		"timestamp":      common.Time(stats.Read),
		"type":           "memory",
		"containerID":    container.ID,
		"containerNames": container.Names,
		"memory": common.MapStr{
			"failcnt":  stats.MemoryStats.Failcnt,
			"limit":    stats.MemoryStats.Limit,
			"maxUsage": stats.MemoryStats.MaxUsage,
			"usage":    stats.MemoryStats.Usage,
			"usage_p":  (float64(stats.MemoryStats.Usage) / float64(stats.MemoryStats.Limit)) * 100,
		},
	}

	return event
}

func (d *EventGenerator) convertContainerPorts(ports *[]docker.APIPort) []map[string]interface{} {
	var outputPorts []map[string]interface{}
	for _, port := range *ports {
		outputPort := common.MapStr{
			"ip":          port.IP,
			"privatePort": port.PrivatePort,
			"publicPort":  port.PublicPort,
			"type":        port.Type,
		}
		outputPorts = append(outputPorts, outputPort)
	}

	return outputPorts
}

func (d *EventGenerator) cleanOldStats(containers []docker.APIContainers) {
	found := false
	for containerStatKey, _ := range d.networkStats {
		for _, container := range containers {
			if container.ID == containerStatKey {
				found = true
				continue
			}
		}
		if !found {
			delete(d.networkStats, containerStatKey)
		}
	}
}
<|endoftext|>