• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utils.parse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: cutActivity

def cutActivity(row):
    fromdate = utils.parse(row[2])
    todate = utils.parse(row[3])
    # print fromdate, todate
    if (todate.date() - fromdate.date()).days != 1:
        print "error cutting activity: wrong date range"
        return [0, 0]
    else:
        middate = copy.deepcopy(todate).replace(hour=0, minute=0, second=0)
        firsthalf = [row[0], utils.deltatohours(middate - fromdate), fromdate.isoformat(' '), middate.isoformat(' ')]
        secondhalf = [row[0], utils.deltatohours(todate - middate), middate.isoformat(' '), todate.isoformat(' ')]
        # print firsthalf, secondhalf
        return [firsthalf, secondhalf]
开发者ID:ilcn,项目名称:time_analysis,代码行数:13,代码来源:analyze.py


示例2: join

 def join(self, layer_attr, data_table, data_attr, prefix=''):
     """
     Joins a data table to this feature collection.
     """
     # Build first a dictionary for the layer attribute
     idx = {}
     for feat in self.features:
         idx[parse(feat['properties'][layer_attr])] = feat
     # Now go through the data table and retrieve all data one by one
     for d in data_table:
         feat = idx.get(parse(d[data_attr]), None)
         if feat is None: continue
         for k in d:
             feat['properties'][prefix+k] = parse(d[k])
开发者ID:christiankaiser,项目名称:themavis,代码行数:14,代码来源:layer.py


示例3: rewriteQuestion

	def rewriteQuestion(inputSentence, addWHword = False):
		utils = RewriterUtils()
		utils.parse(inputSentence)
		vbzIndex = QuestionRewriter.getTheIndexOfVBZ(utils.wordList, utils.posMap)
		if vbzIndex == -1:
			raise Exception("No VBZ found!")

		rewrittenQuestion = [] 
		for i in xrange(vbzIndex + 1, len(utils.wordList)):
			rewriteQuestion.append(util.wordList[i])
		if addWHword:
			rewrittenQuestion.append(utils.wordList[vbzIndex])
		for i in xrange(0, vbzIndex):
			rewrittenQuestion.append(utils.wordList[i])
		return rewrittenQuestion
开发者ID:cuijiaxing,项目名称:nlp,代码行数:15,代码来源:question_rewriter.py


示例4: main

def main():
    usage = "usage: follow.py <search>"
    opts = utils.parse(sys.argv[1:], {}, ".splunkrc", usage=usage)

    if len(opts.args) != 1:
        utils.error("Search expression required", 2)
    search = opts.args[0]

    service = client.connect(**opts.kwargs)

    job = service.jobs.create(search, earliest_time="rt", latest_time="rt", search_mode="realtime")

    # Wait for the job to transition out of QUEUED and PARSING so that
    # we can if its a transforming search, or not.
    while True:
        job.refresh()
        if job["dispatchState"] not in ["QUEUED", "PARSING"]:
            break
        time.sleep(2)  # Wait

    if job["reportSearch"] is not None:  # Is it a transforming search?
        count = lambda: int(job["numPreviews"])
        items = lambda _: job.preview()
    else:
        count = lambda: int(job["eventCount"])
        items = lambda offset: job.events(offset=offset)

    try:
        follow(job, count, items)
    except KeyboardInterrupt:
        print "\nInterrupted."
    finally:
        job.cancel()
开发者ID:rsommer,项目名称:splunk-sdk-python,代码行数:33,代码来源:follow.py


示例5: main

