Beispiel #1
0
func fetchMoves(curr_state string, moves *list.List, steps int) {
	if len(curr_state) <= steps-1 {
		return
	}

	val := []byte(curr_state)

	for i, _ := range val {
		if i+steps-1 < len(val) {
			success := true
			for k := 0; k < steps; k++ {
				if val[i+k] == '0' {
					success = false
				}
			}
			if success {
				for k := 0; k < steps; k++ {
					val[i+k] = '0'
				}

				moves.PushBack(string(val))

				for k := 0; k < steps; k++ {
					val[i+k] = '1'
				}
			}
		}
	}
}
Beispiel #2
0
func doStructMembers(fields []*ast.Field, pkg string, importer Importer, fn func(*ast.Object), q *list.List) {
	// Go Spec: For a value x of type T or *T where T is not an interface type, x.f
	// denotes the field or method at the shallowest depth in T where there
	// is such an f.
	// Thus we traverse shallower fields first, pushing anonymous fields
	// onto the queue for later.

	for _, f := range fields {
		if len(f.Names) > 0 {
			for _, fname := range f.Names {
				fn(fname.Obj)
			}
		} else {
			m := unnamedFieldName(f.Type)
			fn(m.Obj)
			// The unnamed field's Decl points to the
			// original type declaration.
			_, typeNode := splitDecl(m.Obj, nil)
			obj, typ := exprType(typeNode, false, pkg, importer)
			if typ.Kind == ast.Typ {
				q.PushBack(typ)
			} else {
				debugp("unnamed field kind %v (obj %v) not a type; %v", typ.Kind, obj, typ.Node)
			}
		}
	}
}
Beispiel #3
0
// Workers report back how many RPCs they have processed in the Shutdown reply.
// Check that they processed at least 1 RPC.
func checkWorker(t *testing.T, l *list.List) {
	for e := l.Front(); e != nil; e = e.Next() {
		if e.Value == 0 {
			t.Fatalf("Some worker didn't do any work\n")
		}
	}
}
Beispiel #4
0
func main() {
	var list list.List
	scanner := bufio.NewScanner(os.Stdin)
	p := getNumber(scanner)
	q := getNumber(scanner)
	for i := p; i <= q; i++ {
		square := i * i
		squareStr := strconv.Itoa(square)
		mid := len(squareStr) / 2
		power := float64(len(squareStr) - mid)
		rem := square % int(math.Pow(10, power))
		quo := square / int(math.Pow(10, power))
		sum := rem + quo
		if sum == i {
			list.PushBack(i)
		}
	}
	if list.Len() <= 0 {
		fmt.Println("INVALID RANGE")
	} else {
		for e := list.Front(); e != nil; e = e.Next() {
			fmt.Printf("%d ", e.Value)
		}
	}
}
Beispiel #5
0
func List2Array(l *list.List) []interface{} {
	output := make([]interface{}, 0)
	for i := l.Front(); i != nil; i = i.Next() {
		output = append(output, i.Value)
	}
	return output
}
Beispiel #6
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++
	}
}
Beispiel #7
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
}
Beispiel #8
0
func GetMinTime(L *list.List) Time {
	if L.Len() == 0 {
		return NOTIME
	}
	front := L.Front()
	return front.Value.(Elem).GetTime()
}
Beispiel #9
0
func (s *Surface) filterPixel(p Coord2D, used, unUsed *list.List) {
	if s.IsUsed(p.X, p.Y) {
		used.PushBack(p)
	} else {
		unUsed.PushBack(p)
	}
}
Beispiel #10
0
func ParseTokens(t []string) *list.List {
	tokens := new(list.List)
	for i := range t {
		tokens.PushBack(t[i])
	}
	n := 0
	s, o := new(list.List), new(list.List)
	for e := tokens.Front(); e != nil; e = e.Next() {
		if e.Value.(string) == "(" {
			n++
			listAppend(s, new(list.List))
			listAppend(o, s)
			s = s.Back().Value.(*list.List)
		} else if e.Value.(string) == ")" {
			n--
			s = o.Back().Value.(*list.List)
			listPop(o)
		} else {
			listAppend(s, e.Value.(string))
		}
	}
	if n != 0 {
		Error("unbalanced parantheses")
	}
	return s
}
Beispiel #11
0
func (p *Pipeline) removeUnacceptedChanges(l *list.List, allowAdd, allowDelete, allowUpdate bool) *list.List {
	if allowAdd && allowDelete && allowUpdate {
		return l
	}
	n := list.New()
	for iter := l.Front(); iter != nil; iter = iter.Next() {
		if iter.Value == nil {
			continue
		}
		ch, _ := iter.Value.(*dm.Change)
		if ch == nil {
			continue
		}
		if !allowAdd && ch.ChangeType == dm.CHANGE_TYPE_ADD {
			fmt.Printf("[PIPELINE]: Removing add change for path of %#v\n", ch.Path)
		} else if !allowDelete && ch.ChangeType == dm.CHANGE_TYPE_DELETE {
			fmt.Printf("[PIPELINE]: Removing delete change for path of %#v\n", ch.Path)
		} else if !allowUpdate && ch.ChangeType == dm.CHANGE_TYPE_UPDATE {
			if !allowAdd || ch.Path == nil || len(ch.Path) <= 1 {
				fmt.Printf("[PIPELINE]: Removing update for path of %#v and allowAdd %v\n", ch.Path, allowAdd)
			} else {
				fmt.Printf("[PIPELINE]: Changing update to add for path of %#v and allowAdd %v\n", ch.Path, allowAdd)
				ch.ChangeType = dm.CHANGE_TYPE_ADD
				ch.OriginalValue = nil
				n.PushBack(ch)
			}
		} else {
			n.PushBack(ch)
		}
	}
	return n
}
func (server *Server) buildArgumentsFlop(arguments *list.List, params imageserver.Params) error {
	flop, _ := params.GetBool("flop")
	if flop {
		arguments.PushBack("-flop")
	}
	return nil
}
func (server *Server) buildArgumentsMonochrome(arguments *list.List, params imageserver.Params) error {
	monochrome, _ := params.GetBool("monochrome")
	if monochrome {
		arguments.PushBack("-monochrome")
	}
	return nil
}
func (server *Server) buildArgumentsGravity(arguments *list.List, params imageserver.Params) error {
	gravity, _ := params.GetString("gravity")
	var translatedGravity string
	if gravity != "" {
		switch {
		case gravity == "n":
			translatedGravity = "North"
		case gravity == "s":
			translatedGravity = "South"
		case gravity == "e":
			translatedGravity = "East"
		case gravity == "w":
			translatedGravity = "West"
		case gravity == "ne":
			translatedGravity = "NorthEast"
		case gravity == "se":
			translatedGravity = "SouthEast"
		case gravity == "nw":
			translatedGravity = "NorthWest"
		case gravity == "sw":
			translatedGravity = "SouthWest"
		}
		if translatedGravity == "" {
			return &imageserver.ParamError{Param: "gravity", Message: "gravity should n, s, e, w, ne, se, nw or sw"}
		}
	} else {
		// Default gravity is center.
		translatedGravity = "Center"
	}

	arguments.PushBack("-gravity")
	arguments.PushBack(fmt.Sprintf("%s", translatedGravity))
	return nil
}
Beispiel #15
0
func DecomposeRecordLayer(tlsPayload []byte) list.List {
	if len(tlsPayload) < 5 {
		return list.List{}
	}
	log.Println("Parsing one packet......")
	var tlsLayerlist list.List
	total := uint16(len(tlsPayload))
	var offset uint16 = 0

	for offset < total {
		var p TLSHandshakeDecoder.TLSRecordLayer
		p.ContentType = uint8(tlsPayload[0+offset])
		p.Version = uint16(tlsPayload[1+offset])<<8 | uint16(tlsPayload[2+offset])
		p.Length = uint16(tlsPayload[3+offset])<<8 | uint16(tlsPayload[4+offset])
		p.Fragment = make([]byte, p.Length)
		l := copy(p.Fragment, tlsPayload[5+offset:5+p.Length+offset])
		tlsLayerlist.PushBack(p)
		log.Println("Length: ", p.Length, "Type: ", p.ContentType)
		offset += 5 + p.Length
		if l < int(p.Length) {
			fmt.Errorf("Payload to short: copied %d, expected %d.", l, p.Length)
		}
	}
	return tlsLayerlist
}
Beispiel #16
0
func (s system) NewTasksFromConfig(config map[string]interface{}) (*list.List, error) {
	tasks, ok := config["tasks"]
	if !ok {
		return nil, errors.New("The field tasks was not found")
	}

	switch vt := tasks.(type) {
	case []interface{}:
		fmt.Printf("vt: %v\n", vt)

		tasks := new(list.List)

		for t, val := range vt {
			fmt.Printf("%v == %v\n", t, val)
			mt, ok := val.(map[string]interface{})
			if ok {
				task, err := s.NewTask(mt)
				if err == nil {
					log.Printf("Adding %v", task)
					tasks.PushBack(task)
				} else {
					log.Printf("Could not add %v, %v", val, err)
				}
			}
		}

		return tasks, nil
	default:
		return nil, errors.New("tasks field was wrong type")
	}

	return nil, nil
}
Beispiel #17
0
func DecomposeHandshakes(data []byte) list.List {
	if len(data) < 4 {
		return list.List{}
	}
	log.Println("Parsing one TLSLayer.......")
	var handshakelist list.List
	total := uint32(len(data))
	var offset uint32 = 0

	for offset < total {
		var p TLSHandshakeDecoder.TLSHandshake
		p.HandshakeType = uint8(data[0+offset])
		p.Length = uint32(data[1+offset])<<16 | uint32(data[2+offset])<<8 | uint32(data[3+offset])
		p.Body = make([]byte, p.Length)
		if p.Length < 2048 {
			l := copy(p.Body, data[4+offset:4+p.Length+offset])

			if l < int(p.Length) {
				fmt.Errorf("Payload to short: copied %d, expected %d.", l, p.Length)
			}
			offset += 4 + p.Length
		} else {
			p.HandshakeType = 99
			p.Length = 0
			offset = total
		}

		log.Printf("Handshake Type: %d, length: %d ", p.HandshakeType, p.Length)
		handshakelist.PushBack(p)
	}
	return handshakelist
}
Beispiel #18
0
func GetShowTime(lcinema *list.List) {
	for e := lcinema.Front(); e != nil; e = e.Next() {
		lshowtimes := list.New().Init()
		cinema := e.Value.(*TCinema)
		showtimes := getShowTimeSingleCinema(cinema.TypeIndex, "2015-10-15")
		for i := 0; i < len(showtimes); i++ {
			jshowtime := showtimes[i]
			showtime := new(ShowTime)
			showtime.SeatCount = jshowtime.SeatCount
			showtime.Type = 0
			showtime.TypeCinemaIndex = jshowtime.CinemaID
			showtime.TypeCityIndex = jshowtime.CityID
			showtime.TypeHallID = jshowtime.HallID
			showtime.TypeMovieIndex = jshowtime.FilmID
			showtime.TypeMovieName = jshowtime.FilmName
			showtime.TypeName = "wangpiao"
			//			showtime.TypeSaleEndTimeS = jshowtime.SaleEndTime
			ts, _ := time.Parse("2006-01-02 15:04:05", jshowtime.SaleEndTime)
			showtime.TypeSaleEndTimeS = ts
			showtime.TypeSaleEndTime = ts.Unix()
			showtime.TypeShowIndex = jshowtime.ShowIndex
			lshowtimes.PushBack(showtime)
		}
		InsertShowTimeList(lshowtimes)
	}
}
Beispiel #19
0
func (this *UKB) initSynsetVector(ls *list.List, pv []float64) {
	nw := 0
	uniq := make(map[string]*Word)
	for s := ls.Front(); s != nil; s = s.Next() {
		for w := s.Value.(*Sentence).Front(); w != nil; w = w.Next() {
			if this.RE_wnpos.MatchString(w.Value.(*Word).getTag(0)) {
				key := w.Value.(*Word).getLCForm() + "#" + strings.ToLower(w.Value.(*Word).getTag(0))[0:1]
				if uniq[key] == nil {
					nw++
					uniq[key] = w.Value.(*Word)
				}
			}
		}
	}

	for _, u := range uniq {
		lsen := u.getSenses(0)
		nsyn := lsen.Len()
		for s := lsen.Front(); s != nil; s = s.Next() {
			syn := this.wn.getVertex(s.Value.(FloatPair).first)
			if syn == VERTEX_NOT_FOUND {
				LOG.Warn("Unknown synset " + s.Value.(FloatPair).first + " ignored. Please check consistency between sense dictionary and KB")
			} else {
				pv[syn] += (1.0 / float64(nw)) * (1.0 / float64(nsyn))
			}
		}
	}
}
// Performs a scan against the Log.
// For each x509 certificate found, |foundCert| will be called with the
// index of the entry and certificate itself as arguments.  For each precert
// found, |foundPrecert| will be called with the index of the entry and the raw
// precert string as the arguments.
//
// This method blocks until the scan is complete.
func (s *Scanner) Scan(foundCert func(*ct.LogEntry),
	foundPrecert func(*ct.LogEntry)) error {
	s.Log("Starting up...\n")
	s.certsProcessed = 0
	s.precertsSeen = 0
	s.unparsableEntries = 0
	s.entriesWithNonFatalErrors = 0

	latestSth, err := s.logClient.GetSTH()
	if err != nil {
		return err
	}
	s.Log(fmt.Sprintf("Got STH with %d certs", latestSth.TreeSize))

	ticker := time.NewTicker(time.Second)
	startTime := time.Now()
	fetches := make(chan fetchRange, 1000)
	jobs := make(chan matcherJob, 100000)
	go func() {
		for range ticker.C {
			throughput := float64(s.certsProcessed) / time.Since(startTime).Seconds()
			remainingCerts := int64(latestSth.TreeSize) - int64(s.opts.StartIndex) - s.certsProcessed
			remainingSeconds := int(float64(remainingCerts) / throughput)
			remainingString := humanTime(remainingSeconds)
			s.Log(fmt.Sprintf("Processed: %d certs (to index %d). Throughput: %3.2f ETA: %s\n", s.certsProcessed,
				s.opts.StartIndex+int64(s.certsProcessed), throughput, remainingString))
		}
	}()

	var ranges list.List
	for start := s.opts.StartIndex; start < int64(latestSth.TreeSize); {
		end := min(start+int64(s.opts.BatchSize), int64(latestSth.TreeSize)) - 1
		ranges.PushBack(fetchRange{start, end})
		start = end + 1
	}
	var fetcherWG sync.WaitGroup
	var matcherWG sync.WaitGroup
	// Start matcher workers
	for w := 0; w < s.opts.NumWorkers; w++ {
		matcherWG.Add(1)
		go s.matcherJob(w, jobs, foundCert, foundPrecert, &matcherWG)
	}
	// Start fetcher workers
	for w := 0; w < s.opts.ParallelFetch; w++ {
		fetcherWG.Add(1)
		go s.fetcherJob(w, fetches, jobs, &fetcherWG)
	}
	for r := ranges.Front(); r != nil; r = r.Next() {
		fetches <- r.Value.(fetchRange)
	}
	close(fetches)
	fetcherWG.Wait()
	close(jobs)
	matcherWG.Wait()

	s.Log(fmt.Sprintf("Completed %d certs in %s", s.certsProcessed, humanTime(int(time.Since(startTime).Seconds()))))
	s.Log(fmt.Sprintf("Saw %d precerts", s.precertsSeen))
	s.Log(fmt.Sprintf("%d unparsable entries, %d non-fatal errors", s.unparsableEntries, s.entriesWithNonFatalErrors))
	return nil
}
Beispiel #21
0
// Render takes an ast list and renders it to the screen
func Render(ast list.List) {
	for e := ast.Front(); e != nil; e = e.Next() {
		node, ok := e.Value.(Node)
		if !ok {
			panic(ok)
		}
		if node.Type == newline {
			fmt.Println()
		} else {
			if node.Type == heading {
				PrintHeading(node.Content, node.Heading)
			} else if node.Type == blockquote {
				fmt.Print("\t")
			} else if node.Type == italic {
				PrintItalic(node.Content)
			} else if node.Type == strikethrough {
				PrintStrikethrough(node.Content)
			} else if node.Type == bold {
				PrintBold(node.Content)
			} else {
				Print(node.Content)
			}
		}
	}
}
Beispiel #22
0
/**
 * construct functions
 */
