Python locale 模块,format() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用locale.format()

项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        return FalseoutputPoin

## ===================================================================================
## MAIN
项目:Cortex-Analyzers    作者:CERT-BDF    | 项目源码 | 文件源码
def rrset_to_text(m):
    s = StringIO()

    if 'bailiwick' in m:
        s.write(';;  bailiwick: %s\n' % m['bailiwick'])

    if 'count' in m:
        s.write(';;      count: %s\n' % locale.format('%d', m['count'], True))

    if 'time_first' in m:
        s.write(';; first seen: %s\n' % sec_to_text(m['time_first']))
    if 'time_last' in m:
        s.write(';;  last seen: %s\n' % sec_to_text(m['time_last']))

    if 'zone_time_first' in m:
        s.write(';; first seen in zone file: %s\n' % sec_to_text(m['zone_time_first']))
    if 'zone_time_last' in m:
        s.write(';;  last seen in zone file: %s\n' % sec_to_text(m['zone_time_last']))

    if 'rdata' in m:
        for rdata in m['rdata']:
            s.write('%s IN %s %s\n' % (m['rrname'], m['rrtype'], rdata))

    s.seek(0)
    return s.read()
项目:sampleRNN_ICLR2017    作者:soroushmehr    | 项目源码 | 文件源码
def plot_traing_info(x, ylist, path):
    """
    Loads log file and plot x and y values as provided by input.
    Saves as <path>/train_log.png
    """
    file_name = os.path.join(path, __train_log_file_name)
    try:
        with open(file_name, "rb") as f:
            log = pickle.load(f)
    except IOError:  # first time
        warnings.warn("There is no {} file here!!!".format(file_name))
        return
    plt.figure()
    x_vals = log[x]
    for y in ylist:
        y_vals = log[y]
        if len(y_vals) != len(x_vals):
            warning.warn("One of y's: {} does not have the same length as x:{}".format(y, x))
        plt.plot(x_vals, y_vals, label=y)
        # assert len(y_vals) == len(x_vals), "not the same len"
    plt.xlabel(x)
    plt.legend()
    #plt.show()
    plt.savefig(file_name[:-3]+'png', bbox_inches='tight')
    plt.close('all')
项目:Instagram-API    作者:danleyb2    | 项目源码 | 文件源码
def buildBody(self, bodies, boundary):
        body = ''
        for b in bodies:
            body += ('--' + boundary + "\r\n")
            body += ('Content-Disposition: ' + b['type'] + '; name="' + b['name'] + '"')
            if 'filename' in b:
                ext = os.path.splitext(b['filename'])[1][1:]
                body += ('; filename="' + 'pending_media_' + locale.format("%.*f", (
                    0, round(float('%.2f' % time.time()) * 1000)), grouping=False) + '.' + ext + '"')
            if 'headers' in b and isinstance(b['headers'], list):
                for header in b['headers']:
                    body += ("\r\n" + header)
            body += ("\r\n\r\n" + str(b['data']) + "\r\n")
        body += ('--' + boundary + '--')

        return body
项目:SGAN    作者:YuhangSong    | 项目源码 | 文件源码
def param(name, *args, **kwargs):
    """
    A wrapper for `tf.Variable` which enables parameter sharing in models.

    Creates and returns theano shared variables similarly to `tf.Variable`, 
    except if you try to create a param with the same name as a 
    previously-created one, `param(...)` will just return the old one instead of 
    making a new one.

    This constructor also adds a `param` attribute to the shared variables it 
    creates, so that you can easily search a graph for all params.
    """

    if name not in _params:
        kwargs['name'] = name
        param = tf.Variable(*args, **kwargs)
        param.param = True
        _params[name] = param
    result = _params[name]
    i = 0
    while result in _param_aliases:
        # print 'following alias {}: {} to {}'.format(i, result, _param_aliases[result])
        i += 1
        result = _param_aliases[result]
    return result
