当前位置: 首页>>代码示例>>Python>>正文


Python api.parse_args函数代码示例

本文整理汇总了Python中trac.wiki.api.parse_args函数的典型用法代码示例。如果您正苦于以下问题:Python parse_args函数的具体用法?Python parse_args怎么用?Python parse_args使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了parse_args函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: expand_macro

    def expand_macro(self, formatter, name, content, args={}):
        "Produces XHTML code to display mindmaps"

        # Test if this is the long or short version of a macro call
        try:
          # Starting from Trac 0.12 the `args` argument should be set for long 
          # macros with arguments. However, it can be still empty and is not
          # used at all in 0.11.
          if not args:
            # Check for multi-line content, i.e. long macro form
            args, content = content.split("\n",1)
        except: # Short macro
          largs, kwargs = parse_args( content )
          if not largs:
            raise TracError("File name missing!")
          file = largs[0]
          url = extract_url (self.env, formatter.context, file, raw=True)
        else: # Long macro
          largs, kwargs = parse_args( args )
          digest = md5()
          digest.update(unicode(content).encode('utf-8'))
          hash = digest.hexdigest()
          if not self._check_cache(hash):
            mm = MindMap(content)
            self._set_cache(hash, mm)
          url = formatter.context.href.mindmap(hash + '.mm')
        return self.produce_html(formatter.context, url, kwargs)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:27,代码来源:macro.py

示例2: expand_macro

    def expand_macro(self, formatter, name, content):
        # Example: [[ASA(42)]]
        args, kw = parse_args(content)
        args = [arg.strip() for arg in args]
        if not args or not args[0].isdigit():
            raise TracError('Custom artifact id not specified')
        args, kw = parse_args(content)
        if not args or not args[0].isdigit():
            raise TracError('Custom artifact id not specified')
        artifact_id = int(args[0])
        dbp = DBPool(self.env, InstancePool())
        try:
            dbp.load_artifact(id=artifact_id)
        except ValueError:
            return system_message("Custom Artifact not found", "No custom artifact was found for id '{0}'.".format(artifact_id))
        artifact = dbp.pool.get_item(id=artifact_id)
        artifact_url = formatter.req.href.customartifacts('artifact/{0}'.format(artifact.get_id()))
        res = Core._get_resource(artifact) if not artifact in (Entity, Instance, None) and not type(artifact)==unicode else None
        spec_name, spec_url, values = _get_artifact_details(artifact, formatter.req)

        tpl='view_artifact_dialog.html'
        data = {
            'context': Context.from_request(formatter.req, res),
            'spec_name': spec_name,
            'spec_url': spec_url,
            'artifact': artifact,
            'artifact_url': artifact_url,
            'artifacts_values': values,
        }
        return Chrome(self.env).render_template(formatter.req, tpl, data, None, fragment=True)
开发者ID:filipefigcorreia,项目名称:TracAdaptiveSoftwareArtifacts,代码行数:30,代码来源:__init__.py

示例3: expand_macro

    def expand_macro(self, formatter, name, content):
        req = formatter.req
        args, kwargs = parse_args(content)
        args += [None, None]
        path, limit, rev = args[:3]
        limit = kwargs.pop('limit', limit)
        rev = kwargs.pop('rev', rev)

        if 'CHANGESET_VIEW' not in req.perm:
            return Markup('<i>Changelog not available</i>')

        repo = self.env.get_repository(req.authname)

        if rev is None:
            rev = repo.get_youngest_rev()
        rev = repo.normalize_rev(rev)
        path = repo.normalize_path(path)
        if limit is None:
            limit = 5
        else:
            limit = int(limit)
        node = repo.get_node(path, rev)
        out = StringIO()
        out.write('<div class="changelog">\n')
        for npath, nrev, nlog in node.get_history(limit):
            change = repo.get_changeset(nrev)
            datetime = format_datetime(change.date, '%Y/%m/%d %H:%M:%S', req.tz)
            out.write(wiki_to_html("'''[%s] by %s on %s'''\n\n%s" %
                (nrev, change.author, datetime, change.message),
                                   self.env, req));
        out.write('</div>\n')
        return out.getvalue()