func MakePattern(a ...Data) *list.List {
	pattern := new(list.List)
	for _, v := range a {
		pattern.PushBack(v)
	}
	return pattern
}
Beispiel #23
0
// queueUnseenImports scans a package's imports and adds any new ones to the
// processing queue.
func (r *Resolver) queueUnseen(pkg string, queue *list.List) error {
	// A pkg is marked "seen" as soon as we have inspected it the first time.
	// Seen means that we have added all of its imports to the list.

	// Already queued indicates that we've either already put it into the queue
	// or intentionally not put it in the queue for fatal reasons (e.g. no
	// buildable source).

	deps, err := r.imports(pkg)
	if err != nil && !strings.HasPrefix(err.Error(), "no buildable Go source") {
		msg.Error("Could not find %s: %s", pkg, err)
		return err
		// NOTE: If we uncomment this, we get lots of "no buildable Go source" errors,
		// which don't ever seem to be helpful. They don't actually indicate an error
		// condition, and it's perfectly okay to run into that condition.
		//} else if err != nil {
		//	msg.Warn(err.Error())
	}

	for _, d := range deps {
		if _, ok := r.alreadyQ[d]; !ok {
			r.alreadyQ[d] = true
			queue.PushBack(d)
		}
	}
	return nil
}
Beispiel #24
0
func NewTComInputBitstream(buf *list.List) *TComInputBitstream { // std::vector<uint8_t>* buf);
	if buf != nil {
		return &TComInputBitstream{buf, make(map[uint]uint), 0, buf.Front(), 0, 0, 0}
	}

	return &TComInputBitstream{nil, make(map[uint]uint), 0, nil, 0, 0, 0}
}
Beispiel #25
0
func StrList2StrArray(l *list.List) []string {
	output := make([]string, 0)
	for i := l.Front(); i != nil; i = i.Next() {
		output = append(output, i.Value.(string))
	}
	return output
}
Beispiel #26
0
func copyList(l *list.List) *list.List {
	n := list.New()
	for e := l.Front(); e != nil; e = e.Next() {
		n.PushBack(e.Value.(string))
	}
	return n
}
Beispiel #27
0
// ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
	var (
		u          *User
		emails     = map[string]*User{}
		newCommits = list.New()
		e          = oldCommits.Front()
	)
	for e != nil {
		c := e.Value.(*git.Commit)

		if v, ok := emails[c.Author.Email]; !ok {
			u, _ = GetUserByEmail(c.Author.Email)
			emails[c.Author.Email] = u
		} else {
			u = v
		}

		newCommits.PushBack(UserCommit{
			User:   u,
			Commit: c,
		})
		e = e.Next()
	}
	return newCommits
}
Beispiel #28
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) {
	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()
	}
}
Beispiel #29
0
// handleDonePeerMsg deals with peers that have signalled they are done.  It is
// invoked from the peerHandler goroutine.
func (s *server) handleDonePeerMsg(state *peerState, p *peer) {
	var list *list.List
	if p.persistent {
		list = state.persistentPeers
	} else if p.inbound {
		list = state.peers
	} else {
		list = state.outboundPeers
	}
	for e := list.Front(); e != nil; e = e.Next() {
		if e.Value == p {
			// Issue an asynchronous reconnect if the peer was a
			// persistent outbound connection.
			if !p.inbound && p.persistent &&
				atomic.LoadInt32(&s.shutdown) == 0 {
				e.Value = newOutboundPeer(s, p.addr, true)
				return
			}
			if !p.inbound {
				state.outboundGroups[GroupKey(p.na)]--
			}
			list.Remove(e)
			srvrLog.Debugf("Removed peer %s", p)
			return
		}
	}
	// If we get here it means that either we didn't know about the peer
	// or we purposefully deleted it.
}
Beispiel #30
0
func (k *Kademlia) closestContacts(searchID ID, excludedID ID, amount int) (contacts []Contact) {
	contacts = make([]Contact, 0)

	k.doInSearchOrder(searchID, func(index int) bool {
		// add as many contacts from bucket i as possible,

		currentBucket := k.Buckets[index].contacts
		sortedList := new(list.List)

		//sort that list |suspect|
		for e := currentBucket.Front(); e != nil; e = e.Next() {
			insertSorted(sortedList, e.Value.(Contact), func(first Contact, second Contact) int {
				firstDistance := first.NodeID.Xor(searchID)
				secondDistance := second.NodeID.Xor(searchID)
				return firstDistance.Compare(secondDistance)
			})
		}

		// (^._.^)~ kirby says add as much as you can to output slice
		for e := sortedList.Front(); e != nil; e = e.Next() {
			c := e.Value.(Contact)
			if !c.NodeID.Equals(excludedID) {
				contacts = append(contacts, c)
				// if the slice is full, break
				if len(contacts) == amount {
					return false
				}
			}
		}
		// slice isn't full, do on the next index
		return true
	})
	return
}