sys.maxsize

Here are the examples of the python api sys.maxsize taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: validr
Source File: validators.py
View license
@handle_default_optional_desc()
def int_validator(min=-sys.maxsize, max=sys.maxsize):
    """Validate int string

    :param min: the min value, default -sys.maxsize
    :param max: the max value, default sys.maxsize
    """
    def validator(value):
        try:
            v = int(value)
        except Exception:
            raise Invalid("invalid int")
        if v < min:
            raise Invalid("value must >= %d" % min)
        elif v > max:
            raise Invalid("value must <= %d" % max)
        return v
    return validator

Example 2

Project: pymo
Source File: test_struct.py
View license
    def test_count_overflow(self):
        hugecount = '{}b'.format(sys.maxsize+1)
        self.assertRaises(struct.error, struct.calcsize, hugecount)

        hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
        self.assertRaises(struct.error, struct.calcsize, hugecount2)

Example 3

Project: xapian-haystack
Source File: test_backend.py
View license
    def test_parse_query_range(self):
        self.assertExpectedQuery(self.backend.parse_query('name:david1..david2'),
                                 '0 * VALUE_RANGE 9 david1 david2',
                                 xapian12string='VALUE_RANGE 9 david1 david2')
        self.assertExpectedQuery(self.backend.parse_query('number:0..10'),
                                 '0 * VALUE_RANGE 11 000000000000 000000000010',
                                 xapian12string='VALUE_RANGE 11 000000000000 000000000010')
        self.assertExpectedQuery(self.backend.parse_query('number:..10'),
                                 '0 * VALUE_RANGE 11 %012d 000000000010' % (-sys.maxsize - 1),
                                 xapian12string='VALUE_RANGE 11 %012d 000000000010' % (-sys.maxsize - 1))
        self.assertExpectedQuery(self.backend.parse_query('number:10..*'),
                                 '0 * VALUE_RANGE 11 000000000010 %012d' % sys.maxsize,
                                 xapian12string='VALUE_RANGE 11 000000000010 %012d' % sys.maxsize)

Example 4

Project: openwrt-mt7620
Source File: test_struct.py
View license
    def test_count_overflow(self):
        hugecount = '{}b'.format(sys.maxsize+1)
        self.assertRaises(struct.error, struct.calcsize, hugecount)

        hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
        self.assertRaises(struct.error, struct.calcsize, hugecount2)

Example 5

Project: datafari
Source File: test_struct.py
View license
    def test_count_overflow(self):
        hugecount = '{}b'.format(sys.maxsize+1)
        self.assertRaises(struct.error, struct.calcsize, hugecount)

        hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
        self.assertRaises(struct.error, struct.calcsize, hugecount2)

Example 6

Project: PyAutoC
Source File: test_struct.py
View license
    def test_count_overflow(self):
        hugecount = '{}b'.format(sys.maxsize+1)
        self.assertRaises(struct.error, struct.calcsize, hugecount)

        hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
        self.assertRaises(struct.error, struct.calcsize, hugecount2)

Example 7

Project: ghini.desktop
Source File: test_image_putdata.py
View license
def test_long_integers():
    # see bug-200802-systemerror
    def put(value):
        im = Image.new("RGBA", (1, 1))
        im.putdata([value])
        return im.getpixel((0, 0))
    assert_equal(put(0xFFFFFFFF), (255, 255, 255, 255))
    assert_equal(put(0xFFFFFFFF), (255, 255, 255, 255))
    assert_equal(put(-1), (255, 255, 255, 255))
    assert_equal(put(-1), (255, 255, 255, 255))
    if sys.maxsize > 2**32:
        assert_equal(put(sys.maxsize), (255, 255, 255, 255))
    else:
        assert_equal(put(sys.maxsize), (255, 255, 255, 127))

Example 8

Project: myhdl
Source File: test_bin.py
View license
    def testRandomLongWith(self):
        for j in range(SIZE):
            w = randrange(1, 1000)
            k = randrange(sys.maxsize)
            i = k + sys.maxsize
            assert bin(i, w) == binref(i, w)
            i = -k - sys.maxsize
            assert bin(i, w) == binref(i, w)

Example 9

Project: myhdl
Source File: test_bin.py
View license
    def testRandomLong(self):
        for j in range(SIZE):
            k = randrange(sys.maxsize)
            i = k + sys.maxsize
            assert bin(i) == binref(i)
            i = -k - sys.maxsize
            assert bin(i) == binref(i)

Example 10

Project: openwrt-mt7620
Source File: test_struct.py
View license
    def test_count_overflow(self):
        hugecount = '{}b'.format(sys.maxsize+1)
        self.assertRaises(struct.error, struct.calcsize, hugecount)

        hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
        self.assertRaises(struct.error, struct.calcsize, hugecount2)

Example 11

Project: pyzor
Source File: test_pyzor.py
View license
    def test_pong(self):
        input = "Test1 multiple pong Test2"
        self.check_pyzor_multiple("pong", None, input=input, exit_code=0,
                                  code=[200, 200, 200],
                                  counts=[(sys.maxsize, 0),
                                          (sys.maxsize, 0),
                                          (sys.maxsize, 0)])

Example 12

Project: xapian-haystack
Source File: test_backend.py
View license
    def test_parse_query_range(self):
        self.assertExpectedQuery(self.backend.parse_query('name:david1..david2'),
                                 '0 * VALUE_RANGE 9 david1 david2',
                                 xapian12string='VALUE_RANGE 9 david1 david2')
        self.assertExpectedQuery(self.backend.parse_query('number:0..10'),
                                 '0 * VALUE_RANGE 11 000000000000 000000000010',
                                 xapian12string='VALUE_RANGE 11 000000000000 000000000010')
        self.assertExpectedQuery(self.backend.parse_query('number:..10'),
                                 '0 * VALUE_RANGE 11 %012d 000000000010' % (-sys.maxsize - 1),
                                 xapian12string='VALUE_RANGE 11 %012d 000000000010' % (-sys.maxsize - 1))
        self.assertExpectedQuery(self.backend.parse_query('number:10..*'),
                                 '0 * VALUE_RANGE 11 000000000010 %012d' % sys.maxsize,
                                 xapian12string='VALUE_RANGE 11 000000000010 %012d' % sys.maxsize)