开发者ID:lkraav,项目名称:trachacks,代码行数:32,代码来源:ChangeLogMacro.py

示例4: expand_macro

    def expand_macro(self, formatter, name, content):
        env = formatter.env
        req = formatter.req
        if not 'VOTE_VIEW' in req.perm:
            return
        # Simplify function calls.
        format_author = partial(Chrome(self.env).format_author, req)
        if not content:
            args = []
            compact = None
            kw = {}
            top = 5
        else:
            args, kw = parse_args(content)
            compact = 'compact' in args and True
            top = as_int(kw.get('top'), 5, min=0)

        if name == 'LastVoted':
            lst = tag.ul()
            for i in self.get_votes(req, top=top):
                resource = Resource(i[0], i[1])
                # Anotate who and when.
                voted = ('by %s at %s'
                         % (format_author(i[3]),
                            format_datetime(to_datetime(i[4]))))
                lst(tag.li(tag.a(
                    get_resource_description(env, resource, compact and
                                             'compact' or 'default'),
                    href=get_resource_url(env, resource, formatter.href),
                    title=(compact and '%+i %s' % (i[2], voted) or None)),
                    (not compact and Markup(' %s %s' % (tag.b('%+i' % i[2]),
                                                        voted)) or '')))
            return lst

        elif name == 'TopVoted':
            realm = kw.get('realm')
            lst = tag.ul()
            for i in self.get_top_voted(req, realm=realm, top=top):
                if 'up-only' in args and i[2] < 1:
                    break
                resource = Resource(i[0], i[1])
                lst(tag.li(tag.a(
                    get_resource_description(env, resource, compact and
                                             'compact' or 'default'),
                    href=get_resource_url(env, resource, formatter.href),
                    title=(compact and '%+i' % i[2] or None)),
                    (not compact and ' (%+i)' % i[2] or '')))
            return lst

        elif name == 'VoteList':
            lst = tag.ul()
            resource = resource_from_path(env, req.path_info)
            for i in self.get_votes(req, resource, top=top):
                vote = ('at %s' % format_datetime(to_datetime(i[4])))
                lst(tag.li(
                    compact and format_author(i[3]) or
                    Markup(u'%s by %s %s' % (tag.b('%+i' % i[2]),
                                             tag(format_author(i[3])), vote)),
                    title=(compact and '%+i %s' % (i[2], vote) or None)))
            return lst
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:60,代码来源:__init__.py

示例5: expand_macro

    def expand_macro(self, formatter, name, content, args):
        fdx = False
        start_with_scene = False
        end_with_scene = False
#        self.log.debug("EXPAND ARGUMENTS: %s " % args)
#        self.log.debug("EXPAND INITIAL CONTENT: %s" % content)
        req = formatter.req
        if content:
            args2,kw = parse_args(content)
#            self.log.debug("RENDER ARGUMENTS: %s " % args2)
#            self.log.debug("RENDER KW: %s " % kw)
            if 'fdx' in kw:
                fdx = self._parse_filespec(kw['fdx'].strip(), formatter.context, self.env)
            if 'start_with_scene' in kw:
                start_with_scene = int(kw['start_with_scene'])
            if 'end_with_scene' in kw:
                end_with_scene = int(kw['end_with_scene'])
            elif 'start_with_scene' in kw:
                end_with_scene = int(kw['start_with_scene']) + 1
                
        if args != {} and args != None and args['mode'] == "full":
            add_stylesheet(req, 'scrippets/css/scrippets-full.css')
            mode = "-full"
        elif kw != {} and fdx:
            add_stylesheet(req, 'scrippets/css/scrippets.css')
            mode = ""
            return self.render_fdx_subset(fdx,start_with_scene,end_with_scene,mode,formatter)
        else:
            add_stylesheet(req, 'scrippets/css/scrippets.css')
            mode = ""
            return self.render_inline_content(self.env, formatter.context, content,mode)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:31,代码来源:macro.py

示例6: expand_macro

 def expand_macro(self,formatter,name,args):
     anon_params,named_params = parse_args(args)
     if len(anon_params) <> 1:
         raise TracError('Error: mandatory param, you must provide a company name.')
     corp = anon_params[0];
     
     type = named_params.pop('type', 'noborder')
     
     if type == 'noborder':
         useborder = 'no'
         jsfunc = 'CompanyInsiderBox'
     elif type == 'popup':
         useborder = 'yes'
         jsfunc = 'CompanyInsiderPopup'
     elif type == 'border':
         useborder = 'yes'
         jsfunc = 'CompanyInsiderBox'
     else:
         raise TracError('Error: Type must be one from noborder, border or popup.')
     
     span_id = str(uuid.uuid4())
     
     res = ('<script ' +
         'src="http://www.linkedin.com/companyInsider?script&useBorder=' +
         useborder + '"' + 'type="text/javascript"></script>\n' +
         '<span id="' + span_id + '"></span>\n' +
         '<script type="text/javascript">\n' +
         'new LinkedIn.'+jsfunc+'("' + span_id + '","' + corp + '");\n'+
         '</script>')
     return res;
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:30,代码来源:macro.py

示例7: expand_macro

    def expand_macro(self, formatter, name, content):

        args, kw = parse_args(content)
        
        if not ('site' in kw and 'chapter' in kw):
            raise Exception("'site' and 'chapter' are required arguments")

        if not (re.match("^[a-zA-Z0-9-]+$",kw['site']) and re.match("^[a-zA-Z0-9-]+$",kw['site'])):
            raise Exception("'site' or 'chapter' setting contains invalid characters")

        template_dict = {'height': int(kw.get('height', 253)),
                         'width':  int(kw.get('width', 450)),
                         'SiteId': kw['site'],
                         'chapterId': kw['chapter'],
                         'scheme': formatter.req.scheme}
        template = """
<object id="%(SiteId)s" 
        name="MediahubVideoPlayer"  
        type="application/x-shockwave-flash" 
        data="%(scheme)s://players.mymediahub.com/MediaHubPlayer.swf" height="%(height)s" width="%(width)s">
<param name="movie" value="%(scheme)s://players.mymediahub.com/MediaHubPlayer.swf" />
<param name="allowFullScreen" value="true" />
<param name="allowScriptAccess" value="always" />
<param name="wmode" value="transparent" />
<param name="flashvars" value="ServiceUrl=%(scheme)s://sites.mymediahub.com/Services/&SiteId=%(SiteId)s" />
<a href="%(scheme)s://sites.mymediahub.com/Devices/Services/GetChapterVideo.ashx?chapterId=%(chapterId)s&siteId=%(SiteId)s">
<img border="0" alt="Video" src="%(scheme)s://sites.mymediahub.com/Devices/Services/GetEmbedPreviewStill.ashx?siteId=%(SiteId)s" 
     width="%(width)s" height="%(height)s" 
     class="MediahubPreviewStill" />
</a>
</object>
"""
        return template % template_dict
开发者ID:CGI-define-and-primeportal,项目名称:trac-plugin-miscmacros,代码行数:33,代码来源:MediahubPlayerMacro.py

示例8: expand_macro

    def expand_macro(self, formatter, name, content):
        req = formatter.req
        query_string = ""
        argv, kwargs = parse_args(content, strict=False)

        if "order" not in kwargs:
            kwargs["order"] = "id"
        if "max" not in kwargs:
            kwargs["max"] = "0"  # unlimited by default

        query_string = "&".join(["%s=%s" % item for item in kwargs.iteritems()])
        query = Query.from_string(self.env, query_string)

        tickets = query.execute(req)
        tickets = [t for t in tickets if "TICKET_VIEW" in req.perm("ticket", t["id"])]
        ticket_ids = [t["id"] for t in tickets]

        # locate the tickets
        geoticket = GeoTicket(self.env)
        locations = geoticket.locate_tickets(ticket_ids, req)

        if not locations:
            return tag.div(tag.b("MapTickets: "), "No locations found for ", tag.i(content))

        data = dict(locations=Markup(simplejson.dumps(locations)), query_href=query.get_href(req), query_string=content)

        # set an id for the map
        map_id = req.environ.setdefault("MapTicketsId", 0) + 1
        req.environ["MapTicketsId"] = map_id
        data["map_id"] = "tickets-map-%d" % map_id

        return Chrome(self.env).render_template(req, "map_tickets.html", data, None, fragment=True)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:query.py

示例9: expand_macro

    def expand_macro(self, formatter, name, content):
        from trac.mimeview.api import Mimeview
        mime_map = Mimeview(self.env).mime_map
        mime_type_filter = ''
        args, kw = parse_args(content)
        if args:
            mime_type_filter = args.pop(0).strip().rstrip('*')

        mime_types = {}
        for key, mime_type in mime_map.iteritems():
            if (not mime_type_filter or
                mime_type.startswith(mime_type_filter)) and key != mime_type:
                mime_types.setdefault(mime_type, []).append(key)

        return tag.div(class_='mimetypes')(
            tag.table(class_='wiki')(
                tag.thead(tag.tr(
                    tag.th(_("MIME Types")),  # always use plural
                    tag.th(tag.a("WikiProcessors",
                                 href=formatter.context.href.wiki(
                                     'WikiProcessors'))))),
                tag.tbody(
                    tag.tr(tag.th(tag.tt(mime_type),
                                  style="text-align: left"),
                           tag.td(tag.code(
                               ' '.join(sorted(mime_types[mime_type])))))
                    for mime_type in sorted(mime_types.keys()))))
开发者ID:exocad,项目名称:exotrac,代码行数:27,代码来源:macros.py

示例10: expand_macro

	def expand_macro(self, formatter, name, content):
		formatter.req.perm.assert_permission('TICKET_VIEW')

		self._seen_tickets = []
		options, kw = parse_args(content)
		if len(options) == 0:
			options = ['']

		# Generate graph header
#		result = "digraph G%s { rankdir = \"LR\"\n node [ style=filled ]\n" \
#				% (options[0])
		result = 'digraph G { rankdir = \"LR\"\n node [ style=filled ]\n'
		
		graphviz = Graphviz(self.env)

		if len(options) > 1 and options[1] is not '':
			self._maxdepth = int(options[1])

		if len(options) == 0 or (len(options) > 0 and options[0] == ''):
			result += self._depgraph_all(formatter.req)
		else:
			result += self._depgraph(formatter.req, options[0], 0)

		# Add footer
		result += "\n}"

		# Draw graph and return result to browser
		return graphviz.expand_macro(formatter, "graphviz", result)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:28,代码来源:depgraph.py

示例11: _parse_args

    def _parse_args(self, args, content):
        """
        Parse args from incoming args or from content. Depending on which is set.
        If called as a macro, the content holds the arguments. Otherwise it's
        the args param that holds the arguments.

        In macro case, a tuple is returned, first element is list of arguments,
        second is a dict. We only support the dict format.
        """
        env_name = ""
        count = 0
        title = "Latest announcements"

        if args is None:
            args = parse_args(content)
            if len(args) > 1:
                args = args[1]

        if args is not None and "project" in args:
            env_name = args["project"]
            env_name = env_name.strip("\" '")
            env_name = env_name.encode("utf-8")
            env_name = safe_string(env_name)

        if args is not None and "count" in args:
            count = args["count"]
            count = safe_int(count)

        if args is not None and "title" in args:
            title = args["title"]
            title = title.strip('"')

        self.log.debug("Returning args: {0}".format((env_name, count, title)))

        return env_name, count, title
开发者ID:nagyistoce,项目名称:trac-multiproject,代码行数:35,代码来源:announcements.py