def main(argv):
    weeks = []
    sessions = []

    with open('weeks.csv', newline='') as csvfile:
        weeksreader = reader(csvfile, quotechar='"')
        weeks = make_weeks(weeksreader)

    with open('tt.csv', newline='') as csvfile:
        ttreader = reader(csvfile, quotechar='"')
        errors = []
        sessions = parse(ttreader, config.MODULES, weeks, errors)
        for i, error in enumerate(errors):
            if i == len(error) - 1:
                print(error[0] + '\n' + error[1])
            else:
                print(error[0] + '\n' + error[1] + '\n')

    calendar = []
    calendar.append(['Subject', 'Start Date', 'End Date',
                    'Start Time', 'End Time', 'Location'])
    for session in sessions:
        calendar.append([
            session.title + '-' + session.kind,
            session.start.strftime('%Y/%m/%d'),
            session.end.strftime('%Y/%m/%d'),
            session.start.strftime('%H:%M'),
            session.end.strftime('%H:%M'),
            session.location
        ])

    with open('parsed.csv', 'w', newline='') as csvfile:
        csvwriter = writer(csvfile, delimiter=',', quotechar='"',
                           quoting=QUOTE_MINIMAL)
        csvwriter.writerows(calendar)
开发者ID:maxf130,项目名称:timetable_parser,代码行数:35,代码来源:tt-parse.py


示例6: main

def main():
    """ main entry """
    options = parse(sys.argv[1:], CLIRULES, ".splunkrc")

    if options.kwargs['omode'] not in OUTPUT_MODES:
        print "output mode must be one of %s, found %s" % (OUTPUT_MODES,
              options.kwargs['omode'])
        sys.exit(1)

    service = connect(**options.kwargs)

    if path.exists(options.kwargs['output']):
        if options.kwargs['recover'] == False:
            error("Export file exists, and recover option nor specified")
        else:
            options.kwargs['end'] = recover(options)
            options.kwargs['fixtail'] = True
            openmode = "a"
    else:
        openmode = "w"
        options.kwargs['fixtail'] = False
        
    try:
        options.kwargs['fd'] = open(options.kwargs['output'], openmode)
    except IOError:
        print "Failed to open output file %s w/ mode %s" % \
                             (options.kwargs['output'], openmode)
        sys.exit(1)

    export(options, service)
开发者ID:chiehwen,项目名称:splunk-sdk-python,代码行数:30,代码来源:export.py


示例7: main

def main():
    usage = "usage: %prog <search>"
    opts = utils.parse(sys.argv[:], {}, ".splunkrc", usage=usage)
    
    service = connect(**opts.kwargs)

    try:
        result = service.get(
            "search/jobs/export",
            search="search instantaneous_eps",
            index="_internal",
            earliest_time="rt", 
            latest_time="rt", 
            search_mode="realtime")

        for result in ResultsReader(result.body):
            
            if result is not None:
                if isinstance(result, dict):
        
                        # extract only the event contents
                        event=result.items()[2][1]
                        # strip out the leading timestamp files, they don't read well
                        shorte=event[61:]
                        # send the shortened event contents to the speech synth
                        subprocess.call(["/usr/bin/say", shorte])
                        
    except KeyboardInterrupt:
        print "\nInterrupted."
开发者ID:DoubleDensity,项目名称:splunk-speak,代码行数:29,代码来源:epsmon.py


示例8: test_sample_1

    def test_sample_1(self):
        graph = parse('sample-1.txt')

        result = karger(graph)
        ans = 2

        self.assertEqual(ans, result)
开发者ID:SHLo,项目名称:algorithms,代码行数:7,代码来源:test.py


示例9: main

def main(argv):
    usage = "usage: %prog [options]"

    redirect_port_args = {
        "redirectport": {
            "flags": ["--redirectport"],
            "default": PORT,
            "help": "Port to use for redirect server (default: %s)" % PORT,
        },
    }

    opts = utils.parse(argv, redirect_port_args, ".splunkrc", usage=usage)

    args = [("scheme", opts.kwargs["scheme"]),
            ("host", opts.kwargs["host"]),
            ("port", opts.kwargs["port"]),
            ("redirecthost", "localhost"),
            ("redirectport", opts.kwargs["redirectport"]),
            ("username", opts.kwargs["username"]),
            ("password", opts.kwargs["password"])]
    if 'app' in opts.kwargs.keys():
        args.append(('app', opts.kwargs['app']))
    if 'owner' in opts.kwargs.keys():
        args.append(('owner', opts.kwargs['owner']))

    # Encode these arguments
    args = urllib.urlencode(args)

    # Launch the browser
    webbrowser.open("file://%s" % os.path.join(os.getcwd(), "explorer.html?%s" % args))

    # And server the files
    server.serve(opts.kwargs["redirectport"])
