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


Python format函数代码示例

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


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

示例1: _formatPrivmsg

 def _formatPrivmsg(self, nick, network, msg):
     channel = msg.args[0]
     if self.registryValue('includeNetwork', channel):
         network = '@' + network
     else:
         network = ''
     # colorize nicks
     color = self.registryValue('color', channel) # Also used further down.
     if color:
         nick = ircutils.IrcString(nick)
         newnick = ircutils.mircColor(nick, *ircutils.canonicalColor(nick))
         colors = ircutils.canonicalColor(nick, shift=4)
         nick = newnick
     if ircmsgs.isAction(msg):
         if color:
             t = ircutils.mircColor('*', *colors)
         else:
             t = '*'
         s = format('%s %s%s %s', t, nick, network, ircmsgs.unAction(msg))
     else:
         if color:
             lt = ircutils.mircColor('<', *colors)
             gt = ircutils.mircColor('>', *colors)
         else:
             lt = '<'
             gt = '>'
         s = format('%s%s%s%s %s', lt, nick, network, gt, msg.args[1])
     return s
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:28,代码来源:plugin.py

示例2: ReadDateTime

   def ReadDateTime(self, DateTime):
# Initiate DS1302 communication.
      self.InitiateDS1302()
# Write address byte.
      self.WriteByte(int("10111111", 2))