Example 13

Project: robotframework
Source File: test_testlibrary.py
View license
    def test_arguments_with_kwargs(self):
        lib = TestLibrary('classes.ArgDocDynamicLibraryWithKwargsSupport')
        for name, (mina, maxa) in [('No Arg', (0, 0)),
                                   ('One Arg', (1, 1)),
                                   ('One or Two Args', (1, 2)),
                                   ('Many Args', (0, sys.maxsize))]:
            assert_handler_args(lib.handlers[name], mina, maxa, kwargs=False)
        for name, (mina, maxa) in [('Kwargs', (0, 0)),
                                   ('Varargs and Kwargs', (0, sys.maxsize)),
                                   ('No Arg Spec', (0, sys.maxsize))]:
            assert_handler_args(lib.handlers[name], mina, maxa, kwargs=True)

Example 14

Project: wordgraph
Source File: grapher.py
View license
    def __init__(self):

        self.defaults = {
            'title': None,
            'x_axis': {
                'label': 'time',
                'min': sys.maxsize,
                'max': -1 * sys.maxsize
            },
            'y_axis': {
                'label': 'metric',
                'min': sys.maxsize,
                'max': -1 * sys.maxsize
            },
            "series": []

        }

Example 15

Project: chipsec
Source File: test_struct.py
View license
    def test_count_overflow(self):
        hugecount = '{}b'.format(sys.maxsize+1)
        self.assertRaises(struct.error, struct.calcsize, hugecount)

        hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
        self.assertRaises(struct.error, struct.calcsize, hugecount2)

Example 16

View license
    def test_initminmax(self):
        "Sequence.__init__(...minmax=...)"
        p1 = Prod('p1', lambda t, v: t == 1)      
        p2 = Prod('p2', lambda t, v: t == 2)
            
        s = Sequence(p1, p2, minmax=lambda: (2, 3))
        self.assertEqual(2, s._min)
        self.assertEqual(3, s._max)

        s = Sequence(p1, p2, minmax=lambda: (0, None))        
        self.assertEqual(0, s._min)
        
        try:
            # py2.6/3
            m = sys.maxsize
        except AttributeError:
            # py<1.6
            m = sys.maxint
        self.assertEqual(m, s._max)

Example 17

Project: utter-pool
Source File: __init__.py
View license
    def reorderByPrefs(self, detectors, prefs):
        if prefs is None:
            return []
        elif prefs == []:
            return detectors
        else:
            prefs.insert(0, '')
            return sorted(detectors,
                key=lambda d: d.name in prefs and prefs.index(d.name) or sys.maxsize)

Example 18

Project: hacking-tools
Source File: test_sre_yield.py
View license
    def testCanIterateGiantValues(self):
        v = sre_yield.AllStrings('.+')
        self.assertGreater(v.__len__(), sys.maxsize)
        it = iter(v)
        self.assertEqual('\x00', next(it))
        self.assertEqual('\x01', next(it))

Example 19

Project: unicode-solutions
Source File: charfinder2.py
View license
    def find_chars(self, query, start=0, stop=None):
        stop = sys.maxsize if stop is None else stop
        result_sets = []
        for word in tokenize(query):
            chars = self.index.get(word)
            if chars is None:  # shorcut: no such word
                result_sets = []
                break
            result_sets.append(chars)

        if not result_sets:
            return QueryResult(0, ())

        result = functools.reduce(set.intersection, result_sets)
        result = sorted(result)  # must sort to support start, stop
        result_iter = itertools.islice(result, start, stop)
        return QueryResult(len(result),
                           (char for char in result_iter))

Example 20

Project: plenum
Source File: stacked.py
View license
    async def service(self, limit=None) -> int:
        """
        Service `limit` number of received messages in this stack.

        :param limit: the maximum number of messages to be processed. If None,
        processes all of the messages in rxMsgs.
        :return: the number of messages processed.
        """
        pracLimit = limit if limit else sys.maxsize
        x = next(self.coro)
        if x > 0:
            for x in range(pracLimit):
                try:
                    self.msgHandler(self.rxMsgs.popleft())
                except IndexError:
                    break
        return x

Example 21

Project: imagrium
Source File: test_bytes.py
View license
    def test_from_ssize(self):
        self.assertEqual(self.type2test(0), b'')
        self.assertEqual(self.type2test(1), b'\x00')
        self.assertEqual(self.type2test(5), b'\x00\x00\x00\x00\x00')
        self.assertRaises(ValueError, self.type2test, -1)

        self.assertEqual(self.type2test('0', 'ascii'), b'0')
        self.assertEqual(self.type2test(b'0'), b'0')
        self.assertRaises(OverflowError, self.type2test, sys.maxsize + 1)

Example 22

View license
    def test_hypergeometric_range(self):
        # Test for ticket #921
        assert_(np.all(np.random.hypergeometric(3, 18, 11, size=10) < 4))
        assert_(np.all(np.random.hypergeometric(18, 3, 11, size=10) > 0))

        # Test for ticket #5623
        args = [
            (2**20 - 2, 2**20 - 2, 2**20 - 2),  # Check for 32-bit systems
        ]
        is_64bits = sys.maxsize > 2**32
        if is_64bits and sys.platform != 'win32':
            args.append((2**40 - 2, 2**40 - 2, 2**40 - 2)) # Check for 64-bit systems
        for arg in args:
            assert_(np.random.hypergeometric(*arg) > 0)

