本文整理汇总了Golang中sort.Sort函数的典型用法代码示例。如果您正苦于以下问题:Golang Sort函数的具体用法?Golang Sort怎么用?Golang Sort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Sort函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestUserAddRole
func (s *S) TestUserAddRole(c *check.C) {
_, err := permission.NewRole("r1", "app")
c.Assert(err, check.IsNil)
_, err = permission.NewRole("r2", "app")
c.Assert(err, check.IsNil)
u := User{Email: "[email protected]", Password: "123"}
err = u.Create()
c.Assert(err, check.IsNil)
err = u.AddRole("r1", "c1")
c.Assert(err, check.IsNil)
err = u.AddRole("r1", "c2")
c.Assert(err, check.IsNil)
err = u.AddRole("r2", "x")
c.Assert(err, check.IsNil)
err = u.AddRole("r2", "x")
c.Assert(err, check.IsNil)
err = u.AddRole("r3", "a")
c.Assert(err, check.Equals, permission.ErrRoleNotFound)
expected := []RoleInstance{
{Name: "r1", ContextValue: "c1"},
{Name: "r1", ContextValue: "c2"},
{Name: "r2", ContextValue: "x"},
}
sort.Sort(roleInstanceList(expected))
sort.Sort(roleInstanceList(u.Roles))
c.Assert(u.Roles, check.DeepEquals, expected)
uDB, err := GetUserByEmail("[email protected]")
c.Assert(err, check.IsNil)
sort.Sort(roleInstanceList(uDB.Roles))
c.Assert(uDB.Roles, check.DeepEquals, expected)
}
示例2: TestSort
func TestSort(t *testing.T) {
sorted_loglines, err := Parse("fixtures/sorted.out")
if err != nil {
t.Error(err)
}
if len(sorted_loglines) != 11 {
t.Errorf("Logline length mismatch: %v != 11", len(sorted_loglines))
}
unsorted_loglines, err := Parse("fixtures/unsorted.out")
if err != nil {
t.Error(err)
}
if len(unsorted_loglines) != 11 {
t.Errorf("Logline length mismatch: %v != 11", len(unsorted_loglines))
}
if reflect.DeepEqual(sorted_loglines, unsorted_loglines) {
t.Error("Unsorted loglines match sorted loglines.")
}
sort.Sort(ByTime(unsorted_loglines))
if !reflect.DeepEqual(sorted_loglines, unsorted_loglines) {
t.Error("Sorted loglines do not match.")
}
sort.Sort(ByTime(sorted_loglines))
if !reflect.DeepEqual(sorted_loglines, unsorted_loglines) {
t.Error("Sorted loglines do not match after unnecessary sort.")
}
}
示例3: FindLatestMatchingName
// FindLatestMatchingName locats a package by name, returns the latest available version.
func (repo *RepositoryXMLBackend) FindLatestMatchingName(name, version, release string) (*Package, error) {
var pkg *Package
var err error
pkgs, ok := repo.Packages[name]
if !ok {
repo.msg.Debugf("could not find package %q\n", name)
return nil, fmt.Errorf("no such package %q", name)
}
if version == "" && len(pkgs) > 0 {
// return latest
sorted := make([]*Package, len(pkgs))
copy(sorted, pkgs)
sort.Sort(Packages(sorted))
pkg = sorted[len(sorted)-1]
} else {
// trying to match the requirements
req := NewRequires(name, version, release, "", "EQ", "")
sorted := make(Packages, 0, len(pkgs))
for _, p := range pkgs {
if req.ProvideMatches(p) {
sorted = append(sorted, p)
}
}
if len(sorted) > 0 {
sort.Sort(sorted)
pkg = sorted[len(sorted)-1]
}
}
return pkg, err
}
示例4: SortHostPorts
// SortHostPorts sorts the given HostPort slice according to the
// sortOrder of each HostPort's embedded Address and the preferIpv6
// flag. See Address.sortOrder() for more info.
func SortHostPorts(hps []HostPort, preferIPv6 bool) {
if preferIPv6 {
sort.Sort(hostPortsPreferringIPv6Slice{hostPortsPreferringIPv4Slice(hps)})
} else {
sort.Sort(hostPortsPreferringIPv4Slice(hps))
}
}
示例5: TestSort
func TestSort(t *testing.T) {
infos := InfoArray{
{"a", Float64Value(3.0), 0, 0, 0, 0},
{"b", Float64Value(1.0), 0, 0, 0, 0},
{"c", Float64Value(2.1), 0, 0, 0, 0},
{"d", Float64Value(2.0), 0, 0, 0, 0},
{"e", Float64Value(-1.0), 0, 0, 0, 0},
}
// Verify forward sort.
sort.Sort(infos)
last := Float64Value(-math.MaxFloat64)
for _, info := range infos {
if info.Val.Less(last) {
t.Errorf("info val %v not increasing", info.Val)
}
last = info.Val.(Float64Value)
}
// Verify reverse sort.
sort.Sort(sort.Reverse(infos))
last = Float64Value(math.MaxFloat64)
for _, info := range infos {
if !info.Val.Less(last) {
t.Errorf("info val %v not decreasing", info.Val)
}
last = info.Val.(Float64Value)
}
}
示例6: Interfaces
// Interfaces returns object holding a lists of all the plugs and slots and their connections.
func (r *Repository) Interfaces() *Interfaces {
r.m.Lock()
defer r.m.Unlock()
ifaces := &Interfaces{}
// Copy and flatten plugs and slots
for _, plugs := range r.plugs {
for _, plug := range plugs {
p := &Plug{
PlugInfo: plug.PlugInfo,
Connections: append([]SlotRef(nil), plug.Connections...),
}
sort.Sort(bySlotRef(p.Connections))
ifaces.Plugs = append(ifaces.Plugs, p)
}
}
for _, slots := range r.slots {
for _, slot := range slots {
s := &Slot{
SlotInfo: slot.SlotInfo,
Connections: append([]PlugRef(nil), slot.Connections...),
}
sort.Sort(byPlugRef(s.Connections))
ifaces.Slots = append(ifaces.Slots, s)
}
}
sort.Sort(byPlugSnapAndName(ifaces.Plugs))
sort.Sort(bySlotSnapAndName(ifaces.Slots))
return ifaces
}
示例7: testPeerListsMatch
func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {
if len(p1) != len(p2) {
t.Fatal("did not find as many peers as should have", p1, p2)
}
ids1 := make([]string, len(p1))
ids2 := make([]string, len(p2))
for i, p := range p1 {
ids1[i] = string(p)
}
for i, p := range p2 {
ids2[i] = string(p)
}
sort.Sort(sort.StringSlice(ids1))
sort.Sort(sort.StringSlice(ids2))
for i := range ids1 {
if ids1[i] != ids2[i] {
t.Fatal("Didnt find expected peer", ids1[i], ids2)
}
}
}
示例8: MatchingInstanceTypes
// MatchingInstanceTypes returns all instance types matching constraints and available
// in region, sorted by increasing region-specific cost (if known).
func MatchingInstanceTypes(allInstanceTypes []InstanceType, region string, cons constraints.Value) ([]InstanceType, error) {
var itypes []InstanceType
// Rules used to select instance types:
// - non memory constraints like cpu-cores etc are always honoured
// - if no mem constraint specified and instance-type not specified,
// try opinionated default with enough mem to run a server.
// - if no matches and no mem constraint specified, try again and
// return any matching instance with the largest memory
origCons := cons
if !cons.HasInstanceType() && cons.Mem == nil {
minMem := uint64(minMemoryHeuristic)
cons.Mem = &minMem
}
itypes = matchingTypesForConstraint(allInstanceTypes, cons)
// No matches using opinionated default, so if no mem constraint specified,
// look for matching instance with largest memory.
if len(itypes) == 0 && cons.Mem != origCons.Mem {
itypes = matchingTypesForConstraint(allInstanceTypes, origCons)
if len(itypes) > 0 {
sort.Sort(byMemory(itypes))
itypes = []InstanceType{itypes[len(itypes)-1]}
}
}
// If we have matching instance types, we can return those, sorted by cost.
if len(itypes) > 0 {
sort.Sort(byCost(itypes))
return itypes, nil
}
// No luck, so report the error.
return nil, fmt.Errorf("no instance types in %s matching constraints %q", region, origCons)
}
示例9: TestNodes
func TestNodes(t *testing.T) {
st := tbl.Construct(t)
for _, node := range tbl.Nodes {
reply, err := st.Nodes(ctx, &xpb.NodesRequest{
Ticket: []string{node.Ticket},
})
testutil.FatalOnErrT(t, "NodesRequest error: %v", err)
if len(reply.Node) != 1 {
t.Fatalf("Expected 1 node for %q; found %d: {%v}", node.Ticket, len(reply.Node), reply)
} else if expected := nodeInfo(node); !reflect.DeepEqual(reply.Node[0], expected) {
t.Fatalf("Expected {%v}; received {%v}", expected, reply.Node[0])
}
}
var tickets []string
var expected []*xpb.NodeInfo
for _, n := range tbl.Nodes {
tickets = append(tickets, n.Ticket)
expected = append(expected, nodeInfo(n))
}
reply, err := st.Nodes(ctx, &xpb.NodesRequest{Ticket: tickets})
testutil.FatalOnErrT(t, "NodesRequest error: %v", err)
sort.Sort(byNodeTicket(expected))
sort.Sort(byNodeTicket(reply.Node))
if !reflect.DeepEqual(expected, reply.Node) {
t.Fatalf("Expected {%v}; received {%v}", expected, reply.Node)
}
}
示例10: TestUnreferencedBlobs
func TestUnreferencedBlobs(t *testing.T) {
WithTestEnvironment(t, checkerTestData, func(repodir string) {
repo := OpenLocalRepo(t, repodir)
snID := "51d249d28815200d59e4be7b3f21a157b864dc343353df9d8e498220c2499b02"
OK(t, repo.Backend().Remove(backend.Snapshot, snID))
unusedBlobsBySnapshot := backend.IDs{
ParseID("58c748bbe2929fdf30c73262bd8313fe828f8925b05d1d4a87fe109082acb849"),
ParseID("988a272ab9768182abfd1fe7d7a7b68967825f0b861d3b36156795832c772235"),
ParseID("c01952de4d91da1b1b80bc6e06eaa4ec21523f4853b69dc8231708b9b7ec62d8"),
ParseID("bec3a53d7dc737f9a9bee68b107ec9e8ad722019f649b34d474b9982c3a3fec7"),
ParseID("2a6f01e5e92d8343c4c6b78b51c5a4dc9c39d42c04e26088c7614b13d8d0559d"),
ParseID("18b51b327df9391732ba7aaf841a4885f350d8a557b2da8352c9acf8898e3f10"),
}
sort.Sort(unusedBlobsBySnapshot)
chkr := checker.New(repo)
OK(t, chkr.LoadIndex())
OKs(t, checkPacks(chkr))
OKs(t, checkStruct(chkr))
blobs := chkr.UnusedBlobs()
sort.Sort(blobs)
Equals(t, unusedBlobsBySnapshot, blobs)
})
}
示例11: printTags
// printTags collects all tags referenced in the profile and prints
// them in a sorted table.
func printTags(w io.Writer, rpt *Report) error {
p := rpt.prof
// Hashtable to keep accumulate tags as key,value,count.
tagMap := make(map[string]map[string]int64)
for _, s := range p.Sample {
for key, vals := range s.Label {
for _, val := range vals {
if valueMap, ok := tagMap[key]; ok {
valueMap[val] = valueMap[val] + s.Value[0]
continue
}
valueMap := make(map[string]int64)
valueMap[val] = s.Value[0]
tagMap[key] = valueMap
}
}
for key, vals := range s.NumLabel {
for _, nval := range vals {
val := scaledValueLabel(nval, key, "auto")
if valueMap, ok := tagMap[key]; ok {
valueMap[val] = valueMap[val] + s.Value[0]
continue
}
valueMap := make(map[string]int64)
valueMap[val] = s.Value[0]
tagMap[key] = valueMap
}
}
}
tagKeys := make(tags, 0, len(tagMap))
for key := range tagMap {
tagKeys = append(tagKeys, &tag{name: key})
}
sort.Sort(tagKeys)
for _, tagKey := range tagKeys {
var total int64
key := tagKey.name
tags := make(tags, 0, len(tagMap[key]))
for t, c := range tagMap[key] {
total += c
tags = append(tags, &tag{name: t, weight: c})
}
sort.Sort(tags)
fmt.Fprintf(w, "%s: Total %d\n", key, total)
for _, t := range tags {
if total > 0 {
fmt.Fprintf(w, " %8d (%s): %s\n", t.weight,
percentage(t.weight, total), t.name)
} else {
fmt.Fprintf(w, " %8d: %s\n", t.weight, t.name)
}
}
fmt.Fprintln(w)
}
return nil
}
示例12: Spearman
// Spearman returns the rank correlation coefficient between data1 and data2, and the associated p-value
func Spearman(data1, data2 []float64) (rs float64, p float64) {
n := len(data1)
wksp1, wksp2 := make([]float64, n), make([]float64, n)
copy(wksp1, data1)
copy(wksp2, data2)
sort.Sort(sort2{wksp1, wksp2})
sf := crank(wksp1)
sort.Sort(sort2{wksp2, wksp1})
sg := crank(wksp2)
d := 0.0
for j := 0; j < n; j++ {
sq := wksp1[j] - wksp2[j]
d += (sq * sq)
}
en := float64(n)
en3n := en*en*en - en
fac := (1.0 - sf/en3n) * (1.0 - sg/en3n)
rs = (1.0 - (6.0/en3n)*(d+(sf+sg)/12.0)) / math.Sqrt(fac)
if fac = (rs + 1.0) * (1.0 - rs); fac > 0 {
t := rs * math.Sqrt((en-2.0)/fac)
df := en - 2.0
p = mathx.BetaInc(df/(df+t*t), 0.5*df, 0.5)
}
return rs, p
}
示例13: main
// start
func main() {
var p Player
folderPath, _ := osext.ExecutableFolder()
p.client_id, _ = ioutil.ReadFile(folderPath + "/client_id.txt")
p.MinD = 50 * 60 * 1000
p.MaxD = 500 * 60 * 1000
println("Please type a search term or 'x' to exit ....")
r := bufio.NewReader(os.Stdin)
for {
i, _, _ := r.ReadLine()
p.li = string(i)
switch {
case p.li == "x":
p.exit()
case p.li == "ll":
p.showResultList()
case strings.HasPrefix(p.li, "set "):
p.set()
case strings.HasPrefix(p.li, "i "):
p.info()
case isAllint(p.li):
go p.killAndPlay()
case true:
p.searchSoundCloud()
sort.Sort(ByLength{p.srs})
sort.Sort(ByAge{p.srs})
p.showResultList()
}
}
}
示例14: TestUserRemoveRole
func (s *S) TestUserRemoveRole(c *check.C) {
u := User{
Email: "[email protected]",
Password: "123",
Roles: []RoleInstance{
{Name: "r1", ContextValue: "c1"},
{Name: "r1", ContextValue: "c2"},
{Name: "r2", ContextValue: "x"},
},
}
err := u.Create()
c.Assert(err, check.IsNil)
err = u.RemoveRole("r1", "c2")
c.Assert(err, check.IsNil)
err = u.RemoveRole("r1", "c2")
c.Assert(err, check.IsNil)
expected := []RoleInstance{
{Name: "r1", ContextValue: "c1"},
{Name: "r2", ContextValue: "x"},
}
sort.Sort(roleInstanceList(expected))
sort.Sort(roleInstanceList(u.Roles))
c.Assert(u.Roles, check.DeepEquals, expected)
uDB, err := GetUserByEmail("[email protected]")
c.Assert(err, check.IsNil)
sort.Sort(roleInstanceList(uDB.Roles))
c.Assert(uDB.Roles, check.DeepEquals, expected)
}
示例15: _sort
func _sort(programTree *program.Program, filename string, _groupMethodsByType bool, _groupMethodsByVisibility bool, _sortImports bool, order string) (bool, *errors.GoRefactorError) {
if ok, err := CheckSortParameters(filename, order); !ok {
return false, err
}
pack, file := programTree.FindPackageAndFileByFilename(filename)
if pack == nil {
return false, errors.ArgumentError("filename", "Program packages don't contain file '"+filename+"'")
}
fset := pack.FileSet
tokFile := printerUtil.GetFileFromFileSet(fset, filename)
groupMethodsByType = _groupMethodsByType
groupMethodsByVisibility = _groupMethodsByVisibility
sortImports = _sortImports
fullOrder = getFullOrder(order)
decls := &DeclCollection{file.Decls, file, fset, tokFile}
if sortImports {
for _, d := range decls.Arr {
if gd, ok := d.(*ast.GenDecl); ok {
if gd.Tok == token.IMPORT {
sort.Sort(SpecCollection(gd.Specs))
}
}
}
}
printDecls(tokFile, file)
//test
//decls.Swap(2, decls.Len()-1)
sort.Sort(decls)
printDecls(tokFile, file)
//printer.Fprint(os.Stdout, fset, file)
return true, nil
}