# Read date and time data.
      Data = ""

      Byte = self.ReadByte()
      DateTime["Second"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10
      Byte = self.ReadByte()
      DateTime["Minute"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10
      Byte = self.ReadByte()
      DateTime["Hour"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10
      Byte = self.ReadByte()
      DateTime["Day"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10
      Byte = self.ReadByte()
      DateTime["Month"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10
      Byte = self.ReadByte()
      DateTime["DayOfWeek"] = (operator.mod(Byte, 16) + operator.div(Byte, 16) * 10) - 1
      Byte = self.ReadByte()
      DateTime["Year"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10

      Data = self.DOW[DateTime["DayOfWeek"]] + " " + format(DateTime["Year"] + 2000, "04d") + "-" + format(DateTime["Month"], "02d") + "-" + format(DateTime["Day"], "02d")
      Data += " " + format(DateTime["Hour"], "02d") + ":" + format(DateTime["Minute"], "02d") + ":" + format(DateTime["Second"], "02d")

# End DS1302 communication.
      self.EndDS1302()
      return Data
开发者ID:BirchJD,项目名称:RTC_DS1302,代码行数:29,代码来源:RTC_DS1302.py

示例3: add_plan

def add_plan(request, access_token):
	result = login_auth(access_token)
	if result['err']['code'] != 0:
		return HttpResponse(json.dumps(result))	
	userid = result['data']['id']
	try:
		new_plan = Plan()
		user = FBUser.objects.get(fbid=userid)
		new_plan.holder = user
		new_plan.title = request.POST.get('title', "testtitle")
		new_plan.destination = request.POST.get('destination', "testdestination")
		new_plan.description = request.POST.get('description', "testdescription")
		new_plan.depart_time = request.POST.get('depart_time', datetime.today())
		new_plan.length = request.POST.get('length', 2)
		new_plan.limit = request.POST.get('limit', 2)
		visible_type = request.POST.get('visible_type', 1)
		new_plan.visible_type = int(visible_type)
		friend_list = request.POST.getlist('friendlist',[])
		new_plan.full_clean()
		new_plan.save()
		if new_plan.visible_type == 3:
			for friendid in friend_list:
				friend = FBUser.objects.get(fbid=friendid)
				private = PrivatePlan()
				private.accessible_user = friend
				private.accessible_plan = new_plan
				private.full_clean()
				private.save()
		result = format(0, 'create success')
		return HttpResponse(json.dumps(result))	
	except Exception as e:
   		result = format(400, str(e))
        return HttpResponse(json.dumps(result))	
开发者ID:Staniel,项目名称:Travel-Together-Backend,代码行数:33,代码来源:plan_action.py

示例4: handle

    def handle(self):
        while True:
            try:
                data = self.request.recv(2*1024*1024)
                if not data:
                    break  #end
                data = json.loads(data)

                res = self.execute(data)
                
                logger.debug('instance count:' + str(len(self.rpc_instances.keys())))

                res = json.dumps(res) 
                res = str(len(res)).rjust(8, '0') + res 
                self.request.send(res)
            except socket.timeout as err:
                res = ('error in RequestHandler :%s, res:%s' % (traceback.format_exc(), data))
                logger.debug(res)
                res = json.dumps({'err':'sys.socket.error', 'msg':format(err)})
                res = str(len(res)).rjust(8, '0') + res 
                self.request.send(res)
                self.request.close()
                break
            except Exception as err:
                res = ('error in RequestHandler :%s, res:%s' % (traceback.format_exc(), data))
                logger.debug(res)
                res = json.dumps({'err':'sys.socket.error', 'msg': format(err)})
                res = str(len(res)).rjust(8, '0') + res 
                self.request.send(res)
开发者ID:akira-cn,项目名称:Kohana-python,代码行数:29,代码来源:server.py

示例5: disp_results

def disp_results(fig, ax1, ax2, loss_iterations, losses, accuracy_iterations, accuracies, accuracies_iteration_checkpoints_ind, fileName, color_ind=0):
    modula = len(plt.rcParams['axes.color_cycle'])
    acrIterations =[]
    top_acrs={}
    if accuracies.size:
        if 	accuracies.size>4:
		    top_n = 4
        else:
            top_n = accuracies.size -1		
        temp = np.argpartition(-accuracies, top_n)
        result_indexces = temp[:top_n]
        temp = np.partition(-accuracies, top_n)
        result = -temp[:top_n]
        for acr in result_indexces:
            acrIterations.append(accuracy_iterations[acr])
            top_acrs[str(accuracy_iterations[acr])]=str(accuracies[acr])

        sorted_top4 = sorted(top_acrs.items(), key=operator.itemgetter(1))
        maxAcc = np.amax(accuracies, axis=0)
        iterIndx = np.argmax(accuracies)
        maxAccIter = accuracy_iterations[iterIndx]
        maxIter =   accuracy_iterations[-1]
        consoleInfo = format('\n[%s]:maximum accuracy [from 0 to %s ] = [Iteration %s]: %s ' %(fileName,maxIter,maxAccIter ,maxAcc))
        plotTitle = format('max accuracy(%s) [Iteration %s]: %s ' % (fileName,maxAccIter, maxAcc))
        print (consoleInfo)
        #print (str(result))
        #print(acrIterations)
       # print 'Top 4 accuracies:'		
        print ('Top 4 accuracies:'+str(sorted_top4))		
        plt.title(plotTitle)
    ax1.plot(loss_iterations, losses, color=plt.rcParams['axes.color_cycle'][(color_ind * 2 + 0) % modula])
    ax2.plot(accuracy_iterations, accuracies, plt.rcParams['axes.color_cycle'][(color_ind * 2 + 1) % modula], label=str(fileName))
    ax2.plot(accuracy_iterations[accuracies_iteration_checkpoints_ind], accuracies[accuracies_iteration_checkpoints_ind], 'o', color=plt.rcParams['axes.color_cycle'][(color_ind * 2 + 1) % modula])
    plt.legend(loc='lower right') 
开发者ID:Coderx7,项目名称:caffe-windows-examples,代码行数:34,代码来源:plot.py

示例6: fromDate

    def fromDate(clazz, date):
        """
        date may be a datetime.datetime instance, a POSIX timestamp
        (integer value, such as returned by time.time()), or an RFC
        2068 Full Date (eg. "Mon, 23 May 2005 04:52:22 GMT") string.
        """
        def format(date):
            #
            # FIXME: strftime() is subject to localization nonsense; we need to
            # ensure that we're using the correct localization, or don't use
            # strftime().
            #
            return date.strftime("%a, %d %b %Y %H:%M:%S GMT")

        if type(date) is int:
            date = format(datetime.datetime.utcfromtimestamp(date))
        elif type(date) is str:
            pass
        elif type(date) is unicode:
            date = date.encode("utf-8")
        elif isinstance(date, datetime.datetime):
            if date.tzinfo:
                raise NotImplementedError("I need to normalize to UTC")
            date = format(date)
        else:
            raise ValueError("Unknown date type: %r" % (date,))

        return clazz(PCDATAElement(date))
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:28,代码来源:base.py

示例7: to_regexps

 def to_regexps(cls, use, possibles, have_add=False):
     '''
     Convert to regular expressions.
     
     `have_add` indicaes whether the caller can supply an "add".
     None - caller doesn't care what lower code needed.
     True - caller has add, and caller should need that.
     False - caller doesn't have add, and caller should not need it.
     '''
     regexps = []
     for possible in possibles:
         if isinstance(possible, RegexpContainer):
             cls.log.debug(format('unpacking: {0!s}', possible))
             if have_add is None or possible.add_reqd == have_add:
                 regexps.append(possible.regexp)
                 # this flag indicates that it's "worth" using the regexp
                 # so we "inherit"
                 use = use or possible.use
             else:
                 raise Unsuitable('Add inconsistent.')
         else:
             cls.log.debug(format('cannot unpack: {0!s}', 
                                  possible.__class__))
             raise Unsuitable('Not a container.')
     return (use, regexps)
开发者ID:alexmac,项目名称:ifdef-refactor,代码行数:25,代码来源:rewriters.py

示例8: channelstats

    def channelstats(self, irc, msg, args, channel):
        """[<channel>]

        Returns the statistics for <channel>.  <channel> is only necessary if
        the message isn't sent on the channel itself.
        """
        try:
            stats = self.db.getChannelStats(channel)
            curUsers = len(irc.state.channels[channel].users)
            s = format('On %s there %h been %i messages, containing %i '
                       'characters, %n, %n, and %n; '
                       '%i of those messages %s.  There have been '
                       '%n, %n, %n, %n, %n, and %n.  There %b currently %n '
                       'and the channel has peaked at %n.',
                       channel, stats.msgs, stats.msgs, stats.chars,
                       (stats.words, 'word'),
                       (stats.smileys, 'smiley'),
                       (stats.frowns, 'frown'),
                       stats.actions, stats.actions == 1 and 'was an ACTION'
                                                          or 'were ACTIONs',
                       (stats.joins, 'join'),
                       (stats.parts, 'part'),
                       (stats.quits, 'quit'),
                       (stats.kicks, 'kick'),
                       (stats.modes, 'mode', 'change'),
                       (stats.topics, 'topic', 'change'),
                       curUsers,
                       (curUsers, 'user'),
                       (stats.users, 'user'))
            irc.reply(s)
        except KeyError:
            irc.error(format('I\'ve never been on %s.', channel))
开发者ID:Elwell,项目名称:supybot,代码行数:32,代码来源:plugin.py

示例9: pairedt

def pairedt(pairs, numSamples):
    results = dict()
    t,v = pairs.items()
    diffs = [t[1][x] - v[1][x] for x in range(len(t[1]))]
    plotDiffs(diffs)
    sampleSize = int(len(diffs)/numSamples)
    indices = range(len(diffs))
    random.shuffle(indices)
    mean_diffs = []
    i = 0
    for sample in range(numSamples):
        total_diff = 0
        for x in range(sampleSize):
            index = indices[i]
            total_diff += diffs[index]
            i+=1
        sample_avg = total_diff/float(sampleSize)
        mean_diffs.append(sample_avg)

    #normality check
    nt = stats.normaltest(mean_diffs)
    results['normal_p'] =  format(round(nt[1],4))

    #ttest
    t_prob = stats.ttest_1samp(mean_diffs, 0)
    results['ttest_t'] =  format(round(t_prob[0],4))
    results['ttest_p'] =  format(round(t_prob[1],4))

    #other stats
    results['avg_diff'] =  format(round(np.mean(diffs),4))
    results['numSamples'] = numSamples
    results['sampleSize'] = sampleSize
    results['num_pairs'] = len(pairs['tor'])

    return results
开发者ID:jontonsoup,项目名称:airlinepricechecker,代码行数:35,代码来源:pairedt.py

示例10: test_LilyPondParser__spanners__PhrasingSlur_02

def test_LilyPondParser__spanners__PhrasingSlur_02():
    """
    Swapped start and stop.
    """

    maker = abjad.NoteMaker()
    target = abjad.Container(maker([0] * 4, [(1, 4)]))
    abjad.phrasing_slur(target[2:])
    abjad.phrasing_slur(target[:3])

    assert format(target) == abjad.String.normalize(
        r"""
        {
            c'4
            \(
            c'4
            c'4
            \)
            \(
            c'4
            \)
        }
        """
    )

    string = r"\relative c' { c \( c c \( \) c \) }"

    parser = abjad.parser.LilyPondParser()
    result = parser(string)
    assert format(target) == format(result) and target is not result
开发者ID:Abjad,项目名称:abjad,代码行数:30,代码来源:test_LilyPondParser__spanners__PhrasingSlur.py

示例11: test_LilyPondParser__spanners__PhrasingSlur_01

def test_LilyPondParser__spanners__PhrasingSlur_01():
    """
    Successful slurs, showing single leaf overlap.
    """

    maker = abjad.NoteMaker()
    target = abjad.Container(maker([0] * 4, [(1, 4)]))
    abjad.phrasing_slur(target[2:])
    abjad.phrasing_slur(target[:3])

    assert format(target) == abjad.String.normalize(
        r"""
        {
            c'4
            \(
            c'4
            c'4
            \)
            \(
            c'4
            \)
        }
        """
    )

    parser = abjad.parser.LilyPondParser()
    result = parser(format(target))
    assert format(target) == format(result) and target is not result
开发者ID:Abjad,项目名称:abjad,代码行数:28,代码来源:test_LilyPondParser__spanners__PhrasingSlur.py

示例12: test_lilypondparsertools_LilyPondParser__spanners__Hairpin_03

def test_lilypondparsertools_LilyPondParser__spanners__Hairpin_03():
    r'''Dynamics can terminate hairpins.
    '''

    target = Staff(scoretools.make_notes([0] * 3, [(1, 4)]))
    hairpin = Hairpin(descriptor='<')
    attach(hairpin, target[0:2])
    hairpin = Hairpin(descriptor='>')
    attach(hairpin, target[1:])
    dynamic = Dynamic('p')
    attach(dynamic, target[1])
    dynamic = Dynamic('f')
    attach(dynamic, target[-1])

    assert format(target) == stringtools.normalize(
        r'''
        \new Staff {
            c'4 \<
            c'4 \p \>
            c'4 \f
        }
        '''
        )

    string = r"\new Staff \relative c' { c \< c \p \> c \f }"
    parser = LilyPondParser()
    result = parser(string)
    assert format(target) == format(result) and target is not result
开发者ID:ajyoon,项目名称:abjad,代码行数:28,代码来源:test_lilypondparsertools_LilyPondParser__spanners__Hairpin.py

示例13: test_lilypondparsertools_LilyPondParser__spanners__Hairpin_01

def test_lilypondparsertools_LilyPondParser__spanners__Hairpin_01():

    target = Staff(scoretools.make_notes([0] * 5, [(1, 4)]))
    hairpin = Hairpin(descriptor='<')
    attach(hairpin, target[:3])
    hairpin = Hairpin(descriptor='>')
    attach(hairpin, target[2:])
    dynamic = Dynamic('ppp')
    attach(dynamic, target[-1])

    assert format(target) == stringtools.normalize(
        r'''
        \new Staff {
            c'4 \<
            c'4
            c'4 \! \>
            c'4
            c'4 \ppp
        }
        '''
        )

    parser = LilyPondParser()
    result = parser(format(target))
    assert format(target) == format(result) and target is not result
开发者ID:ajyoon,项目名称:abjad,代码行数:25,代码来源:test_lilypondparsertools_LilyPondParser__spanners__Hairpin.py

示例14: test_lilypondparsertools_LilyPondParser__spanners__Hairpin_02

def test_lilypondparsertools_LilyPondParser__spanners__Hairpin_02():

    target = Container(scoretools.make_notes([0] * 4, [(1, 4)]))
    hairpin = Hairpin(descriptor='<')
    attach(hairpin, target[0:2])
    hairpin = Hairpin(descriptor='<')
    attach(hairpin, target[1:3])
    hairpin = Hairpin(descriptor='<')
    attach(hairpin, target[2:])

    assert format(target) == stringtools.normalize(
        r'''
        {
            c'4 \<
            c'4 \! \<
            c'4 \! \<
            c'4 \!
        }
        '''
        )

    string = r'''\relative c' { c \< c \< c \< c \! }'''
    parser = LilyPondParser()
    result = parser(string)
    assert format(target) == format(result) and target is not result
开发者ID:ajyoon,项目名称:abjad,代码行数:25,代码来源:test_lilypondparsertools_LilyPondParser__spanners__Hairpin.py

示例15: StepSizeFromExplore

    def StepSizeFromExplore(self, FileList, StablePerc):
        """         """

        step = {}
        for fileName in FileList:
            data = tmcmc.iopostmcmc.readMCMC(fileName)
            if data['acr'][-1] > 0.44-StablePerc \
                and data['acr'][-1] < 0.44+StablePerc:
                for par in data.keys():
                    if not tmcmc.iopostmcmc.isNonParam(par):
                        medfrac = np.median(data['frac'][-1000:])
                        print par+' has stabilized, acr = '+format(data['acr'][-1],'.2f')+\
                              ' frac = '+str(medfrac)+' | '+self.name+', '+self.case
                        step[par] = {'frac':medfrac}
            else:
                for par in data.keys():
                    if not tmcmc.iopostmcmc.isNonParam(par):
                        print par+' has NOT stabilized, acr = '+format(data['acr'][-1],'.2f')+\
                              ' | '+self.name+', '+self.case

        for par in step.keys():
            for key in self.ModelParams.keys():
                if key == par:
                    self.ModelParams[par]['step'] = self.ModelParams[par]['step']*step[par]['frac']
                    self.ModelParams[par]['open'] = True
开发者ID:pkundurthy,项目名称:tmcmc,代码行数:25,代码来源:class_fitprep.py


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