本文整理汇总了Python中trac.util.sorted函数的典型用法代码示例。如果您正苦于以下问题:Python sorted函数的具体用法?Python sorted怎么用?Python sorted使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sorted函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: expand_macro
def expand_macro(self, formatter, name, content):
args, kw = util.parse_args(content)
prefix = args and args[0] or None
format = kw.get('format', '')
minsize = max(int(kw.get('min', 2)), 2)
depth = int(kw.get('depth', -1))
start = prefix and prefix.count('/') or 0
wiki = formatter.wiki
pages = sorted([page for page in wiki.get_pages(prefix) \
if 'WIKI_VIEW' in formatter.perm('wiki', page)])
pagelangs = {}
for page in pages:
name, lang = util.split_lang(page, '')
langs = pagelangs.get(name, [])
if lang not in langs:
langs.append(lang)
pagelangs[name] = langs
pages = sorted(pagelangs.keys()) # collection of default pages
upages, spages = self.split_pages(pages)
def format_page_name(page, split=False):
try:
# for trac 0.11
return wiki.format_page_name(page, split=split)
except:
# for trac 0.10
if split:
return self.PAGE_SPLIT_RE.sub(r"\1 \2", page)
return page
def split(page):
if format != 'group':
return [format_page_name(page)]
else:
return self.SPLIT_RE.split(format_page_name(page, split=True))
# Group by Wiki word and/or Wiki hierarchy
upages, spages = [[(split(page), page) for page in pages
if depth < 0 or depth >= page.count('/') - start]
for pages in (upages, spages)]
def split_in_groups(group):
"""Return list of pagename or (key, sublist) elements"""
groups = []
for key, subgrp in groupby(group, lambda (k,p): k and k[0] or ''):
subgrp = [(k[1:],p) for k,p in subgrp]
if key and len(subgrp) >= minsize:
sublist = split_in_groups(sorted(subgrp))
if len(sublist) == 1:
elt = (key+sublist[0][0], sublist[0][1])
else:
elt = (key, sublist)
groups.append(elt)
else:
for elt in subgrp:
groups.append(elt[1])
return groups
示例2: _get_candidate_subjects
def _get_candidate_subjects(self, not_in_list = []):
candidates = []
users = [user for user in self._get_all_users()
if user not in not_in_list]
candidates += sorted(users)
candidates += sorted([group.__str__() for group in self.authz.get_groups()
if group.__str__() not in not_in_list])
#self.env.log.debug("Candidates:")
#for c in candidates:
# self.env.log.debug(" %s" % c)
return candidates
示例3: _get_candidate_subjects
def _get_candidate_subjects(self, not_in_list = []):
candidates = []
if '*' not in not_in_list:
candidates.append('*')
users = [user for user in self.account_manager.get_users()
if user not in not_in_list]
candidates += sorted(users)
candidates += sorted([group.__str__() for group in self.authz.get_groups()
if group.__str__() not in not_in_list])
self.env.log.debug("Candidates:")
for c in candidates:
self.env.log.debug(" %s" % c)
return candidates
示例4: render_macro
def render_macro(self, req, name, content):
intertracs = {}
for key, value in self.config.options('intertrac'):
idx = key.rfind('.') # rsplit only in 2.4
if idx > 0: # 0 itself doesn't help much: .xxx = ...
prefix, attribute = key[:idx], key[idx+1:]
intertrac = intertracs.setdefault(prefix, {})
intertrac[attribute] = value
else:
intertracs[key] = value # alias
def generate_prefix(prefix):
intertrac = intertracs[prefix]
if isinstance(intertrac, basestring):
yield html.TR(html.TD(html.B(prefix)),
html.TD('Alias pour ', html.B(intertrac)))
else:
url = intertrac.get('url', '')
if url:
title = intertrac.get('title', url)
yield html.TR(html.TD(html.A(html.B(prefix),
href=url + '/timeline')),
html.TD(html.A(title, href=url)))
return html.TABLE(class_="wiki intertrac")(
html.TR(html.TH(html.EM('Prefix')), html.TH(html.EM('Site Trac'))),
[generate_prefix(p) for p in sorted(intertracs.keys())])
示例5: render_admin_panel
def render_admin_panel(self, req, cat, page, path_info):
db = self.env.get_db_cnx()
cursor = db.cursor()
field = dict([(field['name'], field) for field in TicketSystem(self.env).get_ticket_fields()])[page]
cursor.execute('SELECT sid, value FROM hidevals WHERE field = %s', (field['name'],))
values = cursor.fetchall()
enabled = field['name'] not in HideValsSystem(self.env).dont_filter
if req.method == 'POST':
if req.args.get('add'):
group = req.args['group']
value = req.args['value']
if (group, value) not in values:
cursor.execute('INSERT INTO hidevals (sid, field, value) VALUES (%s, %s, %s)', (group, field['name'], value))
db.commit()
elif req.args.get('remove'):
sel = req.args.getlist('sel')
for val in sel:
group, value = val.split('#', 1)
cursor.execute('DELETE FROM hidevals WHERE sid = %s AND field = %s AND value = %s', (group, field['name'], value))
db.commit()
elif req.args.get('toggle'):
new_val = HideValsSystem(self.env).dont_filter[:]
if enabled:
new_val.append(field['name'])
else:
new_val.remove(field['name'])
self.config.set('hidevals', 'dont_filter', ', '.join(sorted(new_val)))
self.config.save()
req.redirect(req.href.admin(cat, page))
data = {'field' : field,
'values' : [{'group': g, 'value': v} for g, v in values],
'enabled' : enabled}
return 'admin_hidevals.html', data
示例6: _edit_path
def _edit_path(self, req, cat, page, path_info):
"""
Populates the editpath.* parts of the hdf
@return the value of editgroup.url or None
"""
data = {}
editpath = url2pathname(path_info[path_info.index('/')+1:len(path_info)])
paths = [(p.get_repo(), p.get_path()) for p in self.authz.get_paths()]
validpath = self._get_valid_path(paths, editpath)
if validpath:
data['editpath_name'] = editpath
data['editpath_url'] = pathname2url(editpath)
pathmembers = self.authz.find_path(validpath[1], validpath[0])
editpath_members = []
for member in pathmembers:
read = write = ""
if member.is_read():
read = "checked"
if member.is_write():
write = "checked"
editpath_members.append({'subject' : member.get_member().__str__(),
'read' : read,
'write' : write})
data['editpath_members'] = sorted(editpath_members, key=lambda member : member['subject'].lower())
# Populate member candidates
not_in_list = [m.get_member().__str__() for m in pathmembers]
candidates = self._get_candidate_subjects(not_in_list)
if candidates != []:
data['editpath_candidates'] = candidates
return data['editpath_url'], data
return None, {}
示例7: expand_macro
def expand_macro(self, formatter, name, content):
intertracs = {}
for key, value in self.config.options('intertrac'):
idx = key.rfind('.') # rsplit only in 2.4
if idx > 0: # 0 itself doesn't help much: .xxx = ...
prefix, attribute = key[:idx], key[idx+1:]
intertrac = intertracs.setdefault(prefix, {})
intertrac[attribute] = value
else:
intertracs[key] = value # alias
def generate_prefix(prefix):
intertrac = intertracs[prefix]
if isinstance(intertrac, basestring):
yield tag.tr(tag.td(tag.b(prefix)),
tag.td('Alias for ', tag.b(intertrac)))
else:
url = intertrac.get('url', '')
if url:
title = intertrac.get('title', url)
yield tag.tr(tag.td(tag.a(tag.b(prefix),
href=url + '/timeline')),
tag.td(tag.a(title, href=url)))
return tag.table(class_="wiki intertrac")(
tag.tr(tag.th(tag.em('Prefix')), tag.th(tag.em('Trac Site'))),
[generate_prefix(p) for p in sorted(intertracs.keys())])
示例8: render_macro
def render_macro(self, req, name, filter):
from trac.config import Option
from trac.wiki.formatter import wiki_to_html, wiki_to_oneliner
filter = filter or ""
sections = set([section for section, option in Option.registry.keys() if section.startswith(filter)])
return html.DIV(class_="tracini")(
[
(
html.H2("[%s]" % section, id="%s-section" % section),
html.TABLE(class_="wiki")(
html.TBODY(
[
html.TR(
html.TD(html.TT(option.name)), html.TD(wiki_to_oneliner(option.__doc__, self.env))
)
for option in Option.registry.values()
if option.section == section
]
)
),
)
for section in sorted(sections)
]
)
示例9: save
def save(self):
"""Write the configuration options to the primary file."""
if not self.filename:
return
# Only save options that differ from the defaults
sections = []
for section in self.sections():
options = []
for option in self[section]:
default = self.site_parser.has_option(section, option) and \
self.site_parser.get(section, option)
current = self.parser.has_option(section, option) and \
self.parser.get(section, option)
if current is not False and current != default:
options.append((option, current))
if options:
sections.append((section, sorted(options)))
fileobj = file(self.filename, 'w')
try:
print>>fileobj, '# -*- coding: utf-8 -*-'
print>>fileobj
for section, options in sections:
print>>fileobj, '[%s]' % section
for key, val in options:
if key in self[section].overridden:
print>>fileobj, '# %s = <set in global trac.ini>' % key
else:
val = val.replace(CRLF, '\n').replace('\n', '\n ')
print>>fileobj, '%s = %s' % \
(key, to_unicode(val).encode('utf-8'))
print>>fileobj
finally:
fileobj.close()
示例10: process_request
def process_request(self, req):
mode = req.args.get('mode', 'view')
all_fields = []
standard_fields = set()
for f in TicketSystem(self.env).get_ticket_fields():
all_fields.append(f['name'])
if not f.get('custom'):
standard_fields.add(f['name'])
if 'owner' in all_fields:
curr_idx = all_fields.index('owner')
if 'cc' in all_fields:
insert_idx = all_fields.index('cc')
else:
insert_idx = len(all_fields)
if curr_idx < insert_idx:
all_fields.insert(insert_idx, all_fields[curr_idx])
del all_fields[curr_idx]
for t in self.types:
fields = set(getattr(self, t+'_fields'))
if self.include_std:
fields.update(standard_fields)
fields.update(self.forced_fields)
req.hdf['condfields.types.%s'%t] = dict([
(f, f in fields) for f in all_fields
])
req.hdf['condfields.mode'] = mode
req.hdf['condfields.all_fields'] = list(all_fields)
req.hdf['condfields.ok_fields'] = sorted(set(all_fields) - self.forced_fields, key=lambda x: all_fields.index(x))
return 'condfields.cs', 'text/javascript'
示例11: _do_config
def _do_config(self, req):
if req.method == 'POST':
selected_class = req.args.get('selected')
self.config.set('account-manager', 'password_store', selected_class)
selected = self.account_manager.password_store
for attr, option in _getoptions(selected):
newvalue = req.args.get('%s.%s' % (selected_class, attr))
if newvalue is not None:
self.config.set(option.section, option.name, newvalue)
self.config.save()
try:
selected = self.account_manager.password_store
except AttributeError:
selected = None
sections = [
{'name': store.__class__.__name__,
'classname': store.__class__.__name__,
'selected': store is selected,
'options': [
{'label': attr,
'name': '%s.%s' % (store.__class__.__name__, attr),
'value': option.__get__(store, store),
}
for attr, option in _getoptions(store)
],
} for store in self.account_manager.stores
]
sections = sorted(sections, key=lambda i: i['name'])
req.hdf['sections'] = sections
return 'admin_accountsconfig.cs', None
示例12: render_macro
def render_macro(self, req, name, content):
prefix = content or None
wiki = WikiSystem(self.env)
return html.UL([html.LI(html.A(wiki.format_page_name(page),
href=req.href.wiki(page)))
for page in sorted(wiki.get_pages(prefix))])
示例13: _render_directory
def _render_directory(self, req, repos, node, rev=None):
req.perm.assert_permission('BROWSER_VIEW')
# Entries metadata
info = []
for entry in node.get_entries():
info.append({
'name': entry.name,
'fullpath': entry.path,
'is_dir': entry.isdir,
'content_length': entry.content_length,
'size': pretty_size(entry.content_length),
'rev': entry.rev,
'log_href': req.href.log(entry.path, rev=rev),
'browser_href': req.href.browser(entry.path, rev=rev)
})
changes = get_changes(self.env, repos, [i['rev'] for i in info])
# Ordering of entries
order = req.args.get('order', 'name').lower()
desc = req.args.has_key('desc')
if order == 'date':
def file_order(a):
return changes[a['rev']]['date_seconds']
elif order == 'size':
def file_order(a):
return (a['content_length'],
embedded_numbers(a['name'].lower()))
else:
def file_order(a):
return embedded_numbers(a['name'].lower())
dir_order = desc and 1 or -1
def browse_order(a):
return a['is_dir'] and dir_order or 0, file_order(a)
info = sorted(info, key=browse_order, reverse=desc)
switch_ordering_hrefs = {}
for col in ('name', 'size', 'date'):
switch_ordering_hrefs[col] = req.href.browser(
node.path, rev=rev, order=col,
desc=(col == order and not desc and 1 or None))
# ''Zip Archive'' alternate link
patterns = self.downloadable_paths
if node.path and patterns and \
filter(None, [fnmatchcase(node.path, p) for p in patterns]):
zip_href = req.href.changeset(rev or repos.youngest_rev, node.path,
old=rev, old_path='/', format='zip')
add_link(req, 'alternate', zip_href, 'Zip Archive',
'application/zip', 'zip')
req.hdf['browser'] = {'order': order, 'desc': desc and 1 or 0,
'items': info, 'changes': changes,
'order_href': switch_ordering_hrefs}
示例14: write_groups
def write_groups(self, groups):
"""write new group file"""
group_file_name = self.get_group_filename()
#load the file into the memory
if os.path.exists(group_file_name):
group_file = file(group_file_name, 'w')
try:
for group_name in sorted(groups):
if groups[group_name]: #if non empty
group_file.write('%s: %s\n' % (
group_name,
' '.join(sorted(groups[group_name]))
))
finally:
group_file.close()
self.env.log.debug('htgroup-editor wrote %r' % (group_file_name,))
示例15: _do_htgroup
def _do_htgroup(self, req):
"""Provide a list of groups, a current group name and a list
of users in the current group.
"""
# get the groups from the database file
groups = self.get_groups()
# prepare the selection and user list
group_name = req.args.get('group')
if not group_name or group_name not in groups:
# no group name given, try to use a default
if groups: #not empty
group_name = sorted(groups.keys())[0]
else:
group_name = None
# process forms/commands
if req.method == 'POST':
if req.args.get('add'):
new_group = req.args.get('new_group')
new_user = req.args.get('new_user')
groups.setdefault(new_group, []).append(new_user)
self.write_groups(groups)
req.hdf['message'] = u'added %s to %s' % (new_user, new_group)
elif req.args.get('remove') and req.args.get('group'):
sel = req.args.get('sel')
sel = isinstance(sel, list) and sel or [sel]
for user in sel:
groups[req.args.get('group')].remove(user)
self.write_groups(groups)
req.hdf['message'] = u'removed %s from %s' % (sel, req.args.get('group'))
# listst and other info
req.hdf['groups'] = sorted(groups.keys())
listing_enabled = isinstance(group_name, basestring) and group_name in groups
if listing_enabled:
req.hdf['group'] = group_name
req.hdf['members'] = sorted(groups[group_name])
req.hdf['listing_enabled'] = listing_enabled
req.hdf['selection_enabled'] = len(groups.keys()) > 1
return 'htgroup_editor.cs', None