Example 23

Project: nolearn
Source File: handlers.py
View license
    def __init__(self, loss='valid_loss', score=None, verbose=1):
        self.loss = loss
        self.score = score
        self.verbose = verbose
        self.best_weights = None
        self.best_weights_loss = sys.maxsize
        self.best_weights_epoch = None
        self.restore = _RestoreBestWeights(self)

Example 24

Project: toxygen
Source File: main.py
View license
def configure():
    """Removes unused libs"""
    d = curr_directory() + '/libs/'
    is_64bits = sys.maxsize > 2 ** 32
    if not is_64bits:
        if os.path.exists(d + 'libtox64.dll'):
            os.remove(d + 'libtox64.dll')
        if os.path.exists(d + 'libsodium64.a'):
            os.remove(d + 'libsodium64.a')
    else:
        if os.path.exists(d + 'libtox.dll'):
            os.remove(d + 'libtox.dll')
        if os.path.exists(d + 'libsodium.a'):
            os.remove(d + 'libsodium.a')
        try:
            os.rename(d + 'libtox64.dll', d + 'libtox.dll')
            os.rename(d + 'libsodium64.a', d + 'libsodium.a')
        except:
            pass

Example 25

Project: gajim-omemo
Source File: test_omemo_state.py
View license
def test_own_devices(omemo_state):
    """ Checks the adding/removing device_ids to own_devices .
    """
    assert len(omemo_state.own_devices) == 0
    assert isinstance(omemo_state.own_device_id, int)
    devices_update = [random.randint(0, sys.maxsize) for x in range(0,3)]
    omemo_state.set_own_devices(devices_update) 
    assert len(omemo_state.own_devices) == 3
    assert omemo_state.own_devices == devices_update

Example 26

Project: nzbToMedia
Source File: munkres.py
View license
    def __find_smallest(self):
        """Find the smallest uncovered value in the matrix."""
        minval = sys.maxsize
        for i in range(self.n):
            for j in range(self.n):
                if (not self.row_covered[i]) and (not self.col_covered[j]):
                    if minval > self.C[i][j]:
                        minval = self.C[i][j]
        return minval

Example 27

Project: gremlin-python
Source File: test_pipeline.py
View license
def test_side_effect():
    global youngest
    def find_youngest(it):
        global youngest
        youngest = it.age if youngest > it.age else youngest

    assert youngest == sys.maxsize
    assert set(g.V.has('age').side_effect(find_youngest).age) == {29, 27, 32, 35}
    assert youngest == 27

Example 28

Project: WAPT
Source File: test_odbc.py
View license
    def testInt(self):
        self._test_val('intfield', 1)
        self._test_val('intfield', 0)
        try:
            big = sys.maxsize
        except AttributeError:
            big = sys.maxint
        self._test_val('intfield', big)

Example 29

Project: bde-tools
Source File: sysutil.py
View license
def is_64bit_system():
    """Return whether the system is 64-bit capable.

    We approximate the return value by first checking whether we are
    running the 64-bit python interpreter.  If so, then we are done.
    Otherwise, we match the current machine type with a set of known 64-bit
    machine types.
    """

    if sys.maxsize > 2**32:
        return True

    return platform.machine().lower()  \
        in ('amd64', 'x86_64', 'sun4v', 'ppc64')

Example 30

Project: python101
Source File: code.py
View license
    def run(self):
        if 'linenothreshold' in self.options:
            try:
                linenothreshold = int(self.options['linenothreshold'])
            except Exception:
                linenothreshold = 10
        else:
            linenothreshold = sys.maxsize
        return [addnodes.highlightlang(lang=self.arguments[0].strip(),
                                       linenothreshold=linenothreshold)]

Example 31

Project: plexpy
Source File: arrow.py
View license
    @classmethod
    def _get_iteration_params(cls, end, limit):

        if end is None:

            if limit is None:
                raise Exception('one of \'end\' or \'limit\' is required')

            return cls.max, limit

        else:
            return end, sys.maxsize

Example 32

Project: wakatime
Source File: lexer.py
View license
    def _process_regex(cls, regex, rflags, state):
        if isinstance(regex, words):
            rex = regex_opt(regex.words, prefix=regex.prefix,
                            suffix=regex.suffix)
        else:
            rex = regex
        compiled = re.compile(rex, rflags)

        def match_func(text, pos, endpos=sys.maxsize):
            info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0])
            t0 = time.time()
            res = compiled.match(text, pos, endpos)
            t1 = time.time()
            info[0] += 1
            info[1] += t1 - t0
            return res
        return match_func

Example 33

Project: smc.mw
Source File: sink.py
View license
def create_sink():
    """ Return a new Sink with a numeric ID incremented in a threadsafe way """
    global last_sink_id, sink_id_lock, sinks
    sink_id_lock.acquire()
    try:
        this_sink_id = last_sink_id
        last_sink_id = (last_sink_id + 1) % sys.maxsize
        # If you have more than maxsize sinks open at a time, you're screwed
    finally:
        sink_id_lock.release()
    sink = Sink(this_sink_id)
    sinks[this_sink_id] = sink
    return sink

Example 34

Project: taurus
Source File: mocks.py
View license
    def __init__(self):
        super(ModuleMock, self).__init__()
        self.postproc_exc = None
        self.check_exc = None
        self.prepare_exc = None
        self.startup_exc = None
        self.shutdown_exc = None

        self.check_iterations = sys.maxsize

        self.was_shutdown = False
        self.was_startup = False
        self.was_prepare = False
        self.was_check = False
        self.was_postproc = False

Example 35

Project: sublime-wakatime
Source File: lexer.py
View license
    def _process_regex(cls, regex, rflags, state):
        if isinstance(regex, words):
            rex = regex_opt(regex.words, prefix=regex.prefix,
                            suffix=regex.suffix)
        else:
            rex = regex
        compiled = re.compile(rex, rflags)

        def match_func(text, pos, endpos=sys.maxsize):
            info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0])
            t0 = time.time()
            res = compiled.match(text, pos, endpos)
            t1 = time.time()
            info[0] += 1
            info[1] += t1 - t0
            return res
        return match_func

Example 36

Project: mypaint
Source File: layers.py
View license
    def invalidate_iters(self):
        """Invalidates all iters produced by this model"""
        # No need to zap the lookup tables: tree paths have a tightly
        # controlled vocabulary.
        if self._iter_stamp == sys.maxsize:
            self._iter_stamp = self.MIN_VALID_STAMP
        else:
            self._iter_stamp += 1

Example 37

Project: r-bridge-install
Source File: utils.py
View license
def platform():
    """ Check whether our Python is 32 or 64 bits."""
    platform = None
    if sys.maxsize > 2**32:
        platform = 'x64'
    else:
        platform = 'i386'
    return platform

Example 38

Project: multiprocess
Source File: heap.py
View license
    def malloc(self, size):
        # return a block of right size (possibly rounded up)
        assert 0 <= size < sys.maxsize
        if os.getpid() != self._lastpid:
            self.__init__()                     # reinitialize after fork
        self._lock.acquire()
        self._free_pending_blocks()
        try:
            size = self._roundup(max(size,1), self._alignment)
            (arena, start, stop) = self._malloc(size)
            new_stop = start + size
            if new_stop < stop:
                self._free((arena, new_stop, stop))
            block = (arena, start, new_stop)
            self._allocated_blocks.add(block)
            return block
        finally:
            self._lock.release()

Example 39

Project: txstatsd
Source File: uniformsample.py
View license
    def __init__(self, reservoir_size):
        """Creates a new C{UniformSample}.

        @param reservoir_size: The number of samples to keep in the sampling
            reservoir.
        """
        self._values = [0 for i in range(reservoir_size)]
        self._count = 0
        self.clear()
        self.maxint = getattr(sys, 'maxint', sys.maxsize)

Example 40

Project: ScratchABit
Source File: scratchabit.py
View license
    def set_model(self, model):
        self.model = model
        self.set_lines(model.lines())
        # Invalidate top_line. Assuming goto_*() will be called
        # after set_model().
        self.top_line = sys.maxsize

Example 41

Project: TwistedBot
Source File: base.py
View license
    def callLater(self, _seconds, _f, *args, **kw):
        """See twisted.internet.interfaces.IReactorTime.callLater.
        """
        assert callable(_f), "%s is not callable" % _f
        assert sys.maxsize >= _seconds >= 0, \
               "%s is not greater than or equal to 0 seconds" % (_seconds,)
        tple = DelayedCall(self.seconds() + _seconds, _f, args, kw,
                           self._cancelCallLater,
                           self._moveCallLaterSooner,
                           seconds=self.seconds)
        self._newTimedCalls.append(tple)
        return tple

Example 42

Project: pyforms
Source File: EventsWidget.py
View license
	@position.setter
	def position(self, position):
		self._pointer._position = position
		self._break_draw = True and self._is_painting

		if (position / self._scale) >= sys.maxsize:
			self.scale += 1

		#######################################################################
		# Check if the current time position is inside the scroll
		# if is not in, update the scroll position
		self.__check_current_time_is_visible(position)
		#######################################################################
		self.repaint()

Example 43

Project: LTLMoP
Source File: strategy.py
View license
    def getName(self):
        if self.state_id is None:
            # Make sure the unique ID is positive
            unique_id = hash(self) % ((sys.maxsize + 1) * 2)
            return "state_{}".format(unique_id)
        else:
            return self.state_id

Example 44

Project: GAE-Bulk-Mailer
Source File: __init__.py
View license
    def reorderByPrefs(self, detectors, prefs):
        if prefs is None:
            return []
        elif prefs == []:
            return detectors
        else:
            prefs.insert(0, '')
            return sorted(detectors,
                key=lambda d: d.name in prefs and prefs.index(d.name) or sys.maxsize)

Example 45

View license
    def test_basic(self):
        self.assertEqual(int(314), 314)
        self.assertEqual(int(3.14), 3)
        # Check that conversion from float truncates towards zero
        self.assertEqual(int(-3.14), -3)
        self.assertEqual(int(3.9), 3)
        self.assertEqual(int(-3.9), -3)
        self.assertEqual(int(3.5), 3)
        self.assertEqual(int(-3.5), -3)
        self.assertEqual(int("-3"), -3)
        self.assertEqual(int(" -3 "), -3)
        self.assertEqual(int("\N{EM SPACE}-3\N{EN SPACE}"), -3)
        # Different base:
        self.assertEqual(int("10",16), 16)
        # Test conversion from strings and various anomalies
        for s, v in L:
            for sign in "", "+", "-":
                for prefix in "", " ", "\t", "  \t\t  ":
                    ss = prefix + sign + s
                    vv = v
                    if sign == "-" and v is not ValueError:
                        vv = -v
                    try:
                        self.assertEqual(int(ss), vv)
                    except ValueError:
                        pass

        s = repr(-1-sys.maxsize)
        x = int(s)
        self.assertEqual(x+1, -sys.maxsize)
        self.assertIsInstance(x, int)
        # should return int
        self.assertEqual(int(s[1:]), sys.maxsize+1)

        # should return int
        x = int(1e100)
        self.assertIsInstance(x, int)
        x = int(-1e100)
        self.assertIsInstance(x, int)


        # SF bug 434186:  0x80000000/2 != 0x80000000>>1.
        # Worked by accident in Windows release build, but failed in debug build.
        # Failed in all Linux builds.
        x = -1-sys.maxsize
        self.assertEqual(x >> 1, x//2)

        self.assertRaises(ValueError, int, '123\0')
        self.assertRaises(ValueError, int, '53', 40)

        # SF bug 1545497: embedded NULs were not detected with
        # explicit base
        self.assertRaises(ValueError, int, '123\0', 10)
        self.assertRaises(ValueError, int, '123\x00 245', 20)

        x = int('1' * 600)
        self.assertIsInstance(x, int)


        self.assertRaises(TypeError, int, 1, 12)

        self.assertEqual(int('0o123', 0), 83)
        self.assertEqual(int('0x123', 16), 291)

        # Bug 1679: "0x" is not a valid hex literal
        self.assertRaises(ValueError, int, "0x", 16)
        self.assertRaises(ValueError, int, "0x", 0)

        self.assertRaises(ValueError, int, "0o", 8)
        self.assertRaises(ValueError, int, "0o", 0)

        self.assertRaises(ValueError, int, "0b", 2)
        self.assertRaises(ValueError, int, "0b", 0)

        # SF bug 1334662: int(string, base) wrong answers
        # Various representations of 2**32 evaluated to 0
        # rather than 2**32 in previous versions

        self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296)
        self.assertEqual(int('102002022201221111211', 3), 4294967296)
        self.assertEqual(int('10000000000000000', 4), 4294967296)
        self.assertEqual(int('32244002423141', 5), 4294967296)
        self.assertEqual(int('1550104015504', 6), 4294967296)
        self.assertEqual(int('211301422354', 7), 4294967296)
        self.assertEqual(int('40000000000', 8), 4294967296)
        self.assertEqual(int('12068657454', 9), 4294967296)
        self.assertEqual(int('4294967296', 10), 4294967296)
        self.assertEqual(int('1904440554', 11), 4294967296)
        self.assertEqual(int('9ba461594', 12), 4294967296)
        self.assertEqual(int('535a79889', 13), 4294967296)
        self.assertEqual(int('2ca5b7464', 14), 4294967296)
        self.assertEqual(int('1a20dcd81', 15), 4294967296)
        self.assertEqual(int('100000000', 16), 4294967296)
        self.assertEqual(int('a7ffda91', 17), 4294967296)
        self.assertEqual(int('704he7g4', 18), 4294967296)
        self.assertEqual(int('4f5aff66', 19), 4294967296)
        self.assertEqual(int('3723ai4g', 20), 4294967296)
        self.assertEqual(int('281d55i4', 21), 4294967296)
        self.assertEqual(int('1fj8b184', 22), 4294967296)
        self.assertEqual(int('1606k7ic', 23), 4294967296)
        self.assertEqual(int('mb994ag', 24), 4294967296)
        self.assertEqual(int('hek2mgl', 25), 4294967296)
        self.assertEqual(int('dnchbnm', 26), 4294967296)
        self.assertEqual(int('b28jpdm', 27), 4294967296)
        self.assertEqual(int('8pfgih4', 28), 4294967296)
        self.assertEqual(int('76beigg', 29), 4294967296)
        self.assertEqual(int('5qmcpqg', 30), 4294967296)
        self.assertEqual(int('4q0jto4', 31), 4294967296)
        self.assertEqual(int('4000000', 32), 4294967296)
        self.assertEqual(int('3aokq94', 33), 4294967296)
        self.assertEqual(int('2qhxjli', 34), 4294967296)
        self.assertEqual(int('2br45qb', 35), 4294967296)
        self.assertEqual(int('1z141z4', 36), 4294967296)

        # tests with base 0
        # this fails on 3.0, but in 2.x the old octal syntax is allowed
        self.assertEqual(int(' 0o123  ', 0), 83)
        self.assertEqual(int(' 0o123  ', 0), 83)
        self.assertEqual(int('000', 0), 0)
        self.assertEqual(int('0o123', 0), 83)
        self.assertEqual(int('0x123', 0), 291)
        self.assertEqual(int('0b100', 0), 4)
        self.assertEqual(int(' 0O123   ', 0), 83)
        self.assertEqual(int(' 0X123  ', 0), 291)
        self.assertEqual(int(' 0B100 ', 0), 4)

        # without base still base 10
        self.assertEqual(int('0123'), 123)
        self.assertEqual(int('0123', 10), 123)

        # tests with prefix and base != 0
        self.assertEqual(int('0x123', 16), 291)
        self.assertEqual(int('0o123', 8), 83)
        self.assertEqual(int('0b100', 2), 4)
        self.assertEqual(int('0X123', 16), 291)
        self.assertEqual(int('0O123', 8), 83)
        self.assertEqual(int('0B100', 2), 4)

        # the code has special checks for the first character after the
        #  type prefix
        self.assertRaises(ValueError, int, '0b2', 2)
        self.assertRaises(ValueError, int, '0b02', 2)
        self.assertRaises(ValueError, int, '0B2', 2)
        self.assertRaises(ValueError, int, '0B02', 2)
        self.assertRaises(ValueError, int, '0o8', 8)
        self.assertRaises(ValueError, int, '0o08', 8)
        self.assertRaises(ValueError, int, '0O8', 8)
        self.assertRaises(ValueError, int, '0O08', 8)
        self.assertRaises(ValueError, int, '0xg', 16)
        self.assertRaises(ValueError, int, '0x0g', 16)
        self.assertRaises(ValueError, int, '0Xg', 16)
        self.assertRaises(ValueError, int, '0X0g', 16)

        # SF bug 1334662: int(string, base) wrong answers
        # Checks for proper evaluation of 2**32 + 1
        self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297)
        self.assertEqual(int('102002022201221111212', 3), 4294967297)
        self.assertEqual(int('10000000000000001', 4), 4294967297)
        self.assertEqual(int('32244002423142', 5), 4294967297)
        self.assertEqual(int('1550104015505', 6), 4294967297)
        self.assertEqual(int('211301422355', 7), 4294967297)
        self.assertEqual(int('40000000001', 8), 4294967297)
        self.assertEqual(int('12068657455', 9), 4294967297)
        self.assertEqual(int('4294967297', 10), 4294967297)
        self.assertEqual(int('1904440555', 11), 4294967297)
        self.assertEqual(int('9ba461595', 12), 4294967297)
        self.assertEqual(int('535a7988a', 13), 4294967297)
        self.assertEqual(int('2ca5b7465', 14), 4294967297)
        self.assertEqual(int('1a20dcd82', 15), 4294967297)
        self.assertEqual(int('100000001', 16), 4294967297)
        self.assertEqual(int('a7ffda92', 17), 4294967297)
        self.assertEqual(int('704he7g5', 18), 4294967297)
        self.assertEqual(int('4f5aff67', 19), 4294967297)
        self.assertEqual(int('3723ai4h', 20), 4294967297)
        self.assertEqual(int('281d55i5', 21), 4294967297)
        self.assertEqual(int('1fj8b185', 22), 4294967297)
        self.assertEqual(int('1606k7id', 23), 4294967297)
        self.assertEqual(int('mb994ah', 24), 4294967297)
        self.assertEqual(int('hek2mgm', 25), 4294967297)
        self.assertEqual(int('dnchbnn', 26), 4294967297)
        self.assertEqual(int('b28jpdn', 27), 4294967297)
        self.assertEqual(int('8pfgih5', 28), 4294967297)
        self.assertEqual(int('76beigh', 29), 4294967297)
        self.assertEqual(int('5qmcpqh', 30), 4294967297)
        self.assertEqual(int('4q0jto5', 31), 4294967297)
        self.assertEqual(int('4000001', 32), 4294967297)
        self.assertEqual(int('3aokq95', 33), 4294967297)
        self.assertEqual(int('2qhxjlj', 34), 4294967297)
        self.assertEqual(int('2br45qc', 35), 4294967297)
        self.assertEqual(int('1z141z5', 36), 4294967297)

Example 46

View license
    def test_integer(self):

        # Point of interest:
        #
        # On all *nix operating systems an int is 32-bits long on 32-bit systems and 64-bits long on 64-bit systems so
        # that you can count on this equality:
        #
        #   sys.maxint == sys.maxsize
        #
        # On Windows an int is always 32-bits long and you cannot count on the same equality. Specifically, on 64-bit
        # systems:
        #
        #   sys.maxint != sys.maxsize

        maxsize = sys.maxsize
        minsize = -(sys.maxsize - 1)

        # The Integer validator should convert values in the range of a Python long which has unlimited precision
        # Anecdotal evidence: This portion of the test checks 5-10 K integer values and runs for less than 2-3 seconds

        validator = validators.Integer()

        def test(integer):
            for s in str(integer), unicode(integer):
                value = validator.__call__(s)
                self.assertEqual(value, integer)
                self.assertIsInstance(value, long)
            self.assertEqual(validator.format(integer), unicode(integer))

        test(2L * minsize)
        test(minsize)
        test(-1)
        test(0)
        test(1)
        test(2L * maxsize)

        for i in xrange(0, 10000):
            test(randint(minsize, maxsize))

        # The Integer validator can impose a range restriction

        validator = validators.Integer(minimum=0)
        self.assertEqual(validator.__call__(0), 0)
        self.assertEqual(validator.__call__(2L * maxsize), 2L * maxsize)
        self.assertRaises(ValueError, validator.__call__, -1)

        validator = validators.Integer(minimum=1, maximum=maxsize)
        self.assertEqual(validator.__call__(1), 1)
        self.assertEqual(validator.__call__(maxsize), maxsize)
        self.assertRaises(ValueError, validator.__call__, 0)
        self.assertRaises(ValueError, validator.__call__, maxsize + 1)

        validator = validators.Integer(minimum=minsize, maximum=maxsize)
        self.assertEqual(validator.__call__(minsize), minsize)
        self.assertEqual(validator.__call__(0), 0)
        self.assertEqual(validator.__call__(maxsize), maxsize)
        self.assertRaises(ValueError, validator.__call__, minsize - 1L)
        self.assertRaises(ValueError, validator.__call__, maxsize + 1L)

        return

Example 47

