Esempio n. 1
0
func printList(l *list.List) {
	elements := make([]interface{}, 0, l.Len())
	Do(l, func(i interface{}) {
		elements = append(elements, i)
	})
	log.Printf("%v", elements)
}
Esempio n. 2
0
func Commits(ctx *middleware.Context, params martini.Params) {
	userName := params["username"]
	repoName := params["reponame"]
	branchName := params["branchname"]

	brs, err := models.GetBranches(userName, repoName)
	if err != nil {
		ctx.Handle(200, "repo.Commits", err)
		return
	} else if len(brs) == 0 {
		ctx.Handle(404, "repo.Commits", nil)
		return
	}

	var commits *list.List
	if models.IsBranchExist(userName, repoName, branchName) {
		commits, err = models.GetCommitsByBranch(userName, repoName, branchName)
	} else {
		commits, err = models.GetCommitsByCommitId(userName, repoName, branchName)
	}

	if err != nil {
		ctx.Handle(404, "repo.Commits", err)
		return
	}

	ctx.Data["Username"] = userName
	ctx.Data["Reponame"] = repoName
	ctx.Data["CommitCount"] = commits.Len()
	ctx.Data["Commits"] = commits
	ctx.Data["IsRepoToolbarCommits"] = true
	ctx.HTML(200, "repo/commits")
}
Esempio n. 3
0
func drain_pending(p *list.List) int {
	var ret int
	for p.Len() > 0 {
		ret = wait_pending_front(p)
	}
	return ret
}
Esempio n. 4
0
//add Nodes we here about in the reply to the shortList, only if that node is not in the sentList
func addResponseNodesToSL(fnodes []FoundNode, shortList *list.List, sentMap map[ID]bool, targetID ID) {
	for i := 0; i < len(fnodes); i++ {
		foundNode := &fnodes[i]
		_, inSentList := sentMap[foundNode.NodeID]
		//if the foundNode is already in sentList, dont add it to shortList
		if inSentList {
			continue
		}
		for e := shortList.Front(); e != nil; e = e.Next() {
			if e.Value.(*FoundNode).NodeID.Equals(foundNode.NodeID) {
				break
			}
			dist := e.Value.(*FoundNode).NodeID.Distance(targetID)
			foundNodeDist := foundNode.NodeID.Distance(targetID)
			//if responseNode is closer than node in ShortList, add it
			if foundNodeDist < dist {
				shortList.InsertBefore(foundNode, e)
				//keep the shortList length < Kconst
				if shortList.Len() > KConst {
					shortList.Remove(shortList.Back())
				}
				//node inserted! getout
				break
			}
		}
	}
}
Esempio n. 5
0
func (frame *Frame) Eval(interp *Interp, script string) string {
	var ok bool
	var words *list.List

	retval := ""

	for len(script) != 0 {
		ok, _, script = ParseComment(script)
		if ok {
			continue
		}

		_, words, script = ParseWords(script)

		if len(script) == 0 || script[0] == '\n' || script[0] == ';' {
			if len(script) != 0 {
				script = script[1:]
			}

			if words.Len() == 0 {
				continue
			}

			retval = interp.EvalWords(words)
		}
	}

	return retval

}
Esempio n. 6
0
func (frame *Frame) BindArguments(cmd Command, words *list.List) bool {
	len := len(cmd.args)

	for i, arg := range cmd.args {
		name := arg.GetName()
		value := arg.GetValue()

		if i == (len-1) && name == "args" {
			tmp := []string{}

			for words.Len() != 0 {
				word := words.Remove(words.Front()).(Word).String()
				tmp = append(tmp, word)
			}

			value = StringToValueP(strings.Join(tmp, " "))
		} else {
			if words.Len() != 0 {
				word := Value(words.Remove(words.Front()).(Word).String())
				value = &word
			}
		}

		frame.SetValue(name, value)
	}

	return true
}
func StackSpec(c Context) {
	stack := new(list.List)

	c.Specify("An empty stack", func() {

		c.Specify("contains no elements", func() {
			c.Expect(stack.Len()).Equals(0)
		})
	})

	c.Specify("When elements are pushed onto a stack", func() {
		stack.PushFront("pushed first")
		stack.PushFront("pushed last")

		c.Specify("then it contains some elements", func() {
			c.Expect(stack.Len()).NotEquals(0)
		})
		c.Specify("the element pushed last is popped first", func() {
			poppedFirst := stack.Remove(stack.Front())
			c.Expect(poppedFirst).Equals("pushed last")
		})
		c.Specify("the element pushed first is popped last", func() {
			stack.Remove(stack.Front())
			poppedLast := stack.Remove(stack.Front())
			c.Expect(poppedLast).Equals("pushed first")
		})
	})
}
Esempio n. 8
0
func makeDrawPriorityList(li *list.List) DrawPriorityList {
	l := make([](*ConcreteElement), li.Len())
	for o, i := li.Front(), 0; o != nil; o, i = o.Next(), i+1 {
		l[i] = o.Value.(*ConcreteElement)
	}
	return DrawPriorityList(l)
}
Esempio n. 9
0
func makeAbstraction(idents *list.List, body Expression) Expression {
	for idents.Len() > 0 {
		ident,_ := listPopFront(idents).(string);
		body = Abstraction{ident, body};
	}
	return body;
}
Esempio n. 10
0
// Run Pattern
func (network *Network) RunPattern(input *list.List) (output *list.List, err error) {

	network.debug("resetting network\n")
	// send reset
	ch := make(chan string)
	for _, v := range network.command {
		v <- message{message: Reset, reply: ch}
		// wait for response
		_ = <-ch
	}
	// make sure pattern is same size as inputs
	if input.Len() != network.inputs.Len() {
		return nil, errors.New("invalid argument")
	}
	network.info("Run pattern to network: ")
	PrintList(input)
	i := uint(0)
	for v := input.Front(); v != nil; v = v.Next() {
		network.trace("\tsending %v to input %v\n", v, i)
		network.inputs[i].c <- v.Value.(Data) * network.inputs[i].weight
		i++
	}
	// get output
	output = new(list.List)
	for i := 0; i < network.outputs.Len(); i++ {
		o := <-network.outputs[i].c
		output.PushBack(o)
	}
	network.info(" \\- output is: ")
	PrintList(output)
	return output, err
}
Esempio n. 11
0
// bootstrapStores bootstraps uninitialized stores once the cluster
// and node IDs have been established for this node. Store IDs are
// allocated via a sequence id generator stored at a system key per
// node.
func (n *Node) bootstrapStores(bootstraps *list.List, stopper *stop.Stopper) {
	log.Infof("bootstrapping %d store(s)", bootstraps.Len())
	if n.ClusterID == "" {
		panic("ClusterID missing during store bootstrap of auxiliary store")
	}

	// Bootstrap all waiting stores by allocating a new store id for
	// each and invoking store.Bootstrap() to persist.
	inc := int64(bootstraps.Len())
	firstID, err := allocateStoreIDs(n.Descriptor.NodeID, inc, n.ctx.DB)
	if err != nil {
		log.Fatal(err)
	}
	sIdent := roachpb.StoreIdent{
		ClusterID: n.ClusterID,
		NodeID:    n.Descriptor.NodeID,
		StoreID:   firstID,
	}
	for e := bootstraps.Front(); e != nil; e = e.Next() {
		s := e.Value.(*storage.Store)
		if err := s.Bootstrap(sIdent, stopper); err != nil {
			log.Fatal(err)
		}
		if err := s.Start(stopper); err != nil {
			log.Fatal(err)
		}
		n.stores.AddStore(s)
		sIdent.StoreID++
		log.Infof("bootstrapped store %s", s)
		// Done regularly in Node.startGossip, but this cuts down the time
		// until this store is used for range allocations.
		s.GossipStore()
	}
}
Esempio n. 12
0
// Adds the given story id and bayes factor to the given list if it
// is higher than at least one of the ones already in the list
func addIfHigh(scores *list.List, length int, storyid int64, k float64) {

	s := score{storyid: storyid, score: k}

	// Add the score if the list is empty
	last := scores.Back()
	if last == nil {
		scores.PushBack(s)
		return
	}

	if scores.Len() < length {
		insertScore(scores, length, s)
		return
	}

	// Add the score to the list if it is high enough
	lowest, ok := last.Value.(score)
	if !ok {
		log.Fatal("Could not extract score from sorted list")
	}

	if k < lowest.score {
		return
	}

	// If this point is reached, we insert the score
	insertScore(scores, length, s)
}
Esempio n. 13
0
func outOfOrder(l *list.List) {
	iTotal := 25
	if iTotal > l.Len() {
		iTotal = l.Len()
	}
	ll := make([]*list.List, iTotal)

	for i := 0; i < iTotal; i++ {
		ll[i] = list.New()
	}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for e := l.Front(); e != nil; e = e.Next() {
		fpath, ok := e.Value.(string)
		if !ok {
			panic("The path is invalid string")
		}
		if rand.Int()%2 == 0 {
			ll[r.Intn(iTotal)].PushFront(fpath)
		} else {
			ll[r.Intn(iTotal)].PushBack(fpath)
		}
	}

	r0 := rand.New(rand.NewSource(time.Now().UnixNano()))
	l.Init()
	for i := 0; i < iTotal; i++ {
		if r0.Intn(2) == 0 {
			l.PushBackList(ll[i])
		} else {
			l.PushFrontList(ll[i])
		}
		ll[i].Init()
	}
}
Esempio n. 14
0
func List2IntPairsArray(ls *list.List) []IntPair {
	out := make([]IntPair, ls.Len())
	for i, l := 0, ls.Front(); i < ls.Len() && l != nil; i, l = i+1, l.Next() {
		out[i] = l.Value.(IntPair)
	}
	return out
}
Esempio n. 15
0
func convertArgumentsToSlice(arguments *list.List) []string {
	argumentSlice := make([]string, 0, arguments.Len())
	for e := arguments.Front(); e != nil; e = e.Next() {
		argumentSlice = append(argumentSlice, e.Value.(string))
	}
	return argumentSlice
}
Esempio n. 16
0
// pushMetric adds the metric to the end of the list and returns a comma separated string of the
// previous 61 entries.  We return 61 instead of 60 (an hour) because the chart on the client
// tracks deltas between these values - there is nothing to compare the first value against.
func pushMetric(history *list.List, ev expvar.Var) string {
	history.PushBack(ev.String())
	if history.Len() > 61 {
		history.Remove(history.Front())
	}
	return JoinStringList(history)
}
Esempio n. 17
0
func (this *CSRKB) fillCSRTables(nv int, rels *list.List) {
	tmpA := List2IntPairsArray(rels)
	sort.Sort(IntPairsArray(tmpA))
	rels = IntPairsArray2List(tmpA)

	this.edges = make([]int, rels.Len())
	this.firstEdge = make([]int, nv)
	this.numEdges = make([]int, nv)
	this.outCoef = make([]float64, nv)

	n := 0
	r := 0

	p := rels.Front()
	for p != nil && n < nv {
		this.firstEdge[n] = r
		for p != nil && p.Value.(IntPair).first == n {
			this.edges[r] = p.Value.(IntPair).second
			r++
			p = p.Next()
		}
		this.numEdges[n] = r - this.firstEdge[n]
		this.outCoef[n] = 1 / float64(this.numEdges[n])
		n++
	}
}
Esempio n. 18
0
func filter(idx int, vals, bits *list.List) []interface{} {
	if vals == nil || bits == nil {
		return nil
	}

	var shifted uint = 0

	valsPerCase := make([]interface{}, vals.Len())

	for i, v, b := 0, vals.Front(), bits.Front(); v != nil && b != nil; v, b = v.Next(), b.Next() {
		valIdx := idx >> shifted
		mask := int(math.Pow(2, float64(b.Value.(uint))) - 1)
		valIdx &= mask

		if valIdx >= len(v.Value.([]interface{})) {
			return nil
		}

		valsPerCase[i] = v.Value.([]interface{})[valIdx]
		i++

		shifted += b.Value.(uint)
	}

	return valsPerCase
}
Esempio n. 19
0
func houseKeeping(get, give chan interface{},
	factory func() interface{}) {
	q := new(list.List)
	for {
		if q.Len() == 0 {
			atomic.AddInt64(&makes, 1)
			q.PushFront(queued{when: time.Now(), data: factory()})
		}

		element := q.Front()
		timeout := time.NewTimer(time.Minute)
		select {
		case b := <-give:
			timeout.Stop()
			q.PushFront(queued{when: time.Now(), data: b})

		case get <- element.Value.(queued).data:
			timeout.Stop()
			q.Remove(element)

		case <-timeout.C:
			e := q.Front()
			for e != nil {
				n := e.Next()
				if time.Since(e.Value.(queued).when) > time.Minute {
					q.Remove(e)
					e.Value = nil
				}
				e = n
			}
		}
	}
}
Esempio n. 20
0
func Delete(e Elem, L *list.List) bool {
	ret := false

	if L.Len() == 0 {
		return ret
	}
	back := L.Back()
	if e.GetTime() > back.Value.(Elem).GetTime() {
		return ret
	}

	el := L.Front()
Loop:
	for i := 0; el != nil; i++ {
		elt := el.Value.(Elem).GetTime()
		if elt > e.GetTime() {
			break Loop
		} else if e.IsEqual(el.Value.(Elem)) {
			L.Remove(el)
			ret = true
			break Loop
		}
		el = el.Next()
	}
	return ret
}
Esempio n. 21
0
func computeAverages(execution_results *list.List) (float64, float64, int) {
	average_concurrent_users, average_response_time := 0.0, 0.0
	var result *httpActionResult
	var avg_rt_counter time.Duration
	max_concurrent_users := 0
	avg_cu_counter := 0.0
	counter := 0.0
	if execution_results.Len() > 0 {
		for elem := execution_results.Front(); elem != nil; elem = elem.Next() {
			result = elem.Value.(*httpActionResult)
			avg_cu_counter += float64(result.concurrent_users)
			if result.concurrent_users > max_concurrent_users {
				max_concurrent_users = result.concurrent_users
			}
			if result.is_client_error == false &&
				result.is_server_error == false &&
				result.has_timed_out == false {
				avg_rt_counter += result.response_time
				counter++
			}
		}
		average_concurrent_users = avg_cu_counter / float64(execution_results.Len())
		numerator := avg_rt_counter.Seconds() * 1000.0
		average_response_time = float64(numerator) / counter
	}
	return average_concurrent_users, average_response_time,
		max_concurrent_users
}
Esempio n. 22
0
func main() {

	give := make(chan []byte)
	get := make(chan []byte)

	go func() {
		q := new(list.List)

		for {
			if q.Len() == 0 {
				q.PushFront(make([]byte, 100))
			}

			e := q.Front()

			select {
			case s := <-give:
				q.PushFront(s)

			case get <- e.Value.([]byte):
				q.Remove(e)
			}
		}
	}()

	// Gets a new buffer from the recycler.
	buffer := <-get

	// Give it back to the recycler.
	give <- buffer

	// Get the recycled buffer again.
	buffer = <-get
}
Esempio n. 23
0
func saveMovie(l *list.List) {
	db, err := sql.Open("mysql", "root:1CUI@/piaofang")
	if err != nil {
		panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
	}
	defer db.Close()
	names := make([]string, l.Len())
	i := 0
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Println(e.Value.(*TMovie).Name)
		names[i] = "\"" + e.Value.(*TMovie).Name + "\""
		i++
	}
	namestrs := strings.Join(names, ",")
	stmtOut, err := db.Prepare("SELECT name FROM movie WHERE name in (" + namestrs + ")")
	fmt.Print("SELECT name FROM movie WHERE name in (" + namestrs + ")")
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	rows, err := stmtOut.Query()
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	defer stmtOut.Close()

	hasnames := getHasNames(rows)
	fmt.Println("has count" + strconv.Itoa(len(hasnames)))
	nohasnames := getNoHasNames(l, hasnames)
	fmt.Println("no has count" + strconv.Itoa(len(nohasnames)))
	insertmovies := getMovieByNames(l, nohasnames)
	fmt.Printf(strconv.Itoa(insertmovies.Len()))
	InsertMovieList(insertmovies)
}
Esempio n. 24
0
func listen(mr *MapReduce, stage JobType, completed *int, jobs *list.List) {

	NumOther := 0
	switch stage {
	case Map:
		NumOther = mr.nReduce
	case Reduce:
		NumOther = mr.nMap
	}

	if jobs.Len() != 0 {
		select {
		//wait for worker responses
		case r := <-mr.responses:
			HandleResponse(r, completed, jobs)

		//wait for available if none are available
		case id := <-mr.available:
			w := mr.Workers[id]
			//pop off a job id
			j := jobs.Remove(jobs.Front()).(int)
			args := &DoJobArgs{mr.file, stage, j, NumOther}
			go SendRPC(mr, w, args, j)
		}
	} else {
		r := <-mr.responses
		HandleResponse(r, completed, jobs)
	}
}
Esempio n. 25
0
func GetMinTime(L *list.List) Time {
	if L.Len() == 0 {
		return NOTIME
	}
	front := L.Front()
	return front.Value.(Elem).GetTime()
}
func TestScannerEndToEnd(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/ct/v1/get-sth":
			log.Printf("GetSTH")
			if _, err := w.Write([]byte(FourEntrySTH)); err != nil {
				t.Fatal("Failed to write get-sth response")
			}
		case "/ct/v1/get-entries":
			log.Printf("GetEntries %s", r.URL.RawQuery)
			if _, err := w.Write([]byte(FourEntries)); err != nil {
				t.Fatal("Failed to write get-sth response")
			}
		default:
			t.Fatal("Unexpected request")
		}
	}))
	defer ts.Close()

	logClient := client.New(ts.URL)
	opts := ScannerOptions{
		Matcher:       &MatchSubjectRegex{regexp.MustCompile(".*\\.google\\.com"), nil},
		BatchSize:     10,
		NumWorkers:    1,
		ParallelFetch: 1,
		StartIndex:    0,
	}
	scanner := NewScanner(logClient, opts)

	var matchedCerts list.List
	var matchedPrecerts list.List

	err := scanner.Scan(func(e *client.LogEntry) {
		// Annoyingly we can't t.Fatal() in here, as this is run in another go
		// routine
		matchedCerts.PushBack(*e.X509Cert)
	}, func(e *client.LogEntry) {
		matchedPrecerts.PushBack(*e.Precert)
	})

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

	if matchedPrecerts.Len() != 0 {
		t.Fatal("Found unexpected Precert")
	}

	switch matchedCerts.Len() {
	case 0:
		t.Fatal("Failed to find mail.google.com cert")
	case 1:
		if matchedCerts.Front().Value.(x509.Certificate).Subject.CommonName != "mail.google.com" {
			t.Fatal("Matched unexpected cert")
		}
	default:
		t.Fatal("Found unexpected number of certs")
	}
}
Esempio n. 27
0
func TestSimpleReaderList(t *testing.T) {
	b := new(bytes.Buffer)
	writer := NewWriter(b, true)
	l := list.New()
	l.PushBack(1)
	l.PushBack(2.0)
	l.PushBack(true)
	l.PushBack(false)
	l.PushBack(nil)
	l.PushBack(math.Inf(1))
	l.PushBack(math.Inf(-1))
	l.PushBack("")
	l.PushBack("我")
	l.PushBack("Hello World")
	l.PushBack("你好")
	writer.Serialize(l)
	writer.Serialize(l)
	writer.Serialize(nil)
	writer.Serialize(nil)

	reader := NewReader(b, true)
	var x list.List
	var p *list.List
	var err error
	if err = reader.Unserialize(&x); err != nil {
		t.Error(err.Error())
	}
	e2 := l.Front()
	for e := x.Front(); e != nil; e = e.Next() {
		if e.Value != e2.Value {
			t.Error(e.Value, e2.Value)
		}
		e2 = e2.Next()
	}

	if err = reader.Unserialize(&p); err != nil {
		t.Error(err.Error())
	}
	e2 = l.Front()
	for e := p.Front(); e != nil; e = e.Next() {
		if e.Value != e2.Value {
			t.Error(e.Value, e2.Value)
		}
		e2 = e2.Next()
	}

	if err = reader.Unserialize(&x); err != nil {
		t.Error(err.Error())
	}
	if x.Len() != 0 {
		t.Error(x)
	}
	if err = reader.Unserialize(&p); err != nil {
		t.Error(err.Error())
	}
	if p != nil {
		t.Error(*p)
	}
}
Esempio n. 28
0
// Convert a doubly linked list of message frames to a slice of message
// fram
func listToFrames(l *list.List) zMsg {
	frames := make(zMsg, l.Len())
	i := 0
	for e := l.Front(); e != nil; e = e.Next() {
		frames[i] = e.Value.(zFrame)
	}
	return frames
}
Esempio n. 29
0
func _del(l *list.List, id HandlerID) bool {
	for e := l.Front(); e != nil; e = e.Next() {
		if e.Value.(Handler).Id() == id {
			l.Remove(e)
		}
	}
	return l.Len() == 0
}
Esempio n. 30
0
func trimToSize(l *list.List, size int) {
	if l.Len() > size {
		diff := l.Len() - size
		for i := 0; i < diff; i++ {
			l.Remove(l.Front()) // Remove the first item from the que
		}
	}
}