项目:learning-texas-holdem    作者:gjgregory    | 项目源码 | 文件源码
def _get_winner_message(self):
        """Helper function to generate a message at end of game."""
        if self.game.everyone_folded:
            message = self.game.winners[0].name + " wins $" \
                    + locale.format("%d", self.game.pot, grouping=True) + " for not folding!"
        else:
            if len(self.game.winners) == 1:
                message = self.game.winners[0].name + " wins $" \
                        + locale.format("%d", self.game.pot, grouping=True) + " with a "
            else:
                message = "Tie game! Both players win $" \
                        + locale.format("%d", self.game.pot/2, grouping=True) + " with an equal "
            win_type = self.game.winners[0].hand
            message += HandStrings[win_type] + "."
            if self.game.tiebreaker:
                card_rank = self.game.tiebreaker_value
                message += " (" + RankStrings[card_rank].upper() + " tiebreaker)"

        return message
项目:learning-texas-holdem    作者:gjgregory    | 项目源码 | 文件源码
def _cpu_move(self):
        """Performs a move by the AI."""
        #self.game.call(self.cpu)
        decision = random.randrange(4)
        if decision == 1 and self.game.lastraise == 0: #shouldn't call. check instead.
            decision = 0
        elif decision == 0 and self.cpu.bid < self.game.lastraise: #can't check. call instead.
            decision = 1
        if decision == 0:
            self.game.check(self.cpu)
            self._set_text(self.prompt, self.cpu.name + " checked.")
        elif decision == 1:
            self.game.call(self.cpu)
            self._set_text(self.prompt, self.cpu.name + " called.")
        elif decision >= 2:
            bid_amount = random.randrange(self.game.lastraise, self.game.lastraise*2+1)
            bid_amount += 50 - (bid_amount % 50)
            self.game.make_bid(self.cpu, bid_amount)
            self._set_text(self.prompt, self.cpu.name + " raised the bet to " \
                    + locale.format("%d", self.game.bid, grouping=True) + ".")

        self._update_display(False)
        if self.game.is_next(self.cpu) and not self.game.finished:
            self._cpu_move()
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        return FalseoutputPoin

## ===================================================================================
## MAIN
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        return FalseoutputPoin

## ===================================================================================
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        #PrintMsg("Unhandled exception in Number_Format function (" + str(num) + ")", 2)
        return "???"

## ===================================================================================
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
# Format a number according to locality and given places

    try:

        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)
        else:
            theNumber = locale.format("%.*f", (places, num), False)

        return theNumber

    except:
        errorMsg()
        return ""

## ===================================================================================
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        return False

## ====================================== Main Body ==================================
# Import modules
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        PrintMsg("Unhandled exception in Number_Format function (" + str(num) + ")", 2)
        return False

## ===================================================================================
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        return False

## ===================================================================================
## ====================================== Main Body ==================================
# Import modules
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        return False

## ===================================================================================
## ====================================== Main Body ==================================
# Import modules
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        return FalseoutputPoin

## ===================================================================================
项目:SSURGO-QA    作者:ncss-tech    | 项目源码 | 文件源码
def Number_Format(num, places=0, bCommas=True):
    try:
    # Format a number according to locality and given places
        #locale.setlocale(locale.LC_ALL, "")
        if bCommas:
            theNumber = locale.format("%.*f", (places, num), True)

        else:
            theNumber = locale.format("%.*f", (places, num), False)
        return theNumber

    except:
        errorMsg()
        return ""

## ===================================================================================
项目:wifi-mac-tracking    作者:rpp0    | 项目源码 | 文件源码
def __str__(self):
        result = ""
        if self._resolved:
            result += str(self._identifier)
            h = self.get_top_hash()
            hash_occurence = self.hash_occurences[h] / self.total_fingerprints
            result += " ["
            result += str(h) + " (" + "{0:.2f}".format(hash_occurence) + ")"
            result += "]"
        else:
            for h in self.hash_occurences:
                hash_occurence = self.hash_occurences[h] / self.total_fingerprints
                result += "* " + str(h) + " (" + "{0:.2f}".format(hash_occurence) + "),"
        result += " !"
        for h in self.hash_occurences_hamming:
            result += str(h)[0:HASH_PRINT_CUTOFF] + ", "
        result += "+[" + str(sorted(self.unstable_data)) + "]"
        return result