Project: ironpython3
Source File: configparser.py
View license
    def _read(self, fp, fpname):
        """Parse a sectioned configuration file.

        Each section in a configuration file contains a header, indicated by
        a name in square brackets (`[]'), plus key/value options, indicated by
        `name' and `value' delimited with a specific substring (`=' or `:' by
        default).

        Values can span multiple lines, as long as they are indented deeper
        than the first line of the value. Depending on the parser's mode, blank
        lines may be treated as parts of multiline values or ignored.

        Configuration files may include comments, prefixed by specific
        characters (`#' and `;' by default). Comments may appear on their own
        in an otherwise empty line or may be entered in lines holding values or
        section names.
        """
        elements_added = set()
        cursect = None                        # None, or a dictionary
        sectname = None
        optname = None
        lineno = 0
        indent_level = 0
        e = None                              # None, or an exception
        for lineno, line in enumerate(fp, start=1):
            comment_start = sys.maxsize
            # strip inline comments
            inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
            while comment_start == sys.maxsize and inline_prefixes:
                next_prefixes = {}
                for prefix, index in inline_prefixes.items():
                    index = line.find(prefix, index+1)
                    if index == -1:
                        continue
                    next_prefixes[prefix] = index
                    if index == 0 or (index > 0 and line[index-1].isspace()):
                        comment_start = min(comment_start, index)
                inline_prefixes = next_prefixes
            # strip full line comments
            for prefix in self._comment_prefixes:
                if line.strip().startswith(prefix):
                    comment_start = 0
                    break
            if comment_start == sys.maxsize:
                comment_start = None
            value = line[:comment_start].strip()
            if not value:
                if self._empty_lines_in_values:
                    # add empty line to the value, but only if there was no
                    # comment on the line
                    if (comment_start is None and
                        cursect is not None and
                        optname and
                        cursect[optname] is not None):
                        cursect[optname].append('') # newlines added at join
                else:
                    # empty line marks end of value
                    indent_level = sys.maxsize
                continue
            # continuation line?
            first_nonspace = self.NONSPACECRE.search(line)
            cur_indent_level = first_nonspace.start() if first_nonspace else 0
            if (cursect is not None and optname and
                cur_indent_level > indent_level):
                cursect[optname].append(value)
            # a section header or option header?
            else:
                indent_level = cur_indent_level
                # is it a section header?
                mo = self.SECTCRE.match(value)
                if mo:
                    sectname = mo.group('header')
                    if sectname in self._sections:
                        if self._strict and sectname in elements_added:
                            raise DuplicateSectionError(sectname, fpname,
                                                        lineno)
                        cursect = self._sections[sectname]
                        elements_added.add(sectname)
                    elif sectname == self.default_section:
                        cursect = self._defaults
                    else:
                        cursect = self._dict()
                        self._sections[sectname] = cursect
                        self._proxies[sectname] = SectionProxy(self, sectname)
                        elements_added.add(sectname)
                    # So sections can't start with a continuation line
                    optname = None
                # no section header in the file?
                elif cursect is None:
                    raise MissingSectionHeaderError(fpname, lineno, line)
                # an option line?
                else:
                    mo = self._optcre.match(value)
                    if mo:
                        optname, vi, optval = mo.group('option', 'vi', 'value')
                        if not optname:
                            e = self._handle_error(e, fpname, lineno, line)
                        optname = self.optionxform(optname.rstrip())
                        if (self._strict and
                            (sectname, optname) in elements_added):
                            raise DuplicateOptionError(sectname, optname,
                                                       fpname, lineno)
                        elements_added.add((sectname, optname))
                        # This check is fine because the OPTCRE cannot
                        # match if it would set optval to None
                        if optval is not None:
                            optval = optval.strip()
                            cursect[optname] = [optval]
                        else:
                            # valueless option handling
                            cursect[optname] = None
                    else:
                        # a non-fatal parsing error occurred. set up the
                        # exception but keep going. the exception will be
                        # raised at the end of the file and will contain a
                        # list of all bogus lines
                        e = self._handle_error(e, fpname, lineno, line)
        # if any parsing errors occurred, raise an exception
        if e:
            raise e
        self._join_multiline_values()

Example 48

Project: ocf
Source File: helper.py
View license
def range_to_match_struct(rangeFS):
    '''
    Convert a FlowSpace element that has range for each of its fields to a list of openflow
    match structs
    @param rangeFS: flowpsace description in range format to be converted to OF match struct
    @type rangeFS: a supeclass of OpenFlow class
    @return: a list of strings corresponding to the equivalent match struct elements
    '''
    match = {}
    for attr_name, (to_str, from_str, width, om_name, of_name) in om_ch_translate.attr_funcs.items():
        om_start = "%s_s" % om_name
        om_end = "%s_e" % om_name
        match[of_name] = []
        # Some value must be within the boundaries
        if (getattr(rangeFS,om_start) > 0 or getattr(rangeFS,om_end) < 2**width-1):
            # Same value
            if (getattr(rangeFS,om_start) == getattr(rangeFS,om_end)):
                match[of_name].append(to_str(getattr(rangeFS,om_start)))
            else:
                # Ports
                if (attr_name == "nw_src" or attr_name == "nw_dst"):
                    ips = getattr(rangeFS,om_start)
                    ipe = getattr(rangeFS,om_end)
                    while (ips <= ipe):
                        for i in range(1,32):
                            if not ((ips | (2**i - 1 )) < ipe and (ips % 2**i)==0) :
                                obtained_match = "%s/%d"%(to_str(ips),33-i)
                                match[of_name].append(obtained_match)
                                ips = (ips| (2**(i-1) - 1 )) + 1
                                break
                else:
                    # If not full range, check that range is not too big
                    if not check_full_range(om_name, getattr(rangeFS,om_start), getattr(rangeFS,om_end)):
                        # Different factor for 32b or 64b OS's
                        factor_avoid_overflow = 1
                        # A limited number of rules should be set in FlowVisor avoiding
                        # overflow on its Java heap space (Xms: 100M, Xmx: 1000M currently)
                        # and also avoiding a lot of time processing (around 11 minutes now)
                        import sys
                        if (sys.maxsize <= 2**31-1):
                            factor_avoid_overflow = 1/5e6 # Allows circa 429 MACs
                        elif (sys.maxsize <= 2**63-1):
                            factor_avoid_overflow = 1/2e16 # Allows circa 461 MACs, e.g. [00:..:00, 00:..:FF]

                        # Avoid huge ranges of numbers (e.g. MACs) or to prevent Java heap space problems
                        # The whole range of VLANs is permitted
                        if (getattr(rangeFS,om_end)+1-getattr(rangeFS,om_start) > (sys.maxsize*factor_avoid_overflow) and om_name != "vlan_id"):
                            range_too_big = True
                            exception_range = "[%s, %s]" % (str(om_start), str(om_end))
                            raise Exception("Range too big for values '%s'" % exception_range)
                        # Compute range otherwise
                        else:
                            for value in range(getattr(rangeFS,om_start), getattr(rangeFS, om_end)+1):
                                match[of_name].append(to_str(value))

    #Now try to combine different of_name(s) together:
    all_match = [""]
    for key in match.keys():
        new_match = []
        for value in match[key]:
            for elem in all_match:
                if (elem == ""):
                    new_match.append("%s=%s"%(key,value))                    
                else:
                    new_match.append("%s,%s=%s"%(elem,key,value))
        if len(match[key]) > 0:
            all_match = new_match

    return all_match

