rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
self.load(htpasswd) | PasswordFileAuthentication.__init__(self, htpasswd) | def __init__(self, htpasswd, realm): self.hash = {} self.realm = realm try: import crypt self.crypt = crypt.crypt except ImportError: self.crypt = None self.load(htpasswd) |
class DigestAuthentication(HTTPAuthentication): | class DigestAuthentication(PasswordFileAuthentication): | def do_auth(self, environ, start_response): header = environ.get('HTTP_AUTHORIZATION') if header and header.startswith('Basic'): auth = b64decode(header[6:]).split(':') if len(auth) == 2: user, password = auth if self.test(user, password): return user |
self.hash = {} | def __init__(self, htdigest, realm): self.active_nonces = [] self.hash = {} self.realm = realm self.load_htdigest(htdigest, realm) | |
self.load_htdigest(htdigest, realm) def load_htdigest(self, filename, realm): | PasswordFileAuthentication.__init__(self, htdigest) def load(self, filename): | def __init__(self, htdigest, realm): self.active_nonces = [] self.hash = {} self.realm = realm self.load_htdigest(htdigest, realm) |
if r == realm: | if r == self.realm: | def load_htdigest(self, filename, realm): """Load account information from apache style htdigest files, only users from the specified realm are used """ fd = open(filename, 'r') for line in fd.readlines(): line = line.strip() if not line: continue try: u, r, a1 = line.split(':') except ValueError: print >>sys.stderr, '... |
print >> sys.stderr, "Warning: found no users in realm:", realm | print >> sys.stderr, "Warning: found no users in realm:", self.realm | def load_htdigest(self, filename, realm): """Load account information from apache style htdigest files, only users from the specified realm are used """ fd = open(filename, 'r') for line in fd.readlines(): line = line.strip() if not line: continue try: u, r, a1 = line.split(':') except ValueError: print >>sys.stderr, '... |
fd = None | fd = open(os.path.join(self.path, 'VERSION'), 'r') | def verify(self): """Verify that the provided path points to a valid Trac environment directory.""" fd = None try: fd = open(os.path.join(self.path, 'VERSION'), 'r') assert fd.read(26) == 'Trac Environment Version 1' finally: if fd: fd.close() |
fd = open(os.path.join(self.path, 'VERSION'), 'r') | def verify(self): """Verify that the provided path points to a valid Trac environment directory.""" fd = None try: fd = open(os.path.join(self.path, 'VERSION'), 'r') assert fd.read(26) == 'Trac Environment Version 1' finally: if fd: fd.close() | |
if fd: fd.close() | fd.close() | def verify(self): """Verify that the provided path points to a valid Trac environment directory.""" fd = None try: fd = open(os.path.join(self.path, 'VERSION'), 'r') assert fd.read(26) == 'Trac Environment Version 1' finally: if fd: fd.close() |
""" Creates a new HDF dataset. | """Create a new HDF dataset. | def __init__(self, loadpaths=[]): """ Creates a new HDF dataset. The loadpaths parameter can be used to specify a sequence of paths under which ClearSilver will search for template files: |
""" Adds data to the HDF dataset. The `name` parameter is the path of the node in dotted syntax. The `value` parameter can be a simple value such as a string or number, but also data structures such as dicts and lists. | """Add data to the HDF dataset. The `name` parameter is the path of the node in dotted syntax. The `value` parameter can be a simple value such as a string or number, but also data structures such as dicts and lists. | def __setitem__(self, name, value): """ Adds data to the HDF dataset. The `name` parameter is the path of the node in dotted syntax. The `value` parameter can be a simple value such as a string or number, but also data structures such as dicts and lists. |
if hasattr(value, '__iter__'): | if hasattr(value, '__iter__') or \ isinstance(value, (list, tuple)): | def add_value(prefix, value): if value is None: return elif value in (True, False): self.hdf.setValue(prefix, str(int(value))) elif isinstance(value, (str, unicode)): self.hdf.setValue(prefix, value) elif isinstance(value, dict): for k in value.keys(): add_value('%s.%s' % (prefix, k), value[k]) else: if hasattr(value, ... |
""" Parses the given string as template text, and returns a neo_cs.CS object. | """Parse the given string as template text, and returns a neo_cs.CS object. | def parse(self, string): """ Parses the given string as template text, and returns a neo_cs.CS object. """ import neo_cs cs = neo_cs.CS(self.hdf) cs.parseStr(string) return cs |
""" Renders the HDF using the given template. | """Render the HDF using the given template. | def render(self, template): """ Renders the HDF using the given template. The template parameter can be either an already parse neo_cs.CS object, or a string. In the latter case it is interpreted as name of the template file. """ if isinstance(template, (str, unicode)): filename = template import neo_cs template = neo... |
from trac.util import escape | def render(self, req, mimetype, content, filename=None, rev=None): if is_binary(content): self.env.log.debug("Binary data; no preview available") return | |
(updater, ) = cursor.fetchone() | for updater, in cursor: break else: cursor.execute("SELECT reporter FROM ticket WHERE id=%s", (tktid,)) for updater, in cursor: break | def get_recipients(self, tktid): notify_reporter = self.config.getbool('notification', 'always_notify_reporter') notify_owner = self.config.getbool('notification', 'always_notify_owner') notify_updater = self.config.getbool('notification', 'always_notify_updater') |
def send_project_index(req, mpr, dir): req.content_type = 'text/html' req.write('<html><head><title>Available Projects</title></head>') req.write('<body><h1>Available Projects</h1><ul>') for project in os.listdir(dir): req.write('<li><a href="%s">%s</a></li>' % (href_join(mpr.idx_location, project), project)) req.write... | def send_project_index(req, mpr, dir, options): from trac.web.clearsilver import HDFWrapper if 'TracEnvIndexTemplate' in options: tmpl_path, template = os.path.split(options['TracEnvIndexTemplate']) from trac.siteconfig import __default_templates_dir__ as def_path mpr.hdf = HDFWrapper(loadpaths=[def_path, tmpl_path]... | def send_project_index(req, mpr, dir): req.content_type = 'text/html' req.write('<html><head><title>Available Projects</title></head>') req.write('<body><h1>Available Projects</h1><ul>') for project in os.listdir(dir): req.write('<li><a href="%s">%s</a></li>' % (href_join(mpr.idx_location, project), project)) req.write... |
send_project_index(req, mpr, env_parent_dir) | send_project_index(req, mpr, env_parent_dir, options) | def get_environment(req, mpr, options): global env_cache, env_cache_lock if options.has_key('TracEnv'): env_path = options['TracEnv'] elif options.has_key('TracEnvParentDir'): env_parent_dir = options['TracEnvParentDir'] env_name = mpr.cgi_location.split('/')[-1] env_path = os.path.join(env_parent_dir, env_name) if le... |
url = self.env.config.get('intertrac', ns + '.url') | intertrac_config = self.env.config['intertrac'] url = intertrac_config.get(ns+'.url') | def _make_intertrac_link(self, ns, target, label): url = self.env.config.get('intertrac', ns + '.url') if url: name = self.env.config.get('intertrac', ns + '.title', 'Trac project %s' % ns) sep = target.find(':') if sep != -1: url = '%s/%s/%s' % (url, target[:sep], target[sep + 1:]) else: url = '%s/search?q=%s' % (url,... |
name = self.env.config.get('intertrac', ns + '.title', 'Trac project %s' % ns) sep = target.find(':') if sep != -1: url = '%s/%s/%s' % (url, target[:sep], target[sep + 1:]) else: url = '%s/search?q=%s' % (url, urllib.quote_plus(target)) | name = intertrac_config.get(ns+'.title', 'Trac project %s' % ns) compat = intertrac_config.getbool(ns+'.compat', 'true') if compat: sep = target.find(':') if sep != -1: url = '%s/%s/%s' % (url, target[:sep], target[sep + 1:]) else: url = '%s/search?q=%s' % (url, urllib.quote_plus(target)) else: url = '%s/intertrac/%s... | def _make_intertrac_link(self, ns, target, label): url = self.env.config.get('intertrac', ns + '.url') if url: name = self.env.config.get('intertrac', ns + '.title', 'Trac project %s' % ns) sep = target.find(':') if sep != -1: url = '%s/%s/%s' % (url, target[:sep], target[sep + 1:]) else: url = '%s/search?q=%s' % (url,... |
def usage(): print '\nUsage: %s <database> <command>' % sys.argv[0] print '\n Available commands:' print ' initdb' print ' config list' print ' config set <name> <value>' print ' component list' print ' component add <name> <owner>' print ' component remove <name>' print ' component set owner <name> <new_... | class TracAdmin(cmd.Cmd): intro = '' license = __license__ credits = '\n Visit the Trac Project at http://trac.edgewall.com/ \n' \ '\n Trac is brought to you by: \n' \ '----------------------------------------------------------------- \n' \ ' Edgewall Research & Development \n' \ ' Profe... | def usage(): print '\nUsage: %s <database> <command>' % sys.argv[0] print '\n Available commands:' print ' initdb' print ' config list' print ' config set <name> <value>' print ' component list' print ' component add <name> <owner>' print ' component remove <name>' print ' component set owner <name> <new_... |
def insert_default_values (cursor): cursor.execute (""" | def initdb_insert_default_values (self, cursor): cursor.execute (""" | def insert_default_values (cursor): cursor.execute (""" |
def cmd_initdb(): dbname = sys.argv[1] if os.access(dbname, os.R_OK): print 'database %s already exists' % dbname sys.exit(1) try: cnx = sqlite.connect (dbname) except Exception, e: print 'Failed to create database %s.' % dbname sys.exit(1) try: cursor = cnx.cursor () create_tables (cursor) insert_default_values (curso... | def cmd_initdb(): dbname = sys.argv[1] if os.access(dbname, os.R_OK): print 'database %s already exists' % dbname sys.exit(1) try: cnx = sqlite.connect (dbname) except Exception, e: print 'Failed to create database %s.' % dbname sys.exit(1) try: cursor = cnx.cursor () create_tables (cursor) insert_default_values (curso... | |
if sys.argv[2:] == ['initdb']: cmd_initdb() elif sys.argv[2:] == ['config', 'list']: cmd_config_list() elif sys.argv[2:4] == ['config', 'set'] and len(sys.argv) == 6: cmd_config_set() elif sys.argv[2:] == ['component', 'list']: cmd_component_list() elif sys.argv[2:4] == ['component', 'add'] and len(sys.argv) == 6: cmd_... | tracadm = TracAdmin() if len (sys.argv) > 1: if sys.argv[1] in ['-h','--help','help']: tracadm.onecmd ("help") elif sys.argv[1] in ['-v','--version','version','about']: tracadm.onecmd ("version") else: tracadm.db_set(sys.argv[1]) if len (sys.argv) > 2: s_args = ' '.join(["'%s'" % c for c in sys.argv[3:]]) command = sys... | def main(): if sys.argv[2:] == ['initdb']: cmd_initdb() elif sys.argv[2:] == ['config', 'list']: cmd_config_list() elif sys.argv[2:4] == ['config', 'set'] and len(sys.argv) == 6: cmd_config_set() elif sys.argv[2:] == ['component', 'list']: cmd_component_list() elif sys.argv[2:4] == ['component', 'add'] and len(sys.argv... |
usage() | tracadm.onecmd ("help") | def main(): if sys.argv[2:] == ['initdb']: cmd_initdb() elif sys.argv[2:] == ['config', 'list']: cmd_config_list() elif sys.argv[2:4] == ['config', 'set'] and len(sys.argv) == 6: cmd_config_set() elif sys.argv[2:] == ['component', 'list']: cmd_component_list() elif sys.argv[2:4] == ['component', 'add'] and len(sys.argv... |
write_date('DTSTAMP', localtime(milestone['due'])) | write_utctime('DTSTAMP', localtime(milestone['due'])) | def write_utctime(name, value, params={}): write_prop(name, strftime('%Y%m%dT%H%M%SZ', value), params) |
span_default_re = re.compile(r'<span class="p_default">(.*?)</span>', | span_default_re = re.compile(r'<span class="\w+_default">(.*?)</span>', | def render(self, req, mimetype, content, filename=None, rev=None): import SilverCity try: typelang = types[mimetype] lang = typelang[0] module = getattr(SilverCity, lang) generator = getattr(module, lang + "HTMLGenerator") try: allprops = typelang[1] propset = SilverCity.PropertySet() for p in allprops.keys(): propset[... |
return html.A(class_='%s ticket' % row[0], title=shorten_line(row[1]) + ' (%s)' % row[0], | return html.A(class_='%s ticket' % row[1], title=shorten_line(row[0]) + ' (%s)' % row[1], | def _format_link(self, formatter, ns, target, label, fullmatch=None): intertrac = formatter.shorthand_intertrac_helper(ns, target, label, fullmatch) if intertrac: return intertrac cursor = formatter.db.cursor() cursor.execute("SELECT summary,status FROM ticket WHERE id=%s", (target,)) row = cursor.fetchone() if row: re... |
req.hdf['title'] = 'Delete Report {%s} %s' % (id, row['title']) | req.hdf['title'] = 'Delete Report {%s} %s' % (id, row[0]) | def _render_confirm_delete(self, req, db, id): req.perm.assert_permission('REPORT_DELETE') |
'title': util.escape(row['title']), | 'title': util.escape(row[0]), | def _render_confirm_delete(self, req, db, id): req.perm.assert_permission('REPORT_DELETE') |
return tag.re( | return tag.tr( | def _head_row(): return tag.re( [tag.th(alabel, class_=atype) for atype, alabel in annotypes] + [tag.th(u'\xa0', class_='content')] ) |
cursor.execute("UPDATE ticket SET component=%s WHERE component=%s" | cursor.execute("UPDATE ticket SET component=%s WHERE component=%s", | def _do_component_rename(self, name, newname): cnx = self.db_open() cursor = cnx.cursor() cursor.execute("SELECT name FROM component WHERE name=%s", (name,)) if not cursor.fetchone(): raise Exception("No such component '%s'" % name) cursor.execute("UPDATE component SET name=%s WHERE name=%s", (newname, name)) cursor.ex... |
parser.error('either the --env_parent_dir option or at least one ' | parser.error('either the --env-parent-dir option or at least one ' | def _validate_callback(option, opt_str, value, parser, valid_values): if value not in valid_values: raise OptionValueError('%s must be one of: %s, not %s' % (opt_str, '|'.join(valid_values), value)) setattr(parser.values, option.dest, value) |
dirs = {} | dirs = [] | def process_request(self, req): prefix = req.args.get('prefix') filename = req.args.get('filename') |
filter_.post_process_request(None, None) | filter_.post_process_request(None, None, None) | def dispatch(self, req): """Find a registered handler that matches the request and let it process it. In addition, this method initializes the HDF data set and adds the web site chrome. """ # For backwards compatibility, should be removed in the future self.env.href = req.href self.env.abs_href = req.abs_href |
cursor.execute('SET search_path TO %s, public', (cnx.schema,)) | cursor.execute('SET search_path TO %s', (cnx.schema,)) | def init_db(self, path, user=None, password=None, host=None, port=None, params={}): cnx = self.get_connection(path, user, password, host, port, params) cursor = cnx.cursor() if cnx.schema: cursor.execute('CREATE SCHEMA %s' % cnx.schema) cursor.execute('SET search_path TO %s, public', (cnx.schema,)) from trac.db_default... |
cnx.cursor().execute('SET search_path TO %s, public', (self.schema,)) | cnx.cursor().execute('SET search_path TO %s', (self.schema,)) | def __init__(self, path, user=None, password=None, host=None, port=None, params={}): if path.startswith('/'): path = path[1:] # We support both psycopg and PgSQL but prefer psycopg global psycopg global PgSQL global PGSchemaError if not psycopg and not PgSQL: try: import psycopg2 as psycopg import psycopg2.extensions ... |
addrfmt = r"[\w\d_\.\-]+\@(([\w\d\-])+\.)+([\w\d]{2,4})+" | addrfmt = r"[\w\d_\.\-\+=]+\@(([\w\d\-])+\.)+([\w\d]{2,4})+" | def finish_send(self): """Clean up after sending all messages. Called after sending all messages.""" pass |
noquickjump = int(req.args.get('noquickjump', '0')) link_elt = self.quickjump(req, query) if link_elt is not None: quickjump_href = link_elt.attr['href'] if noquickjump: req.hdf['search.quickjump'] = { 'href': quickjump_href, 'name': html.EM(link_elt.children), 'description': link_elt.attr.get('title', '') } else: req.... | if query.startswith('!'): | def process_request(self, req): req.perm.assert_permission('SEARCH_VIEW') |
def quickjump(self, req, kwd): | def check_quickjump(self, req, kwd): noquickjump = int(req.args.get('noquickjump', '0')) | def quickjump(self, req, kwd): # Source quickjump if kwd[0] == '/': return req.href.browser(kwd) link = wiki_to_link(kwd, self.env, req) if isinstance(link, Element): return link |
return req.href.browser(kwd) link = wiki_to_link(kwd, self.env, req) if isinstance(link, Element): return link | quickjump_href = req.href.browser(kwd) name = kwd description = 'Browse repository path ' + kwd else: link = wiki_to_link(kwd, self.env, req) if isinstance(link, Element): quickjump_href = link.attr['href'] name = link.children description = link.attr.get('title', '') if quickjump_href: if noquickjump: req.hdf['search.... | def quickjump(self, req, kwd): # Source quickjump if kwd[0] == '/': return req.href.browser(kwd) link = wiki_to_link(kwd, self.env, req) if isinstance(link, Element): return link |
return self.cfg.items(section) | try: return self.cfg.items(section) except AttributeError: items=[] for option in self.cfg.options(section): items.append((option,self.cfg.get(section,option))) return items | def get_config_items(self, section): if not self.cfg.has_section(section): return None return self.cfg.items(section) |
for i, value in enumerate(s): | for value, i in s: print "inserting severity ", value, " ", i | def setSeverityList(self, s): """Remove all severities, set them to `s`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM enum WHERE type='severity'""") for i, value in enumerate(s): c.execute("""INSERT INTO enum (type, name, val... |
for i, value in enumerate(s): | for value, i in s: print "inserting priority ", value, " ", i | def setPriorityList(self, s): """Remove all priorities, set them to `s`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM enum WHERE type='priority'""") for i, value in enumerate(s): c.execute("""INSERT INTO enum (type, name, val... |
def setComponentList(self, l): | def setComponentList(self, l, key): | def setComponentList(self, l): """Remove all components, set them to `l`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM component""") for value in l: c.execute("""INSERT INTO component (name) VALUES (%s)""", value) self.db().c... |
for value in l: | for comp in l: print "inserting component ", comp[key] | def setComponentList(self, l): """Remove all components, set them to `l`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM component""") for value in l: c.execute("""INSERT INTO component (name) VALUES (%s)""", value) self.db().c... |
value) self.db().commit() def setVersionList(self, v): | comp[key]) self.db().commit() def setVersionList(self, v, key): | def setComponentList(self, l): """Remove all components, set them to `l`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM component""") for value in l: c.execute("""INSERT INTO component (name) VALUES (%s)""", value) self.db().c... |
for value in v: | for vers in v: print "inserting version ", vers[key] | def setVersionList(self, v): """Remove all versions, set them to `v`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM version""") for value in v: c.execute("""INSERT INTO version (name) VALUES (%s)""", value) self.db().commit() |
value) self.db().commit() def setMilestoneList(self, m): | vers[key]) self.db().commit() def setMilestoneList(self, m, key): | def setVersionList(self, v): """Remove all versions, set them to `v`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM version""") for value in v: c.execute("""INSERT INTO version (name) VALUES (%s)""", value) self.db().commit() |
for value in m: | for ms in m: print "inserting milestone ", ms[key] | def setMilestoneList(self, m): """Remove all milestones, set them to `m`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM milestone""") for value in m: c.execute("""INSERT INTO milestone (name) VALUES (%s)""", value) self.db().c... |
value) | ms[key]) | def setMilestoneList(self, m): """Remove all milestones, set them to `m`""" if self.hasTickets(): raise Exception("Will not modify database with existing tickets!") c = self.db().cursor() c.execute("""DELETE FROM milestone""") for value in m: c.execute("""INSERT INTO milestone (name) VALUES (%s)""", value) self.db().c... |
if status.lower() == 'open': if owner != '': status = 'assigned' else: status = 'new' | def addTicket(self, time, changetime, component, severity, priority, owner, reporter, cc, version, milestone, status, resolution, summary, description, keywords): c = self.db().cursor() if status.lower() == 'open': if owner != '': status = 'assigned' else: status = 'new' | |
time, changetime, component, | time.strftime('%s'), changetime.strftime('%s'), component, | def addTicket(self, time, changetime, component, severity, priority, owner, reporter, cc, version, milestone, status, resolution, summary, description, keywords): c = self.db().cursor() if status.lower() == 'open': if owner != '': status = 'assigned' else: status = 'new' |
def main(): import optparse p = optparse.OptionParser('usage: %prog xml_export.xml /path/to/trac/environment') opt, args = p.parse_args() if len(args) != 2: p.error("Incorrect number of arguments") try: importData(open(args[0]), args[1]) except Exception, e: print 'Error:', e def importData(f, env): project = Exporte... | class TheBugzillaConverter: def __init__(self, _db, _host, _user, _password, _env, _force): try: print "Bugzilla MySQL('%s':'%s':'%s':'%s'): connecting..." % (_db, _host, _user, _password) self.mysql_con = MySQLdb.connect(host=_host, user=_user, passwd=_password, db=_db, compress=1, cursorclass=MySQLdb.cursors.DictCu... | def addTicketChange(self, ticket, time, author, field, oldvalue, newvalue): c = self.db().cursor() c.execute("""INSERT INTO ticket_change (ticket, time, author, field, oldvalue, newvalue) VALUES (%s, %s, %s, %s, %s, %s)""", ticket, time.strftime('%s'), author, field, oldvalue, newvalue) self.db().commit() |
c.execute("INSERT INTO version (name) VALUES (%s)", (vers[key],)) | c.execute("INSERT INTO version (name) VALUES (%s)", (vers[key].encode('utf-8'),)) | def setVersionList(self, v, key): """Remove all versions, set them to `v`""" self.assertNoTickets() c = self.db().cursor() c.execute("DELETE FROM version") for vers in v: print " inserting version '%s'" % (vers[key]) c.execute("INSERT INTO version (name) VALUES (%s)", (vers[key],)) self.db().commit() |
(name, due, completed, description) | (name, due, completed, description)) | def create_milestone(self, req, name, due=0, completed=0, description=''): self.perm.assert_permission(perm.MILESTONE_CREATE) if not name: raise TracError('You must provide a name for the milestone.', 'Required Field Missing') cursor = self.db.cursor() self.log.debug("Creating new milestone '%s'" % name) cursor.execute... |
missing = False | missing = 0 | def trac_get_reference(env, rawtext, text): for (pattern, function) in LINKS: m = pattern.match(text) if m: g = filter(None, m.groups()) missing = False if pattern == WIKI_LINK: if not (env._wiki_pages.has_key(g[0])): missing = True text = text + "?" uri = function(env.href, g) reference = nodes.reference(rawtext, text... |
missing = True | missing = 1 | def trac_get_reference(env, rawtext, text): for (pattern, function) in LINKS: m = pattern.match(text) if m: g = filter(None, m.groups()) missing = False if pattern == WIKI_LINK: if not (env._wiki_pages.has_key(g[0])): missing = True text = text + "?" uri = function(env.href, g) reference = nodes.reference(rawtext, text... |
self.req = Mock(hdf=HDFWrapper(['./templates']), base_path='/trac.cgi', path_info='', | self.req = Mock(base_path='/trac.cgi', path_info='', | def setUp(self): self.env = EnvironmentStub() self.ticket_module = TicketModule(self.env) self.mimeview = Mimeview(self.env) self.req = Mock(hdf=HDFWrapper(['./templates']), base_path='/trac.cgi', path_info='', href=Href('/trac.cgi'), abs_href=Href('http://example.org/trac.cgi'), environ={}, perm=None, authname='-', ar... |
<generator>Trac 0.11dev-genshi</generator> | <generator>Trac 0.11dev</generator> | def test_rss_conversion(self): ticket = self._create_a_ticket() content, mimetype, ext = self.mimeview.convert_content( self.req, 'trac.ticket.Ticket', ticket, 'rss') self.assertEqual(("""<rss version="2.0"> |
for (tkt_id,) in cursor: | tkt_ids = [int(row[0]) for row in cursor] for tkt_id in tkt_ids: | def delete(self, retarget_to=None, author=None, db=None): if not db: db = self.env.get_db_cnx() handle_ta = True else: handle_ta = False |
req.write(sep.join([str(result[col]).replace(sep, '_') .replace('\n', ' ') .replace('\r', ' ') | req.write(sep.join([unicode(result[col]).replace(sep, '_') .replace('\n', ' ') .replace('\r', ' ') | def display_csv(self, req, query, sep=','): req.send_response(200) req.send_header('Content-Type', 'text/plain;charset=utf-8') req.end_headers() |
return 'CAST(%s AS %s)' % (column, type) | if sqlite_version >= 30203: return 'CAST(%s AS %s)' % (column, type) elif type == 'int': return '1*' + column else: return column | def cast(self, column, type): return 'CAST(%s AS %s)' % (column, type) |
test_out = ''' <ul><li>Foo</li> <ul><li>Foo 2</li> </ul></ul><ol><li>Foo 3</li> </ol><h3>FooBar</h3> <ul> Hoj Hoj2 </ul><p>Hoj3 </p>''' | test_out = ''' <ul><li>Foo</li> <ul><li>Foo 2</li> </ul></ul><ol><li>Foo 3</li> </ol><h3>FooBar</h3> <ul> Hoj Hoj2 </ul><p>Hoj3 Line1<br />Line2 </p>''' | def render(self): name = dict_get_with_default(self.args, 'page', 'WikiStart') action = dict_get_with_default(self.args, 'action', 'view') version = dict_get_with_default(self.args, 'version', 0) page = Page(name, version) |
class Pool(str): | class Pool(object): | def history_cb(path, rev, pool): if authz.has_permission(path): history.append((path, rev)) |
Subversion's bindings use specially formatted strings to refer to objects, so by subclassing `str` we allow instances to be used directly in place of regular pools. | Instances of this type return their associated `pool when called. | def history_cb(path, rev, pool): if authz.has_permission(path): history.append((path, rev)) |
def __new__(klass, parent, parent_pool): | def __init__(self, parent, parent_pool): | def __new__(klass, parent, parent_pool): """ Create a new pool that is a sub-pool of `parent_pool`, and arrange for `self.close` to be called up when the `parent` object is destroyed. The `parent` object must be weak-referenceable. The returned `Pool` instance will have the value of the newly created pool. """ self =... |
self = str.__new__(klass, core.svn_pool_create(parent_pool)) | self.pool = core.svn_pool_create(parent_pool) | def __new__(klass, parent, parent_pool): """ Create a new pool that is a sub-pool of `parent_pool`, and arrange for `self.close` to be called up when the `parent` object is destroyed. The `parent` object must be weak-referenceable. The returned `Pool` instance will have the value of the newly created pool. """ self =... |
core.svn_pool_destroy(self) | core.svn_pool_destroy(self.pool) | def close(self, x): """ The parent object has been destroyed so it is time for us to go. -- So long, and thanks for all the fish! """ core.svn_pool_destroy(self) |
pool = property(lambda self: self._pool(), lambda self, pool: setattr(self, '_pool', pool)) | def close(self, x): """ The parent object has been destroyed so it is time for us to go. -- So long, and thanks for all the fish! """ core.svn_pool_destroy(self) | |
pool = property(lambda self: self._pool(), lambda self, pool: setattr(self, '_pool', pool)) | def get_youngest_rev_in_cache(self, db): """ Get the latest stored revision by sorting the revision strings numerically """ cursor = db.cursor() cursor.execute("SELECT rev FROM revision ORDER BY -LENGTH(rev), rev DESC LIMIT 1") row = cursor.fetchone() return row and row[0] or None | |
pool = property(lambda self: self._pool(), lambda self, pool: setattr(self, '_pool', pool)) | def _get_prop(self, name): return fs.node_prop(self.root, self.scope + self.path, name, self.pool) | |
_to_svn(self.scope, old_path), '', | _to_svn(self.scope + old_path), '', | def authz_cb(root, path, pool): return 1 |
self.file = StringIO.StringIO(data) | self.file = StringIO.StringIO(data.tostring()) | def __init__(self, name, data): self.filename = name self.file = StringIO.StringIO(data) |
print "inserting component ", comp[key] c.execute("""INSERT INTO component (name) VALUES (%s)""", comp[key].encode('utf-8')) | print "inserting component '",comp[key],"', owner", comp['owner'] c.execute("""INSERT INTO component (name, owner) VALUES (%s, %s)""", comp[key].encode('utf-8'), comp['owner'].encode('utf-8')) | def setComponentList(self, l, key): """Remove all components, set them to `l`""" self.assertNoTickets() c = self.db().cursor() c.execute("""DELETE FROM component""") for comp in l: print "inserting component ", comp[key] c.execute("""INSERT INTO component (name) VALUES (%s)""", comp[key].encode('utf-8')) self.db().com... |
self.env.create_attachment(self.db(), 'ticket', str(id), attachment, description, | attachment.filename = attachment.filename.encode('utf-8') self.env.create_attachment(self.db(), 'ticket', str(id), attachment, description.encode('utf-8'), | def addAttachment(self, id, attachment, description, author): print 'inserting attachment for ticket %s -- %s' % (id, description) self.env.create_attachment(self.db(), 'ticket', str(id), attachment, description, author, 'unknown') |
sql = "SELECT DISTINCTROW value FROM components" | sql = "SELECT value, initialowner AS owner FROM components" | def convert(_db, _host, _user, _password, _env, _force): activityFields = FieldTranslator() # account for older versions of bugzilla if BZ_VERSION == '2.11': print 'Using Buzvilla v%s schema.' % BZ_VERSION activityFields['removed'] = 'oldvalue' activityFields['added'] = 'newvalue' # init Bugzilla environment print "B... |
trac.addTicketChange(ticket=bugid, time=activity['bug_when'], author=trac.getLoginName(mysql_cur, activity['who']), field='keywords', oldvalue=oldKeywords, newvalue=newKeywords) | ticketChangeKw = ticketChange ticketChangeKw['field'] = 'keywords' ticketChangeKw['oldvalue'] = oldKeywords ticketChangeKw['newvalue'] = newKeywords ticketChanges.append(ticketChangeKw) | def convert(_db, _host, _user, _password, _env, _force): activityFields = FieldTranslator() # account for older versions of bugzilla if BZ_VERSION == '2.11': print 'Using Buzvilla v%s schema.' % BZ_VERSION activityFields['removed'] = 'oldvalue' activityFields['added'] = 'newvalue' # init Bugzilla environment print "B... |
trac.addTicketChange(ticket=bugid, time=activity['bug_when'], author=trac.getLoginName(mysql_cur, activity['who']), field=field_name, oldvalue=removed, newvalue=added) | for oldChange in ticketChanges: if (field_name == 'summary' and oldChange['field'] == ticketChange['field'] and oldChange['time'] == ticketChange['time'] and oldChange['author'] == ticketChange['author']): oldChange['oldvalue'] += " " + ticketChange['oldvalue'] oldChange['newvalue'] += " " + ticketChange['newvalue'] br... | def convert(_db, _host, _user, _password, _env, _force): activityFields = FieldTranslator() # account for older versions of bugzilla if BZ_VERSION == '2.11': print 'Using Buzvilla v%s schema.' % BZ_VERSION activityFields['removed'] = 'oldvalue' activityFields['added'] = 'newvalue' # init Bugzilla environment print "B... |
req.hdf['search.q'] = req.args.get('q').replace('"', "& | req.hdf['search.q'] = req.args.get('q') | def process_request(self, req): req.perm.assert_permission('SEARCH_VIEW') |
q=query, page=page + 1) | q=req.args.get('q'), page=page + 1) | def process_request(self, req): req.perm.assert_permission('SEARCH_VIEW') |
q=query, page=page - 1) | q=req.args.get('q'), page=page - 1) | def process_request(self, req): req.perm.assert_permission('SEARCH_VIEW') |
req.hdf['search.page_href'] = self.env.href.search(zip(filters, ['on'] * len(filters)), q=query) | req.hdf['search.page_href'] = self.env.href.search(zip(filters, ['on'] * len(filters)), q=req.args.get('q')) | def process_request(self, req): req.perm.assert_permission('SEARCH_VIEW') |
try: buf.write("<dd>%s</dd>" % wiki_to_html(description, self.env, req)) except Exception, e: import traceback print traceback.print_exc() | buf.write("<dd>%s</dd>" % wiki_to_html(description, self.env, req)) | def render_macro(self, req, name, content): from trac.wiki.formatter import wiki_to_html from trac.wiki import WikiSystem buf = StringIO() buf.write("<dl>") |
if line.startswith('Index: ') or line.startswith('======'): | if line.startswith('Index: ') or line.startswith('======') or line == '': | def htmlify(match): div, mod = divmod(len(match.group(0)), 2) return div * ' ' + mod * ' ' |
del req.chrome | try: del req.chrome except AttributeError: pass | def dispatch_request(environ, start_response): """Main entry point for the Trac web interface. @param environ: the WSGI environment dict @param start_response: the WSGI callback for starting the response """ if 'mod_python.options' in environ: options = environ['mod_python.options'] environ.setdefault('trac.env_path',... |
stamp = time.mktime(tt) tt = time.localtime(stamp) return tt.tm_isdst > 0 | try: stamp = time.mktime(tt) tt = time.localtime(stamp) return tt.tm_isdst > 0 except OverflowError: return False | def _isdst(self, dt): tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1) stamp = time.mktime(tt) tt = time.localtime(stamp) return tt.tm_isdst > 0 |
self.assertEqual('http://example.com/trac', req.base_url) | self.assertEqual('http://localhost/trac', req.base_url) | def test_base_url_proxy(self): environ = self._make_environ(HTTP_HOST='localhost', HTTP_X_FORWARDED_HOST='example.com') req = Request(environ, None) self.assertEqual('http://example.com/trac', req.base_url) |
self.projects[project] = env_path | if self.projects.has_key(project): print >>sys.stderr, 'Warning: Ignoring project "%s" since ' \ 'it conflicts with project "%s"' \ % (env_path, self.projects[project]) else: self.projects[project] = env_path | def __init__(self, server_address, env_parent_dir, env_paths, auths): HTTPServer.__init__(self, server_address, TracHTTPRequestHandler) |
self.site_parser.get(section, option) or None | self.site_parser.get(section, option) | def save(self): """Write the configuration options to the primary file.""" if not self.filename: return |
self.parser.get(section, option) or None if current is not None and current != default: | self.parser.get(section, option) if current != default: | def save(self): """Write the configuration options to the primary file.""" if not self.filename: return |
config.set(section, option, current) | config.set(section, option, current or '') | def save(self): """Write the configuration options to the primary file.""" if not self.filename: return |
tmp = s = '' while self._open_tags != [] and tag != tmp: tmp = self._open_tags.pop() s += tmp return s | tmp = '' for i in range(len(self._open_tags)-1, -1, -1): if self._open_tags[i] == tag: tmp += self._open_tags[i] del self._open_tags[i] break return tmp | def close_tag(self, tag): tmp = s = '' while self._open_tags != [] and tag != tmp: tmp = self._open_tags.pop() s += tmp return s |
text = "</p>%s<p>" % text | text = "</p>%s<p>" % unicode(text) | def process(self, req, text, in_paragraph=False): if self.error: return system_message(Markup('Error: Failed to load processor ' '<code>%s</code>', self.name), self.error) text = self.processor(req, text) if in_paragraph: content_for_span = None interrupt_paragraph = False if isinstance(text, Element): tagname = text.t... |
req.hdf['search.q'] = query | def perform_query(self, req, query, changeset, tickets, wiki, page=0): if not query: return ([], 0) keywords = query.split(' ') | |
for type, title, msg, author, keywords, data, t, version in cursor: | for type, title, msg, author, kw, data, t, version in cursor: | def perform_query(self, req, query, changeset, tickets, wiki, page=0): if not query: return ([], 0) keywords = query.split(' ') |
'keywords': keywords or '', | 'keywords': kw or '', | def perform_query(self, req, query, changeset, tickets, wiki, page=0): if not query: return ([], 0) keywords = query.split(' ') |
page_dict = {} | page_dict = {'TitleIndex': 1} | def populate_page_dict(): """Extract wiki page names. This is used to detect broken wiki-links""" global page_dict page_dict = {} cnx = get_connection() cursor = cnx.cursor() cursor.execute('SELECT DISTINCT name FROM wiki') while 1: row = cursor.fetchone() if not row: break page_dict[row[0]] = 1 |
r"""(?P<tickethref> | r(?P<tickethref> | def populate_page_dict(): """Extract wiki page names. This is used to detect broken wiki-links""" global page_dict page_dict = {} cnx = get_connection() cursor = cnx.cursor() cursor.execute('SELECT DISTINCT name FROM wiki') while 1: row = cursor.fetchone() if not row: break page_dict[row[0]] = 1 |
number = int(match[2:]) | number = int(match[1:]) | def _tickethref_formatter(self, match, fullmatch): number = int(match[2:]) return '<a href="%s">#%d</a>' % (href.ticket(number), number) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.