# Collection of MAC - fingerprint pairs in dictionary
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_float_to_string(self):
        def test(f, result):
            self.assertEqual(f.__format__('e'), result)
            self.assertEqual('%e' % f, result)

        # test all 2 digit exponents, both with __format__ and with
        #  '%' formatting
        for i in range(-99, 100):
            test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i))

        # test some 3 digit exponents
        self.assertEqual(1.5e100.__format__('e'), '1.500000e+100')
        self.assertEqual('%e' % 1.5e100, '1.500000e+100')

        self.assertEqual(1.5e101.__format__('e'), '1.500000e+101')
        self.assertEqual('%e' % 1.5e101, '1.500000e+101')

        self.assertEqual(1.5e-100.__format__('e'), '1.500000e-100')
        self.assertEqual('%e' % 1.5e-100, '1.500000e-100')

        self.assertEqual(1.5e-101.__format__('e'), '1.500000e-101')
        self.assertEqual('%e' % 1.5e-101, '1.500000e-101')

        self.assertEqual('%g' % 1.0, '1')
        self.assertEqual('%#g' % 1.0, '1.00000')
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_int__format__locale(self):
        # test locale support for __format__ code 'n' for integers

        x = 123456789012345678901234567890
        for i in range(0, 30):
            self.assertEqual(locale.format('%d', x, grouping=True), format(x, 'n'))

            # move to the next integer to test
            x = x // 10

        rfmt = ">20n"
        lfmt = "<20n"
        cfmt = "^20n"
        for x in (1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890, 12345678900):
            self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt)))
            self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt)))
            self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt)))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_format_spec_errors(self):
        # int, float, and string all share the same format spec
        # mini-language parser.

        # Check that we can't ask for too many digits. This is
        # probably a CPython specific test. It tries to put the width
        # into a C long.
        self.assertRaises(ValueError, format, 0, '1'*10000 + 'd')

        # Similar with the precision.
        self.assertRaises(ValueError, format, 0, '.' + '1'*10000 + 'd')

        # And may as well test both.
        self.assertRaises(ValueError, format, 0, '1'*1000 + '.' + '1'*10000 + 'd')

        # Make sure commas aren't allowed with various type codes
        for code in 'xXobns':
            self.assertRaises(ValueError, format, 0, ',' + code)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_float_to_string(self):
        def test(f, result):
            self.assertEqual(f.__format__('e'), result)
            self.assertEqual('%e' % f, result)

        # test all 2 digit exponents, both with __format__ and with
        #  '%' formatting
        for i in range(-99, 100):
            test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i))

        # test some 3 digit exponents
        self.assertEqual(1.5e100.__format__('e'), '1.500000e+100')
        self.assertEqual('%e' % 1.5e100, '1.500000e+100')

        self.assertEqual(1.5e101.__format__('e'), '1.500000e+101')
        self.assertEqual('%e' % 1.5e101, '1.500000e+101')

        self.assertEqual(1.5e-100.__format__('e'), '1.500000e-100')
        self.assertEqual('%e' % 1.5e-100, '1.500000e-100')

        self.assertEqual(1.5e-101.__format__('e'), '1.500000e-101')
        self.assertEqual('%e' % 1.5e-101, '1.500000e-101')

        self.assertEqual('%g' % 1.0, '1')
        self.assertEqual('%#g' % 1.0, '1.00000')
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_int__format__locale(self):
        # test locale support for __format__ code 'n' for integers

        x = 123456789012345678901234567890
        for i in range(0, 30):
            self.assertEqual(locale.format('%d', x, grouping=True), format(x, 'n'))

            # move to the next integer to test
            x = x // 10

        rfmt = ">20n"
        lfmt = "<20n"
        cfmt = "^20n"
        for x in (1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890, 12345678900):
            self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt)))
            self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt)))
            self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt)))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_format_spec_errors(self):
        # int, float, and string all share the same format spec
        # mini-language parser.

        # Check that we can't ask for too many digits. This is
        # probably a CPython specific test. It tries to put the width
        # into a C long.
        self.assertRaises(ValueError, format, 0, '1'*10000 + 'd')

        # Similar with the precision.
        self.assertRaises(ValueError, format, 0, '.' + '1'*10000 + 'd')

        # And may as well test both.
        self.assertRaises(ValueError, format, 0, '1'*1000 + '.' + '1'*10000 + 'd')

        # Make sure commas aren't allowed with various type codes
        for code in 'xXobns':
            self.assertRaises(ValueError, format, 0, ',' + code)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_float_to_string(self):
        def test(f, result):
            self.assertEqual(f.__format__('e'), result)
            self.assertEqual('%e' % f, result)

        # test all 2 digit exponents, both with __format__ and with
        #  '%' formatting
        for i in range(-99, 100):
            test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i))

        # test some 3 digit exponents
        self.assertEqual(1.5e100.__format__('e'), '1.500000e+100')
        self.assertEqual('%e' % 1.5e100, '1.500000e+100')

        self.assertEqual(1.5e101.__format__('e'), '1.500000e+101')
        self.assertEqual('%e' % 1.5e101, '1.500000e+101')

        self.assertEqual(1.5e-100.__format__('e'), '1.500000e-100')
        self.assertEqual('%e' % 1.5e-100, '1.500000e-100')

        self.assertEqual(1.5e-101.__format__('e'), '1.500000e-101')
        self.assertEqual('%e' % 1.5e-101, '1.500000e-101')

        self.assertEqual('%g' % 1.0, '1')
        self.assertEqual('%#g' % 1.0, '1.00000')
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_int__format__locale(self):
        # test locale support for __format__ code 'n' for integers

        x = 123456789012345678901234567890
        for i in range(0, 30):
            self.assertEqual(locale.format('%d', x, grouping=True), format(x, 'n'))

            # move to the next integer to test
            x = x // 10

        rfmt = ">20n"
        lfmt = "<20n"
        cfmt = "^20n"
        for x in (1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890, 12345678900):
            self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt)))
            self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt)))
            self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt)))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_format_spec_errors(self):
        # int, float, and string all share the same format spec
        # mini-language parser.

        # Check that we can't ask for too many digits. This is
        # probably a CPython specific test. It tries to put the width
        # into a C long.
        self.assertRaises(ValueError, format, 0, '1'*10000 + 'd')

        # Similar with the precision.
        self.assertRaises(ValueError, format, 0, '.' + '1'*10000 + 'd')

        # And may as well test both.
        self.assertRaises(ValueError, format, 0, '1'*1000 + '.' + '1'*10000 + 'd')

        # Make sure commas aren't allowed with various type codes
        for code in 'xXobns':
            self.assertRaises(ValueError, format, 0, ',' + code)
项目:Python-Pentest-Tools    作者:proxyanon    | 项目源码 | 文件源码
def file_stats(max_lenght):
    Fl = 7 ** max_lenght
    Fb = (max_lenght + 2) * Fl
    if Fb >= 1000 and Fb < 1000000:
        Fbfinal = Fb / 1000
        stdout.write("[+] Lines : %s\n[+] File size : %i Kb\n\n"%(Fl, Fbfinal))
    elif Fb >= 1000000 and Fb < 1000000000:
        Fbfinal = Fb / 1000000
        stdout.write("[+] Lines : %s\n[+] File size : %i Mb\n\n"%(Fl, Fbfinal))
    elif Fb >= 1000000000:
        setlocale(LC_NUMERIC, '')
        Fbfinal = Fb / 1000000000
        formato = format("%.*f", (0, Fbfinal), True)
        stdout.write("[+] Lines : %s\n[+] File size : "+formato+" Gb\n\n"%(Fl))
    else:
        stdout.write("[+] Lines : %s\n[+] File size : %i bytes\n\n"%(Fl))
    cmd = raw_input("[?] Do you want continue [Y/N] : ")
    if cmd == "N" or cmd == "n":
        exit()
项目:mifid2-rts    作者:bwbadger    | 项目源码 | 文件源码
def extend_classification(self, classification):
        try:
            option = self.root_option.option_for_dates(
                classification.subject.term_from_date,
                classification.subject.term_to_date)
            if option:
                classification.options.append(option)
            else:
                raise KeyError
        except KeyError as _:
            classification.errors.append(
                'Bad term bucket. '
                'Dates: from_date={from_date}, to_date={to_date}.'.format(
                    from_date=classification.subject.term_from_date,
                    to_date=classification.subject.term_to_date,
                )
            )
        return classification
项目:mifid2-rts    作者:bwbadger    | 项目源码 | 文件源码
def extend_classification(self, classification):
        try:
            option = self.root_option.option_for_dates(
                classification.subject.option_from_date,
                classification.subject.option_to_date)
            if option:
                classification.options.append(option)
            else:
                raise KeyError
        except KeyError:
            classification.errors.append(
                'Bad option maturity bucket. '
                'Dates: from_date={from_date}, to_date={to_date}.'.format(
                    from_date=classification.subject.from_date,
                    to_date=classification.subject.to_date,
                )
            )
        return classification
项目:mifid2-rts    作者:bwbadger    | 项目源码 | 文件源码
def extend_classification(self, classification):
        """
        Here I simply delegate to the maturity bucket Criterion for the parameter of my subject
        """
        metal_type = 'Unknown'
        try:
            metal_type = classification.subject.metal_type
            bucket_criterion = self._options[metal_type]
            bucket_criterion.extend_classification(classification)
        except KeyError:
            classification.errors.append(
                'Bad metals maturity bucket.  Metal type: {metal_type}. '
                'Dates: from_date={from_date}, to_date={to_date}.'.format(
                    metal_type=metal_type,
                    from_date=classification.subject.from_date,
                    to_date=classification.subject.to_date,
                )
            )
        return classification
项目:mifid2-rts    作者:bwbadger    | 项目源码 | 文件源码
def extend_classification(self, classification):
        """
        Here I simply delegate to the maturity bucket Criterion for the parameter of my subject
        Energy type must be one of the Subproduct vales of NRGY in RTS 23
        """
        try:
            bucket_key = self.bucket_map[classification.subject.energy_type]
            bucket_criterion = self._options[bucket_key]
            bucket_criterion.extend_classification(classification)
        except KeyError:
            classification.errors.append(
                'Bad energy maturity bucket.  Energy type: {energy_type}. '
                'Dates: from_date={from_date}, to_date={to_date}.'.format(
                    energy_type=classification.subject.energy_type,
                    from_date=classification.subject.from_date,
                    to_date=classification.subject.to_date,
                )
            )
        return classification
项目:mifid2-rts    作者:bwbadger    | 项目源码 | 文件源码
def next_step(self, bucket_option):
        """
        I return a new instance of my class which takes the next step into the future by
        exactly the same amount of time I represent from the preceding step of option.
        I'll only do this if my class and the one before me is of the same type ... for now,
        anyway.
        """
        previous_bucket_ceiling = bucket_option.previous_bucket_option.ceiling
        my_type = type(self)
        if type(previous_bucket_ceiling) == my_type:
            difference_since_last = self.periods - previous_bucket_ceiling.periods
            next_number_of_periods = self.periods + difference_since_last
            return my_type(next_number_of_periods)
        else:
            error_message = "Can't work out the next step.  I am a {my_type}, the preceding is {preceding}".format(
                my_type=my_type,
                preceding=type(previous_bucket_ceiling)
            )
            raise ValueError(error_message)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_float_to_string(self):
        def test(f, result):
            self.assertEqual(f.__format__('e'), result)
            self.assertEqual('%e' % f, result)

        # test all 2 digit exponents, both with __format__ and with
        #  '%' formatting
        for i in range(-99, 100):
            test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i))

        # test some 3 digit exponents
        self.assertEqual(1.5e100.__format__('e'), '1.500000e+100')
        self.assertEqual('%e' % 1.5e100, '1.500000e+100')

        self.assertEqual(1.5e101.__format__('e'), '1.500000e+101')
        self.assertEqual('%e' % 1.5e101, '1.500000e+101')

        self.assertEqual(1.5e-100.__format__('e'), '1.500000e-100')
        self.assertEqual('%e' % 1.5e-100, '1.500000e-100')

        self.assertEqual(1.5e-101.__format__('e'), '1.500000e-101')
        self.assertEqual('%e' % 1.5e-101, '1.500000e-101')

        self.assertEqual('%g' % 1.0, '1')
        self.assertEqual('%#g' % 1.0, '1.00000')
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_int__format__locale(self):
        # test locale support for __format__ code 'n' for integers

        x = 123456789012345678901234567890
        for i in range(0, 30):
            self.assertEqual(locale.format('%d', x, grouping=True), format(x, 'n'))

            # move to the next integer to test
            x = x // 10

        rfmt = ">20n"
        lfmt = "<20n"
        cfmt = "^20n"
        for x in (1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890, 12345678900):
            self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt)))
            self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt)))
            self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt)))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_format_spec_errors(self):
        # int, float, and string all share the same format spec
        # mini-language parser.

        # Check that we can't ask for too many digits. This is
        # probably a CPython specific test. It tries to put the width
        # into a C long.
        self.assertRaises(ValueError, format, 0, '1'*10000 + 'd')

        # Similar with the precision.
        self.assertRaises(ValueError, format, 0, '.' + '1'*10000 + 'd')

        # And may as well test both.
        self.assertRaises(ValueError, format, 0, '1'*1000 + '.' + '1'*10000 + 'd')

        # Make sure commas aren't allowed with various type codes
        for code in 'xXobns':
            self.assertRaises(ValueError, format, 0, ',' + code)
项目:improved_wgan_training    作者:YuguangTong    | 项目源码 | 文件源码
def param(name, *args, **kwargs):
    """
    A wrapper for `tf.Variable` which enables parameter sharing in models.

    Creates and returns theano shared variables similarly to `tf.Variable`, 
    except if you try to create a param with the same name as a 
    previously-created one, `param(...)` will just return the old one instead of 
    making a new one.

    This constructor also adds a `param` attribute to the shared variables it 
    creates, so that you can easily search a graph for all params.
    """

    if name not in _params:
        kwargs['name'] = name
        param = tf.Variable(*args, **kwargs)
        param.param = True
        _params[name] = param
    result = _params[name]
    i = 0
    while result in _param_aliases:
        # print 'following alias {}: {} to {}'.format(i, result, _param_aliases[result])
        i += 1
        result = _param_aliases[result]
    return result
项目:speech    作者:igul222    | 项目源码 | 文件源码
def print_params_info(cost, params):
    """Print information about the parameters in the given param set."""

    params = sorted(params, key=lambda p: p.name)
    values = [p.get_value(borrow=True) for p in params]
    shapes = [p.shape for p in values]
    print "Params for cost:"
    for param, value, shape in zip(params, values, shapes):
        print "\t{0} ({1})".format(
            param.name,
            ",".join([str(x) for x in shape])
        )

    total_param_count = 0
    for shape in shapes:
        param_count = 1
        for dim in shape:
            param_count *= dim
        total_param_count += param_count
    print "Total parameter count: {0}".format(
        locale.format("%d", total_param_count, grouping=True)
    )
项目:djangoSIGE    作者:thiagopena    | 项目源码 | 文件源码
def test_edit_recebimento_movimentar_caixa_false_get_post_request(self):
        # Buscar entrada com movimento de caixa e data_pagamento
        obj = Entrada.objects.filter(status='0', movimentar_caixa=True).exclude(Q(movimento_caixa__isnull=True) | Q(
            data_pagamento__isnull=True) | Q(data_pagamento=datetime.strptime('06/07/2017', "%d/%m/%Y").date())).order_by('pk').last()
        url = reverse('financeiro:editarrecebimentoview',
                      kwargs={'pk': obj.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        data = response.context['form'].initial
        replace_none_values_in_dictionary(data)
        data['descricao'] = 'Recebimento editado'
        data['valor_total'] = locale.format(
            u'%.2f', Decimal(data['valor_total']), 1)
        data['valor_liquido'] = locale.format(
            u'%.2f', Decimal(data['valor_liquido']), 1)
        data['movimentar_caixa'] = False
        response = self.client.post(url, data, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response, 'financeiro/lancamento/lancamento_list.html')

        # Verificar se movimento foi removido do lancamento
        obj.refresh_from_db()
        self.assertIsNone(obj.movimento_caixa)
项目:djangoSIGE    作者:thiagopena    | 项目源码 | 文件源码
def test_edit_pagamento_movimentar_caixa_false_get_post_request(self):
        # Buscar saida com movimento de caixa e data_pagamento
        obj = Saida.objects.filter(status='0', movimentar_caixa=True).exclude(Q(movimento_caixa__isnull=True) | Q(
            data_pagamento__isnull=True) | Q(data_pagamento=datetime.strptime('06/07/2017', "%d/%m/%Y").date())).order_by('pk').last()
        url = reverse('financeiro:editarpagamentoview',
                      kwargs={'pk': obj.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        data = response.context['form'].initial
        replace_none_values_in_dictionary(data)
        data['descricao'] = 'Pagamento editado'
        data['valor_total'] = locale.format(
            u'%.2f', Decimal(data['valor_total']), 1)
        data['valor_liquido'] = locale.format(
            u'%.2f', Decimal(data['valor_liquido']), 1)
        data['movimentar_caixa'] = False
        response = self.client.post(url, data, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response, 'financeiro/lancamento/lancamento_list.html')

        # Verificar se movimento foi removido do lancamento
        obj.refresh_from_db()
        self.assertIsNone(obj.movimento_caixa)
项目:djangoSIGE    作者:thiagopena    | 项目源码 | 文件源码
def get_aliquota_pis(self, format=True):
        try:
            pis_padrao = PIS.objects.get(
                grupo_fiscal=self.produto.grupo_fiscal)

            if pis_padrao.valiq_pis:
                if format:
                    return locale.format(u'%.2f', pis_padrao.valiq_pis, 1)
                else:
                    return pis_padrao.valiq_pis
            elif pis_padrao.p_pis:
                if format:
                    return locale.format(u'%.2f', pis_padrao.p_pis, 1)
                else:
                    return pis_padrao.p_pis

        except PIS.DoesNotExist:
            return
项目:improved_wgan_training    作者:igul222    | 项目源码 | 文件源码
def param(name, *args, **kwargs):
    """
    A wrapper for `tf.Variable` which enables parameter sharing in models.

    Creates and returns theano shared variables similarly to `tf.Variable`, 
    except if you try to create a param with the same name as a 
    previously-created one, `param(...)` will just return the old one instead of 
    making a new one.

    This constructor also adds a `param` attribute to the shared variables it 
    creates, so that you can easily search a graph for all params.
    """

    if name not in _params:
        kwargs['name'] = name
        param = tf.Variable(*args, **kwargs)
        param.param = True
        _params[name] = param
    result = _params[name]
    i = 0
    while result in _param_aliases:
        # print 'following alias {}: {} to {}'.format(i, result, _param_aliases[result])
        i += 1
        result = _param_aliases[result]
    return result
项目:mimicry.ai    作者:fizerkhan    | 项目源码 | 文件源码
def plot_traing_info(x, ylist, path):
    """
    Loads log file and plot x and y values as provided by input.
    Saves as <path>/train_log.png
    """
    file_name = os.path.join(path, __train_log_file_name)
    try:
        with open(file_name, "rb") as f:
            log = pickle.load(f)
    except IOError:  # first time
        warnings.warn("There is no {} file here!!!".format(file_name))
        return
    plt.figure()
    x_vals = log[x]
    for y in ylist:
        y_vals = log[y]
        if len(y_vals) != len(x_vals):
            warning.warn("One of y's: {} does not have the same length as x:{}".format(y, x))
        plt.plot(x_vals, y_vals, label=y)
        # assert len(y_vals) == len(x_vals), "not the same len"
    plt.xlabel(x)
    plt.legend()
    #plt.show()
    plt.savefig(file_name[:-3]+'png', bbox_inches='tight')
    plt.close('all')
项目:transvar    作者:zwdzwd    | 项目源码 | 文件源码
def format_records(records, qop, args):

    """Print records"""

    if len(records) > 0:
        if args.oneline:
            s = qop+'\t' if qop else ''
            s += '\t|||\t'.join([r.formats() for r in records])
            try:
                print(s)
            except IOError:
                sys.exit(1)
        else:
            for r in records:
                r.format(qop)
    else:
        r = Record()
        r.append_info('no_valid_transcript_found')
        r.format(qop)
项目:WaveNet-Theano    作者:huyouare    | 项目源码 | 文件源码
def print_params_info(params):
    """Print information about the parameters in the given param set."""

    params = sorted(params, key=lambda p: p.name)
    values = [p.get_value(borrow=True) for p in params]
    shapes = [p.shape for p in values]
    print "Params for cost:"
    for param, value, shape in zip(params, values, shapes):
        print "\t{0} ({1})".format(
            param.name,
            ",".join([str(x) for x in shape])
        )

    total_param_count = 0
    for shape in shapes:
        param_count = 1
        for dim in shape:
            param_count *= dim
        total_param_count += param_count
    print "Total parameter count: {0}".format(
        locale.format("%d", total_param_count, grouping=True)
    )
项目:Cortex-Analyzers    作者:CERT-BDF    | 项目源码 | 文件源码
def _query(self, path, before=None, after=None):
        res = []
        url = '%s/lookup/%s' % (self.server, path)

        params = {}
        if self.limit:
            params['limit'] = self.limit
        if before and after:
            params['time_first_after'] = after
            params['time_last_before'] = before
        else:
            if before:
                params['time_first_before'] = before
            if after:
                params['time_last_after'] = after
        if params:
            url += '?{0}'.format(urllib.urlencode(params))

        req = urllib2.Request(url)
        req.add_header('Accept', 'application/json')
        req.add_header('X-Api-Key', self.apikey)
        http = urllib2.urlopen(req)
        while True:
            line = http.readline()
            if not line:
                break
            yield json.loads(line)
项目:sampleRNN_ICLR2017    作者:soroushmehr    | 项目源码 | 文件源码
def print_params_info(params, path=None):
    """
    Print information about the parameters in the given param set.

    With `path` as an address to a directory it will _append_ it
    as a file named `model_settings.txt` as well.

    :usage:
        >>> params = lib.get_params(cost)
        >>> lib.print_params_info(params, path='./')
    """
    params = sorted(params, key=lambda p: p.name)
    values = [p.get_value(borrow=True) for p in params]
    shapes = [p.shape for p in values]
    total_param_count = 0
    multiply_all = lambda a, b: a*b
    log = "\nParams for cost:"
    for param, value, shape in zip(params, values, shapes):
        log += ("\n\t%-20s %s" % (shape, param.name))
        total_param_count += reduce(multiply_all, shape)

    log += "\nTotal parameter count for this cost:\n\t{0}".format(
        locale.format("%d", total_param_count, grouping=True)
    )
    print log

    if path is not None:
        ensure_dir(path)
        # Don't override, just append if by mistake there is something in the file.
        with open(os.path.join(path, __model_setting_file_name), 'a+') as f:
            f.write(log)
项目:SGAN    作者:YuhangSong    | 项目源码 | 文件源码
def alias_params(replace_dict):
    for old,new in replace_dict.items():
        # print "aliasing {} to {}".format(old,new)
        _param_aliases[old] = new
项目:SGAN    作者:YuhangSong    | 项目源码 | 文件源码
def print_model_settings(locals_):
    print "Uppercase local vars:"
    all_vars = [(k,v) for (k,v) in locals_.items() if (k.isupper() and k!='T' and k!='SETTINGS' and k!='ALL_SETTINGS')]
    all_vars = sorted(all_vars, key=lambda x: x[0])
    for var_name, var_value in all_vars:
        print "\t{}: {}".format(var_name, var_value)
项目:SGAN    作者:YuhangSong    | 项目源码 | 文件源码
def print_model_settings_dict(settings):
    print "Settings dict:"
    all_vars = [(k,v) for (k,v) in settings.items()]
    all_vars = sorted(all_vars, key=lambda x: x[0])
    for var_name, var_value in all_vars:
        print "\t{}: {}".format(var_name, var_value)