开发者ID:Anlim,项目名称:splunk-sdk-python,代码行数:33,代码来源:explorer.py


示例10: main

def main():
    usage = ""

    argv = sys.argv[1:]

    splunk_opts = utils.parse(argv, {}, ".splunkrc", usage=usage)
    tracker = AnalyticsTracker("cli_app", splunk_opts.kwargs)
开发者ID:Anlim,项目名称:splunk-sdk-python,代码行数:7,代码来源:input.py


示例11: test_10

    def test_10(self):
        ans = -8448

        nums = parse('test10.txt')
        result = median_maintenance(nums)

        self.assertEqual(ans, result)
开发者ID:SHLo,项目名称:algorithms,代码行数:7,代码来源:test.py


示例12: main

def main(argv):
    usage = "usage: %prog [options]"
    opts = parse(argv, {}, ".splunkrc", usage=usage)
    service = client.connect(**opts.kwargs)

    for logger in service.loggers:
        print "%s (%s)" % (logger.name, logger['level'])
开发者ID:archankr,项目名称:splunk-sdk-python,代码行数:7,代码来源:loggers.py


示例13: main

def main():
    """Main program."""

    usage = "usage: %prog [options] <command> [<args>]"

    argv = sys.argv[1:]

    command = None
    commands = ['create', 'delete', 'list']

    # parse args, connect and setup 
    opts = parse(argv, {}, ".splunkrc", usage=usage)
    service = connect(**opts.kwargs)
    program = Program(service)

    if len(opts.args) == 0:
        # no args means list
        command = "list"
    elif opts.args[0] in commands:
        # args and the first in our list of commands, extract 
        # command and remove from regular args
        command = opts.args[0]
        opts.args.remove(command)
    else:
        # first one not in our list, default to list
        command = "list"

    program.run(command, opts)
开发者ID:apanda,项目名称:splunk-sdk-python,代码行数:28,代码来源:conf.py


示例14: setUpClass

    def setUpClass(cls):
        cls.opts = parse([], {}, ".splunkrc")

        # Before we start, make sure splunk doesn't need a restart.
        service = client.connect(**cls.opts.kwargs)
        if service.restart_required:
            service.restart(timeout=120)
开发者ID:Jaykul,项目名称:splunk-sdk-python,代码行数:7,代码来源:testlib.py


示例15: main

def main():
    usage = ""

    argv = sys.argv[1:]

    opts = utils.parse(argv, {}, ".splunkrc", usage=usage)
    retriever = AnalyticsRetriever(opts.args[0], opts.kwargs)    
开发者ID:larrys,项目名称:splunk-sdk-python,代码行数:7,代码来源:output.py


示例16: main

def main(argv):
    usage = "usage: %prog [options]"

    redirect_port_args = {
        "redirectport": {
            "flags": ["--redirectport"],
            "default": PORT,
            "help": "Port to use for redirect server (default: %s)" % PORT,
        },
    }

    opts = utils.parse(argv, redirect_port_args, ".splunkrc", usage=usage)

    # We have to provide a sensible value for namespace
    namespace = opts.kwargs["namespace"]
    namespace = namespace if namespace else "-"

    # Encode these arguments
    args = urllib.urlencode([
            ("scheme", opts.kwargs["scheme"]),
            ("host", opts.kwargs["host"]),
            ("port", opts.kwargs["port"]),
            ("redirecthost", "localhost"),
            ("redirectport", opts.kwargs["redirectport"]),
            ("username", opts.kwargs["username"]),
            ("password", opts.kwargs["password"]),
            ("namespace", namespace)
        ]),

    # Launch the browser
    webbrowser.open("file://%s" % os.path.join(os.getcwd(), "explorer.html?%s" % args))

    # And server the files
    server.serve(opts.kwargs["redirectport"])