示例12: expand_macro

    def expand_macro(self, formatter, name, content):

        args, kwargs = parse_args(content, strict=False)

        if len(args) > 1:
            raise TracError("Usage: [[BibNoCite(BibTexKey)]]")
        elif len(args) < 1:
            raise TracError("Usage: [[BibNoCite(BibTexKey)]]")

        key = args[0]

        cite = _getCited(formatter.req)
        auto = _getAuto(formatter.req)

        if key not in cite:
            found = False
            for source in _getLoaded(formatter.req):
                if key in source:
                    found = True
                    cite[key] = source[key]
                    break
            if not found:
                for a in auto:
                    if key in a:
                        cite[key] = a[key]
                        found = True
                        break
            if not found:
                raise TracError("Unknown key '" + key + "'")
        return
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:30,代码来源:tracbib.py

示例13: expand_macro

    def expand_macro(self, formatter, name, args):
        """Return a welcome heading with the project name extracted from trac.ini.

           + User-defined welcome string suffix and prefix.
           + Supports both standard and dictionary methods.
           + With defaults.
        """
        prefix = suffix = ''
        args, kw = parse_args(args)

        if args:
            prefix = args.pop(0).strip()
            if args: suffix = args.pop(0).strip()
        elif kw:
            if 'prefix' in kw: prefix = kw['prefix'].strip()
            if 'suffix' in kw: suffix = kw['suffix'].strip()

        default = {
            'prefix': 'Welcome to the',
            'suffix': 'Project'
        }
        if not prefix: prefix = default['prefix']
        if not suffix: suffix = default['suffix']

        return tag.h1('%s %s %s' % (prefix, self.env.project_name, suffix),
                      id='welcome')
开发者ID:dwclifton,项目名称:tracinigetmacro,代码行数:26,代码来源:macro.py

示例14: expand_macro

    def expand_macro(self, formatter, name, content):
        args, kw = parse_args(content)
        utc_dt = args and args[0] or None
        if not utc_dt:
            return system_message('IrcLogQuote: Timestamp required')
        d = self.date_re.match(utc_dt)
        if not d:
            return system_message('IrcLogQuote: Invalid timestamp format')
        offset = int(args and len(args)>1 and args[1] or 10)

        irclogs =  IrcLogsView(self.env)        
        logfile = irclogs._get_filename(d.group('year'),
                                        d.group('month'),
                                        d.group('day'))
        if (not os.path.isfile(logfile)):
            return system_message('IrcLogQuote: No log file for this date')
        iterable = irclogs._to_unicode(file(logfile))
        lines = irclogs._render_lines(iterable, formatter.req.tz)

        filtered_lines = [line for line in lines 
                                if unicode(line['utc_dt']) >= utc_dt
                                    and line['mode'] == 'channel'
                                    and line['hidden_user'] != 'hidden_user']
        
        add_stylesheet(formatter.req, 'irclogs/style.css')
        data = Chrome(self.env).populate_data(formatter.req, 
                                    {'lines':filtered_lines[:offset],
                                     'excerpt_date':d.groupdict(),
                                     'utc_dt':utc_dt})
        return Chrome(self.env).load_template('macro_quote.html') \
                                    .generate(**data)
开发者ID:fajran,项目名称:irclogs,代码行数:31,代码来源:macros.py

示例15: expand_macro

    def expand_macro(self, formatter, name, content):

        args, kwargs = parse_args(content, strict=False)

        if len(args) > 0 or len(kwargs) > 1:
            raise TracError(
                'Usage: [[BibFullRef]] or [[BibFullRef(auto=true|false)]]')

        showAuto = kwargs.get("auto", "false")
        if (showAuto != "false" and showAuto != "true"):
            raise TracError("Usage: [[BibFullRef(auto=true|false)]]")

        cite = getCited(formatter.req)
        auto = getAuto(formatter.req)

        for source in getLoaded(formatter.req):
            for key, value in source.iteritems():
                cite[key] = value
        if showAuto == "true":
            for key, value in auto.iteritems():
                cite[key] = value

        for format in self.formatter:
            div = format.format_fullref(cite, 'References')

        return div
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:26,代码来源:tracbib.py


注:本文中的trac.wiki.api.parse_args函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。