Example 49

Project: tingbot-python
Source File: graphics.py
View license
    def text(self, string, xy=None, color='grey', align='center', font=None, font_size=32, 
             antialias=None, max_width=sys.maxsize, max_height=sys.maxsize, max_lines=sys.maxsize):
        """
        Draws text to the surface.

        Args:
            string: The text to draw.
            xy (tuple): The position (x, y) to draw the text, as measured from the top-left.
            color (tuple or str): The color (r, g, b) or color name.
            align (str): How to align the text relative to `xy`, or relative to the drawing surface
                if `xy` is None. Defaults to 'center'.
            font (str): The filename of the font to use.
            font_size (int): The size to render the font.
            antialias (bool): Set to false to draw pixel fonts.
            max_width (int): The maximum width of the text in pixels.
                If `xy` is not specified, defaults to the width of the drawing surface. Otherwise,
                defaults to unlimited.
            max_height (int): The maximum height of the text in pixels.
                If `xy` is not specified, defaults to the width of the drawing surface. Otherwise,
                defaults to unlimited.
            max_lines (int): The maximum number of lines to use. Set to 1 to draw a single line
                of text. By default, unlimited.
        """
        if xy is None:
            if max_width == sys.maxsize:
                max_width = self.width
            if max_height == sys.maxsize:
                max_height = self.height

        text_image = Image.from_text(
            string,
            color=color,
            font=font,
            font_size=font_size,
            antialias=antialias,
            max_lines=max_lines,
            max_width=max_width,
            max_height=max_height,
            align=_anchor(align)[0])

        self.image(text_image, xy=xy, align=align, scale=1)

Example 50

Project: tingbot-python
Source File: graphics.py
View license
    def image(self, image, xy=None, scale='shrinkToFit', alpha=1.0, align='center',
              max_width=sys.maxsize, max_height=sys.maxsize, raise_error=True):
        """screen.image(image, xy=None, scale='shrinkToFit', alpha=1.0, align='center', max_width=sys.maxsize, max_height=sys.maxsize, raise_error=True)

        Draws an image to the screen.

        Args:
            image (str or Image): A filename, URL or `Image` object to draw. If `image` is
                a URL, then it will attempt to download and display it.
            xy (tuple): The position (x, y) to draw the text, as measured from the top-left.
            scale (str or number): a number that changes the size of the image e.g. scale=2
                makes the image bigger, scale=0.5 makes the image smaller. There are also
                special values 'fit' and 'fill', which will fit or fill the image according
                to max_width and max_height. Defaults to 'shrinkToFit', which will fit an image 
                without enlarging.
            alpha (number): The opacity of the image - 0.0 means fully transparent, 1.0 is fully
                opaque.
            max_width (int): When `scale` is 'fit', 'fill', 'shrinkToFit' used to size the image.
            max_height (int): When `scale` is 'fit', 'fill', 'shrinkToFit' used to size the image.
            raise_error (bool): When loading an image from a URL, whether to raise an error if
                loading fails. Defaults to True. If false, a placeholder image will be substituted.

        Images can be animated GIFs. Draw them in a draw() function to see them animate.

        Images referred to by filename or URL are cached, so this can be called in a loop without
        performance concerns.

        Raises:
            requests.exceptions.RequestException: The image couldn't be loaded from URL.
        """

        if isinstance(image, basestring):
            try:
                image = image_cache.get_image(image)
            except IOError:
                if raise_error:
                    raise
                else:
                    image = image_cache.get_image(broken_image_file)

        if hasattr(image, 'surface'):
            image_size = image.size
            surface = image.surface
        else:
            # maybe the caller passed `image` as a pygame surface
            surface = image
            image_size = surface.get_size()

        if scale in ('fit', 'fill', 'shrinkToFit'):
            if max_width == sys.maxsize:
                max_width = self.width
            if max_height == sys.maxsize:
                max_height = self.height

            fit_scale = min(max_width / image_size[0], max_height / image_size[1])
            fill_scale = max(max_width / image_size[0], max_height / image_size[1])

            if scale == 'shrinkToFit':
                if fit_scale < 1:
                    scale = fit_scale
                else:
                    scale = 1
            elif scale == 'fit':
                scale = fit_scale
            elif scale == 'fill':
                scale = fill_scale

        scale = _scale(scale)

        # blit_surface is a temporary variable to minimise copying on each tranformation
        blit_surface = surface

        if scale != (1, 1):
            image_size = _xy_multiply(image_size, scale)
            image_size = tuple(int(d) for d in image_size)
            try:
                blit_surface = pygame.transform.smoothscale(surface, image_size)
            except ValueError:
                blit_surface = pygame.transform.scale(surface, image_size)

        if alpha < 1.0:
            # only copy the surface if required
            if blit_surface is surface:
                blit_surface = surface.copy()

            # multipling the pixels' color components with white does nothing, so this only
            # changes the alpha of the image
            blit_surface.fill((255, 255, 255, alpha*255), None, pygame.BLEND_RGBA_MULT)

        xy = _topleft_from_aligned_xy(xy, align, image_size, self.size)

        self.surface.blit(blit_surface, xy)