开发者ID:apanda,项目名称:splunk-sdk-python,代码行数:34,代码来源:explorer.py


示例17: main

def main():
    usage = "usage: %prog <search>"
    opts = utils.parse(sys.argv[1:], {}, ".splunkrc", usage=usage)

    if len(opts.args) != 1:
        utils.error("Search expression required", 2)
    search = opts.args[0]

    service = connect(**opts.kwargs)

    try:
        result = service.get(
            "search/jobs/export",
            search=search,
            earliest_time="rt", 
            latest_time="rt", 
            search_mode="realtime")

        reader = results.ResultsReader(result.body)
        while True:
            kind = reader.read()
            if kind == None: break
            if kind == results.RESULT:
                event = reader.value
                pprint(event)

    except KeyboardInterrupt:
        print "\nInterrupted."
开发者ID:apanda,项目名称:splunk-sdk-python,代码行数:28,代码来源:stail.py


示例18: main

def main(argv):
    opts = parse(argv, {}, ".splunkrc")
    context = connect(**opts.kwargs)
    service = Service(context)
    assert service.apps().status == 200
    assert service.indexes().status == 200
    assert service.info().status == 200
    assert service.settings().status == 200
    assert service.search("search 404").status == 200
开发者ID:kalpsfeb28,项目名称:splunk-sdk-python,代码行数:9,代码来源:binding1.py


示例19: test_parse

 def test_parse(self):
     for func_etalon, func_str in self.funcs:
         func = parse(func_str, "x, y, z")
         assert all((
             x == y for x, y in zip(
                 (func(x, y, z) for x, y, z in self.xs),
                 (func_etalon(x, y, z) for x, y, z in self.xs)
             )
         ))
开发者ID:FeodorM,项目名称:amm_code,代码行数:9,代码来源:test_utils.py


示例20: main

def main(argv):
    """ main entry """
    usage = 'usage: %prog --help for options'
    opts = utils.parse(argv, RULES, ".splunkrc", usage=usage)

    context = binding.connect(**opts.kwargs)
    operation = None

    # splunk.binding.debug = True # for verbose information (helpful for debugging)

    # Extract from command line and build into variable args
    kwargs = {}
    for key in RULES.keys():
        if opts.kwargs.has_key(key):
            if key == "operation":
                operation = opts.kwargs[key]
            else:
                kwargs[key] = urllib.quote(opts.kwargs[key])

    # no operation? if name present, default to list, otherwise list-all
    if not operation:
        if kwargs.has_key('name'):
            operation = 'list'
        else:
            operation = 'list-all'

    # pre-sanitize
    if (operation != "list" and operation != "create" 
                            and operation != "delete"
                            and operation != "list-all"):
        print "operation %s not one of list-all, list, create, delete" % operation
        sys.exit(0)

    if not kwargs.has_key('name') and operation != "list-all":
        print "operation requires a name"
        sys.exit(0)

    # remove arg 'name' from passing through to operation builder, except on create
    if operation != "create" and operation != "list-all":
        name = kwargs['name']
        kwargs.pop('name')

    # perform operation on saved search created with args from cli
    if operation == "list-all":
        result = context.get("saved/searches",  **kwargs)
    elif operation == "list":
        result = context.get("saved/searches/%s" % name, **kwargs)
    elif operation == "create":
        result = context.post("saved/searches", **kwargs)
    else:
        result = context.delete("saved/searches/%s" % name, **kwargs)
    print "HTTP STATUS: %d" % result.status
    xml_data = result.body.read()
    sys.stdout.write(xml_data)
开发者ID:huit,项目名称:splunk-sdk-python,代码行数:54,代码来源:saved_search.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.parseTable函数代码示例发布时间:2022-05-26
下一篇:
Python utils.para函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap