Example #1
1
func loadPerms(path string) (mperms PermissionsList) {
	file, e := ioutil.ReadFile(path)
	if e != nil {
		fmt.Println("Could not get group permissions for", path, ":", e)
		return
	}
	lines := bytes.Split(file, []byte("\n"), -1)
	mperms = make(PermissionsList, len(lines))
	for i, line := range lines {
		parts := bytes.Split(line, []byte(" "), 2)
		perms := mperms[i]
		for _, perm := range parts[0] {
			switch perm {
			case 'r':
				perms.Read = true
			case 'w':
				perms.Write = true
			default:
				fmt.Println("WARNING: Unrecognized permission", perm)
			}
			perms.Path = string(parts[1])
			mperms[i] = perms
		}
	}
	sort.Sort(mperms)
	if !sort.IsSorted(mperms) {
		fmt.Println("Failed to sort!")
	}
	return
}
Example #2
0
func TestUxArraySorting(t *testing.T) {
	uxa := make(UxArray, 4)
	for i := 0; i < len(uxa); i++ {
		uxa[i] = makeUxOut(t)
	}
	isSorted := manualUxArrayIsSorted(uxa)
	assert.Equal(t, sort.IsSorted(uxa), isSorted)
	assert.Equal(t, uxa.IsSorted(), isSorted)
	// Make sure uxa is not sorted
	if isSorted {
		uxa[0], uxa[1] = uxa[1], uxa[0]
	}
	assert.False(t, manualUxArrayIsSorted(uxa))
	assert.False(t, sort.IsSorted(uxa))
	assert.False(t, uxa.IsSorted())
	uxb := make(UxArray, 4)
	for i, ux := range uxa {
		uxb[i] = ux
	}
	sort.Sort(uxa)
	assert.True(t, sort.IsSorted(uxa))
	assert.True(t, manualUxArrayIsSorted(uxa))
	assert.True(t, uxa.IsSorted())
	assert.False(t, sort.IsSorted(uxb))
	uxb.Sort()
	assert.Equal(t, uxa, uxb)
	assert.True(t, sort.IsSorted(uxb))
	assert.True(t, manualUxArrayIsSorted(uxb))
	assert.True(t, uxb.IsSorted())
}
Example #3
0
func runTest(t *testing.T, f func(Cover, Cover) Cover, sorted, symmetric bool, tests []Test) {
	if symmetric {
		for _, test := range tests {
			tests = append(tests, Test{test.V1, test.V0, test.R})
		}
	}
	tests = append(tests, Test{Cover{}, Cover{}, Cover{}})
	for _, test := range tests {
		if sorted {
			if !sort.IsSorted(test.V0) {
				t.Fatalf("input is not sorted: %+v", test.V0)
			}
			if !sort.IsSorted(test.V1) {
				t.Fatalf("input is not sorted: %+v", test.V1)
			}
		}
		if !sort.IsSorted(test.R) {
			t.Fatalf("golden is not sorted: %+v", test.R)
		}
		res := f(test.V0, test.V1)
		if !sort.IsSorted(res) {
			t.Fatalf("output is not sorted: %+v", res)
		}
		if (len(res) != 0 || len(test.R) != 0) && !reflect.DeepEqual(res, test.R) {
			t.Fatalf("f(%+v, %+v) = %+v (expect: %+v)", test.V0, test.V1, res, test.R)
		}
	}
}
Example #4
0
// IsSorted checks whether tx has inputs and outputs sorted according to BIP
// 69.
func IsSorted(tx *wire.MsgTx) bool {
	if !sort.IsSorted(sortableInputSlice(tx.TxIn)) {
		return false
	}
	if !sort.IsSorted(sortableOutputSlice(tx.TxOut)) {
		return false
	}
	return true
}
Example #5
0
func TestSortSlice(t *testing.T) {
	a1 := []int{2, 4, 6, 12, 353, 9, 44, 244, 123}
	a := IntSlice(a1)
	fmt.Println(sort.IsSorted(a)) //false
	if !sort.IsSorted(a) {
		sort.Sort(a)
	}
	fmt.Println(a)
}
func (s *S) TestUnitSliceSort(c *gocheck.C) {
	units := UnitSlice{
		Unit{Name: "f", State: provision.StatusBuilding.String()},
		Unit{Name: "g", State: provision.StatusStarted.String()},
		Unit{Name: "b", State: provision.StatusDown.String()},
	}
	c.Assert(sort.IsSorted(units), gocheck.Equals, false)
	sort.Sort(units)
	c.Assert(sort.IsSorted(units), gocheck.Equals, true)
}
Example #7
0
func (S) TestcontainerSliceSort(c *gocheck.C) {
	containers := containerSlice{
		container{Name: "f", Status: provision.StatusBuilding.String()},
		container{Name: "g", Status: provision.StatusStarted.String()},
		container{Name: "b", Status: provision.StatusDown.String()},
	}
	c.Assert(sort.IsSorted(containers), gocheck.Equals, false)
	sort.Sort(containers)
	c.Assert(sort.IsSorted(containers), gocheck.Equals, true)
}
Example #8
0
func TestLookupTableSorted(t *testing.T) {
	if !sort.IsSorted(lookupTableSortByCp949{fromTable}) {
		t.Error("fromTable is not sorted!")
	}
	t.Log("fromTable is sorted")

	if !sort.IsSorted(lookupTableSortByUcs2{toTable}) {
		t.Error("toTable is not sorted!")
	}
	t.Log("toTable is sorted")
}
Example #9
0
func (s *S) TestUnitSliceSort(c *gocheck.C) {
	units := UnitSlice{
		Unit{Name: "b", State: string(provision.StatusDown)},
		Unit{Name: "c", State: string(provision.StatusPending)},
		Unit{Name: "a", State: string(provision.StatusError)},
		Unit{Name: "d", State: string(provision.StatusCreating)},
		Unit{Name: "e", State: string(provision.StatusInstalling)},
		Unit{Name: "f", State: string(provision.StatusStarted)},
	}
	c.Assert(sort.IsSorted(units), gocheck.Equals, false)
	sort.Sort(units)
	c.Assert(sort.IsSorted(units), gocheck.Equals, true)
}
Example #10
0
func TestMergeInt(t *testing.T) {
	l := SortedInt(10)
	if !sort.IsSorted(int64arr(l)) {
		t.Errorf("Not sorted: [%v]\n", l)
		t.FailNow()
	}
	for i := 0; i < 50000; i++ {
		l = mergeInt(l, rand.Int63())
		if !sort.IsSorted(int64arr(l)) {
			t.Errorf("Not sorted: [%v]\n", l)
			t.FailNow()
		}
	}
}
Example #11
0
func TestOldestUxOut(t *testing.T) {
	uxs := OldestUxOut(makeUxArray(t, 4))
	for i, _ := range uxs {
		uxs[i].Head.BkSeq = uint64(i)
	}
	assert.True(t, sort.IsSorted(uxs))
	assert.Equal(t, uxs.Len(), 4)

	uxs.Swap(0, 1)
	assert.False(t, sort.IsSorted(uxs))
	assert.Equal(t, uxs[0].Head.BkSeq, uint64(1))
	assert.Equal(t, uxs[1].Head.BkSeq, uint64(0))
	uxs.Swap(0, 1)
	assert.True(t, sort.IsSorted(uxs))
	assert.Equal(t, uxs[0].Head.BkSeq, uint64(0))
	assert.Equal(t, uxs[1].Head.BkSeq, uint64(1))

	// Test hash sorting
	uxs[1].Head.BkSeq = uint64(0)
	h0 := uxs[0].Hash()
	h1 := uxs[1].Hash()
	firstLower := bytes.Compare(h0[:], h1[:]) < 0
	if firstLower {
		uxs.Swap(0, 1)
	}
	assert.False(t, sort.IsSorted(uxs))
	sort.Sort(uxs)

	cmpHash := false
	cmpSeq := false
	for i, _ := range uxs[:len(uxs)-1] {
		j := i + 1
		if uxs[i].Head.BkSeq == uxs[j].Head.BkSeq {
			ih := uxs[i].Hash()
			jh := uxs[j].Hash()
			assert.True(t, bytes.Compare(ih[:], jh[:]) < 0)
			cmpHash = true
		} else {
			assert.True(t, uxs[i].Head.BkSeq < uxs[j].Head.BkSeq)
			cmpSeq = true
		}
	}
	assert.True(t, cmpHash)
	assert.True(t, cmpSeq)

	// Duplicate output panics
	uxs = append(uxs, uxs[0])
	assert.Panics(t, func() { sort.Sort(uxs) })
}
Example #12
0
func TestAdd(t *testing.T) {
	x := New()
	x.Add("abcdefg")
	checkNum(len(x.circle), 20, t)
	checkNum(len(x.sortedHashes), 20, t)
	if sort.IsSorted(x.sortedHashes) == false {
		t.Errorf("expected sorted hashes to be sorted")
	}
	x.Add("qwer")
	checkNum(len(x.circle), 40, t)
	checkNum(len(x.sortedHashes), 40, t)
	if sort.IsSorted(x.sortedHashes) == false {
		t.Errorf("expected sorted hashes to be sorted")
	}
}
Example #13
0
func TestSort(t *testing.T) {
	assert.Init(t)

	func() {
		array := make(Array, 0, 10)

		assert.Ok(sort.IsSorted(array.Sort()))
	}()

	func() {
		array := Array{1, 5, 9, 8, 7, 6, 2, 4, 3}

		assert.Ok(sort.IsSorted(array.Sort()))
	}()
}
Example #14
0
File: enum.go Project: jvlmdr/go-ml
// Enum computes a performance range from a sorted list
// of scores of examples with ground truth labels.
func Enum(vals []ValScore) PerfPath {
	if !sort.IsSorted(byScoreDesc(vals)) {
		panic("not sorted")
	}
	// Count number of positive and negative.
	var pos, neg int
	for _, val := range vals {
		if val.Pos {
			pos++
		} else {
			neg++
		}
	}
	// Start with high threshold, everything negative,
	// then gradually lower it.
	perfs := make([]Perf, 0, len(vals)+1)
	perf := Perf{FN: pos, TN: neg}
	perfs = append(perfs, perf)
	for _, val := range vals {
		if val.Pos {
			// Positive example classified as positive instead of negative.
			perf.TP, perf.FN = perf.TP+1, perf.FN-1
		} else {
			// Negative example classified as positive instead of negative.
			perf.FP, perf.TN = perf.FP+1, perf.TN-1
		}
		perfs = append(perfs, perf)
	}
	return PerfPath(perfs)
}
Example #15
0
func TestSortFloat64Slice(t *testing.T) {
	data := float64s
	a := make(Float64Slice, testSize)
	nanCount := 0
	for i := range a {
		a[i] = data[i%len(data)]
		if math.IsNaN(a[i]) {
			nanCount++
		}
	}
	a.Sort()
	if !sort.IsSorted(a) {
		t.Errorf("sorted %v", float64s)
		t.Errorf("   got %v", data)
	}
	// sort.IsSorted will compare using the Key, so compare using < to see if
	// Key func is wrong
	prev := a[0]
	for _, v := range a {
		if v < prev {
			t.Errorf("Float64Key is wrong: %f sorted before %f", prev, v)
		}
		prev = v
	}
	// floats data contains two NaNs, so Search will find the spot right
	// before them.
	if a.Search(math.Inf(-1)) != 0 || a.Search(math.NaN()) != len(a)-nanCount {
		t.Errorf("search failed")
	}
}
Example #16
0
func Test_SelectionSort(t *testing.T) {
	ck := getCkints(1000)
	SelectionSort(ck)
	if !sort.IsSorted(ck) {
		t.Error("SelectionSort Error")
	}
}
Example #17
0
//选择器开始进行对象选择
//按照敌人虚弱程度进行选择,通常
func (self *ChooseByWeak) Choose(fromWho interface{}, stepName string, params ...interface{}) (targets []effect.EffectCarrier, error bool) {

	error = true
	from, ok := fromWho.(*battle.Warrior)
	if ok {
		//首先获得攻击者的敌人
		enemy := from.BattleIn.GetEnemyWarriors(from.Player)
		if len(enemy) > 0 {
			n := self.num
			//取最弱的n个,先按照hp排序,最少的放前面
			characters := (characterSliceLessByHP)(enemy)

			if !sort.IsSorted(characters) {
				sort.Sort(characters)
			}

			//然后返回前n个
			warriors := characters[0:n]

			targets = make([]effect.EffectCarrier, 0, len(warriors))

			for id, _ := range warriors {
				targets = append(targets, warriors[id])
			}

			error = false
		}
	}
	return
}
Example #18
0
func TestSelectionSort(t *testing.T) {
	data := generateRandomIntData(1000)
	SelectionSort(data)
	if !sort.IsSorted(data) {
		t.Error("Not sorted")
	}
}
Example #19
0
func (f *File) SortSegments() {
	// Segments are almost always already sorted.
	if sort.IsSorted(ByNumber(f.segments)) {
		return
	}
	sort.Sort(ByNumber(f.segments))
}
Example #20
0
func readChunks(r io.Reader, n int32, typ string) ([]bgzf.Chunk, error) {
	if n == 0 {
		return nil, nil
	}
	var (
		vOff uint64
		err  error
	)
	chunks := make([]bgzf.Chunk, n)
	for i := range chunks {
		err = binary.Read(r, binary.LittleEndian, &vOff)
		if err != nil {
			return nil, fmt.Errorf("%s: failed to read chunk begin virtual offset: %v", typ, err)
		}
		chunks[i].Begin = makeOffset(vOff)
		err = binary.Read(r, binary.LittleEndian, &vOff)
		if err != nil {
			return nil, fmt.Errorf("%s: failed to read chunk end virtual offset: %v", typ, err)
		}
		chunks[i].End = makeOffset(vOff)
	}
	if !sort.IsSorted(byBeginOffset(chunks)) {
		sort.Sort(byBeginOffset(chunks))
	}
	return chunks, nil
}
Example #21
0
func NewConsistantHashScheduler(hosts []string, hashname string) Scheduler {
	var c ConsistantHashScheduler
	c.hosts = make([]*Host, len(hosts))
	c.index = make([]uint64, len(hosts)*VIRTUAL_NODES)
	c.hashMethod = hashMethods[hashname]
	for i, h := range hosts {
		c.hosts[i] = NewHost(h)
		for j := 0; j < VIRTUAL_NODES; j++ {
			v := c.hashMethod([]byte(fmt.Sprintf("%s-%d", h, j)))
			ps := strings.SplitN(h, ":", 2)
			host := ps[0]
			port := ps[1]
			// 11211 这个端口有什么特殊?
			if port == "11211" {
				v = c.hashMethod([]byte(fmt.Sprintf("%s-%d", host, j)))
			}
			// 缓冲hash值
			c.index[i*VIRTUAL_NODES+j] = (uint64(v) << 32) + uint64(i)
		}
	}
	sort.Sort(uint64Slice(c.index))
	if !sort.IsSorted(uint64Slice(c.index)) {
		panic("sort failed")
	}
	return &c
}
Example #22
0
func validate(entries aclEntries) error {
	if len(entries) == 0 {
		return nil
	}
	if !sort.IsSorted(entries) {
		return errors.New("acl entries are not sorted by table name or prefix")
	}
	if err := validateNameOrPrefix(entries[0].tableNameOrPrefix); err != nil {
		return err
	}
	for i := 1; i < len(entries); i++ {
		prev := entries[i-1].tableNameOrPrefix
		cur := entries[i].tableNameOrPrefix
		if err := validateNameOrPrefix(cur); err != nil {
			return err
		}
		if prev == cur {
			return fmt.Errorf("conflict entries, name: %s overlaps with name: %s", cur, prev)
		} else if isPrefix(prev) && isPrefix(cur) {
			if strings.HasPrefix(cur[:len(cur)-1], prev[:len(prev)-1]) {
				return fmt.Errorf("conflict entries, prefix: %s overlaps with prefix: %s", cur, prev)
			}
		} else if isPrefix(prev) {
			if strings.HasPrefix(cur, prev[:len(prev)-1]) {
				return fmt.Errorf("conflict entries, name: %s overlaps with prefix: %s", cur, prev)
			}
		} else if isPrefix(cur) {
			if strings.HasPrefix(prev, cur[:len(cur)-1]) {
				return fmt.Errorf("conflict entries, prefix: %s overlaps with name: %s", cur, prev)
			}
		}
	}
	return nil
}
Example #23
0
// MergeChunks applies the given MergeStrategy to all bins in the Index.
func (i *Index) MergeChunks(s func([]bgzf.Chunk) []bgzf.Chunk) {
	if s == nil {
		return
	}
	for _, ref := range i.Refs {
		for b, bin := range ref.Bins {
			if !sort.IsSorted(byBeginOffset(bin.Chunks)) {
				sort.Sort(byBeginOffset(bin.Chunks))
			}
			ref.Bins[b].Chunks = s(bin.Chunks)
			if !sort.IsSorted(byBeginOffset(bin.Chunks)) {
				sort.Sort(byBeginOffset(bin.Chunks))
			}
		}
	}
}
Example #24
0
func Test_InsertionSort(t *testing.T) {
	ck := getCkints(1000)
	InsertionSort(ck)
	if !sort.IsSorted(ck) {
		t.Error("InsertionSort Error")
	}
}
Example #25
0
func TestSorting(t *testing.T) {
	cards := []Card{
		NewCard(trello.Card{}),
		NewCard(trello.Card{}),
		NewCard(trello.Card{}),
		NewCard(trello.Card{}),
	}
	cards[0].stats.comments = 5
	cards[3].stats.creates = 10
	cards[1].stats.checkListItemUpdates = 4
	sort.Sort(ByStatisticsCountRev(cards))
	if !sort.IsSorted(ByStatisticsCountRev(cards)) {
		t.Fatal("Not sorted")
	}

	sorted := map[int]int{
		0: 10,
		1: 5,
		2: 4,
		3: 0,
	}

	for i, v := range cards {
		if v.stats.Total() != sorted[i] {
			t.Fatalf("Error testing Sort: Expected %d, got %d", sorted[i], v.stats.Total())
		}
	}
}
Example #26
0
func testSortFn(t *testing.T, fn sortFn, fnName string) {
	for _, test := range []sort.Interface{
		sort.IntSlice([]int{660, 14, 796, 336, 223, 594, 419, 574, 372, 103, 991, 718, 436, 351, 844, 277, 668, 250, 330, 86}),
		sort.Float64Slice([]float64{213.237, 458.642, 978.311, 547.351, 57.8992, 245.518, 445.638, 251.79, 960.202, 100.069, 483.136, 407.858, 496.913, 562.943, 557.959, 219.648, 164.599, 843.304, 671.732, 222.676}),
		sort.StringSlice([]string{"assaults", "brackish", "monarchism", "ascribe", "mechanize", "andiron", "overpricing", "jading", "hauliers", "snug", "zodiac", "credit", "tremendous", "palavered", "hibiscuses", "amplest", "interrogated", "geologic", "unorthodoxy", "propagated"}),
	} {
		// Make a copy to avoid modification of the original slice.
		var data sort.Interface
		switch v := test.(type) {
		case sort.IntSlice:
			data = append(sort.IntSlice(nil), v...)
		case sort.Float64Slice:
			data = append(sort.Float64Slice(nil), v...)
		case sort.StringSlice:
			data = append(sort.StringSlice(nil), v...)
		default:
			t.Errorf("missing case: cannot copy %T", v)
			continue
		}
		fn(data)
		if !sort.IsSorted(data) {
			t.Errorf("%s(%v)", fnName, test)
			t.Errorf(" got %v", data)
			sort.Sort(data)
			t.Errorf("want %v", data)
		}
	}
}
Example #27
0
func TestCreateSpends(t *testing.T) {
	now := tNow()
	amt := wallet.Balance{12e6, 125}
	uxs := makeUxBalances([]wallet.Balance{
		wallet.Balance{1e6, 50},
		wallet.Balance{8e6, 10}, // 3
		wallet.Balance{2e6, 80}, // 2
		wallet.Balance{5e6, 15}, // 4
		wallet.Balance{7e6, 20}, // 1
	}, now)
	uxs[4].Head.BkSeq = uint64(1)
	uxs[3].Head.BkSeq = uint64(4)
	uxs[2].Head.BkSeq = uint64(2)
	uxs[1].Head.BkSeq = uint64(3)
	uxs[0].Head.BkSeq = uint64(5)
	if sort.IsSorted(OldestUxOut(uxs)) {
		uxs[0], uxs[1] = uxs[1], uxs[0]
	}
	assert.False(t, sort.IsSorted(OldestUxOut(uxs)))
	expectedSorting := coin.UxArray{uxs[4], uxs[2], uxs[1], uxs[3], uxs[0]}
	cuxs := append(coin.UxArray{}, uxs...)
	sort.Sort(OldestUxOut(cuxs))
	assert.Equal(t, expectedSorting, cuxs)
	assert.True(t, sort.IsSorted(OldestUxOut(cuxs)))
	assert.False(t, sort.IsSorted(OldestUxOut(uxs)))

	ouxs := append(coin.UxArray{}, uxs...)
	spends, err := createSpends(now, uxs, amt, 0, 0)
	assert.True(t, sort.IsSorted(OldestUxOut(uxs)))
	assert.Nil(t, err)
	assert.Equal(t, spends, cuxs[:len(spends)])
	assert.Equal(t, len(spends), 4)
	assert.Equal(t, spends, coin.UxArray{ouxs[4], ouxs[2], ouxs[1], ouxs[3]})

	// Recalculate what it should be
	b := wallet.Balance{0, 0}
	ouxs = make(coin.UxArray, 0, len(spends))
	for _, ux := range cuxs {
		if b.Coins > amt.Coins && b.Hours >= amt.Hours {
			break
		}
		b = b.Add(wallet.NewBalanceFromUxOut(now, &ux))
		ouxs = append(ouxs, ux)
	}
	assert.Equal(t, len(ouxs), len(spends))
	assert.Equal(t, ouxs, spends)
}
Example #28
0
func TestEnumerateIsSorted(t *testing.T) {
	ds := NewStorage(t)
	defer cleanUp(ds)

	const blobsToMake = 250
	t.Logf("Uploading test blobs...")
	for i := 0; i < blobsToMake; i++ {
		blob := &test.Blob{fmt.Sprintf("blob-%d", i)}
		blob.MustUpload(t, ds)
	}

	// Make some fake blobs in other partitions to confuse the
	// enumerate code.
	// TODO(bradfitz): remove this eventually.
	fakeDir := ds.root + "/partition/queue-indexer/sha1/1f0/710"
	ExpectNil(t, os.MkdirAll(fakeDir, 0755), "creating fakeDir")
	ExpectNil(t, ioutil.WriteFile(fakeDir+"/sha1-1f07105465650aa243cfc1b1bbb1c68ea95c6812.dat",
		[]byte("fake file"), 0644), "writing fake blob")

	// And the same for a "cache" directory, used by the default configuration.
	fakeDir = ds.root + "/cache/sha1/1f0/710"
	ExpectNil(t, os.MkdirAll(fakeDir, 0755), "creating cache fakeDir")
	ExpectNil(t, ioutil.WriteFile(fakeDir+"/sha1-1f07105465650aa243cfc1b1bbb1c68ea95c6812.dat",
		[]byte("fake file"), 0644), "writing fake blob")

	var tests = []struct {
		limit int
		after string
	}{
		{200, ""},
		{blobsToMake, ""},
		{200, "sha1-2"},
		{200, "sha1-3"},
		{200, "sha1-4"},
		{200, "sha1-5"},
		{200, "sha1-e"},
		{200, "sha1-f"},
		{200, "sha1-ff"},
	}
	for _, test := range tests {
		limit := test.limit
		ch := make(chan blob.SizedRef)
		errCh := make(chan error)
		go func() {
			errCh <- ds.EnumerateBlobs(context.TODO(), ch, test.after, limit)
		}()
		got := make([]blob.SizedRef, 0, blobsToMake)
		for sb := range ch {
			got = append(got, sb)
		}
		if err := <-errCh; err != nil {
			t.Errorf("case %+v; enumerate error: %v", test, err)
			continue
		}
		if !sort.IsSorted(SortedSizedBlobs(got)) {
			t.Errorf("case %+v: expected sorted; got: %q", test, got)
		}
	}
}
Example #29
0
// sortComments sorts the list of comment groups in source order.
//
func sortComments(list []*CommentGroup) {
	// TODO(gri): Does it make sense to check for sorted-ness
	//            first (because we know that sorted-ness is
	//            very likely)?
	if orderedList := byPos(list); !sort.IsSorted(orderedList) {
		sort.Sort(orderedList)
	}
}
Example #30
0
func TestQuick(t *testing.T) {
	d := init_testdata(20)
	Quick(d)
	if !sort.IsSorted(d) {
		t.Error("Quick Sort Error:", d)
		return
	}
}