Python sys.maxsize() Examples

The following are 30 code examples of sys.maxsize(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: decorators.py    From ratelimit with MIT License 6 votes vote down vote up
def __init__(self, calls=15, period=900, clock=now(), raise_on_limit=True):
        '''
        Instantiate a RateLimitDecorator with some sensible defaults. By
        default the Twitter rate limiting window is respected (15 calls every
        15 minutes).

        :param int calls: Maximum function invocations allowed within a time period.
        :param float period: An upper bound time period (in seconds) before the rate limit resets.
        :param function clock: An optional function retuning the current time.
        :param bool raise_on_limit: A boolean allowing the caller to avoiding rasing an exception.
        '''
        self.clamped_calls = max(1, min(sys.maxsize, floor(calls)))
        self.period = period
        self.clock = clock
        self.raise_on_limit = raise_on_limit

        # Initialise the decorator state.
        self.last_reset = clock()
        self.num_calls = 0

        # Add thread safety.
        self.lock = threading.RLock() 
Example #2
Source File: generator.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def _make_boundary(cls, text=None):
        # Craft a random boundary.  If text is given, ensure that the chosen
        # boundary doesn't appear in the text.
        token = random.randrange(sys.maxsize)
        boundary = ('=' * 15) + (_fmt % token) + '=='
        if text is None:
            return boundary
        b = boundary
        counter = 0
        while True:
            cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
            if not cre.search(text):
                break
            b = boundary + '.' + str(counter)
            counter += 1
        return b 
Example #3
Source File: _sre.py    From jawfish with MIT License 6 votes vote down vote up
def findall(self, string, pos=0, endpos=sys.maxsize):
        """Return a list of all non-overlapping matches of pattern in string."""
        matchlist = []
        state = _State(string, pos, endpos, self.flags)
        while state.start <= state.end:
            state.reset()
            state.string_position = state.start
            if not state.search(self._code):
                break
            match = SRE_Match(self, state)
            if self.groups == 0 or self.groups == 1:
                item = match.group(self.groups)
            else:
                item = match.groups("")
            matchlist.append(item)
            if state.string_position == state.start:
                state.start += 1
            else:
                state.start = state.string_position
        return matchlist 
Example #4
Source File: matplotlib_trading_chart.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def _render_trades(self, step_range, trades):
        trades = [trade for sublist in trades.values() for trade in sublist]

        for trade in trades:
            if trade.step in range(sys.maxsize)[step_range]:
                date = self.df.index.values[trade.step]
                close = self.df['close'].values[trade.step]
                color = 'green'

                if trade.side is TradeSide.SELL:
                    color = 'red'

                self.price_ax.annotate(' ', (date, close),
                                       xytext=(date, close),
                                       size="large",
                                       arrowprops=dict(arrowstyle='simple', facecolor=color)) 
Example #5
Source File: reference_direction.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def map_onto_unit_simplex(rnd, method):
    n_points, n_dim = rnd.shape

    if method == "sum":
        ret = rnd / rnd.sum(axis=1)[:, None]

    elif method == "kraemer":
        M = sys.maxsize

        rnd *= M
        rnd = rnd[:, :n_dim - 1]
        rnd = np.column_stack([np.zeros(n_points), rnd, np.full(n_points, M)])

        rnd = np.sort(rnd, axis=1)

        ret = np.full((n_points, n_dim), np.nan)
        for i in range(1, n_dim + 1):
            ret[:, i - 1] = rnd[:, i] - rnd[:, i - 1]
        ret /= M

    else:
        raise Exception("Invalid unit simplex mapping!")

    return ret 
Example #6
Source File: generator.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _make_boundary(cls, text=None):
        # Craft a random boundary.  If text is given, ensure that the chosen
        # boundary doesn't appear in the text.
        token = random.randrange(sys.maxsize)
        boundary = ('=' * 15) + (_fmt % token) + '=='
        if text is None:
            return boundary
        b = boundary
        counter = 0
        while True:
            cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
            if not cre.search(text):
                break
            b = boundary + '.' + str(counter)
            counter += 1
        return b 
Example #7
Source File: Dijsktra Algo.py    From Advanced-Data-Structures-with-Python with MIT License 6 votes vote down vote up
def dijkstra(self, src):
        dist = [sys.maxsize] * self.vert
        dist[src] = 0
        self.pathlist[0].append(src)
        sptSet = [False] * self.vert
        for cout in range(self.vert):
            u = self.findmindist(dist, sptSet)
            #if u == 225 :
            #  break
            sptSet[u] = True
            for v in range(self.vert):
                if self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]:
                        dist[v] = dist[u] + self.graph[u][v]
                        self.pathlist[v] = self.pathlist[u] + [v]
                        #print(dist,"Changing")
        #print("bhavin")
        self.printshortestgraph(dist) 
Example #8
Source File: generator.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _make_boundary(cls, text=None):
        # Craft a random boundary.  If text is given, ensure that the chosen
        # boundary doesn't appear in the text.
        token = random.randrange(sys.maxsize)
        boundary = ('=' * 15) + (_fmt % token) + '=='
        if text is None:
            return boundary
        b = boundary
        counter = 0
        while True:
            cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
            if not cre.search(text):
                break
            b = boundary + '.' + str(counter)
            counter += 1
        return b 
Example #9
Source File: DijkstraShortestReach.py    From Advanced-Data-Structures-with-Python with MIT License 6 votes vote down vote up
def printshortestgraph(self, dist,src):
        f = open('somefile.txt', 'a')
        #print("Vertex tDistance from Source")
        for node in range(self.vert):
          if(node == src):
            continue
          if(node == self.vert - 1):
            if(dist[node] != sys.maxsize):
                print(dist[node],file = f)
            else:
                print(-1,file = f)
          elif(dist[node] != sys.maxsize):
            #print("From 0 to ", node ," - >",dist[node],end = " ")
            #print(self.pathlist[node])
            print(dist[node],end = ' ',file = f)
            #f.write(dist[node] + " ")
          elif(dist[node] == sys.maxsize):
            #print("From 0 to ", node ," - >",-1,end = " ")
            print(-1,end = ' ',file = f)
            #f.write(-1 + " ")
        #print('\n')
        #f.write("\n") 
Example #10
Source File: platform.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 6 votes vote down vote up
def platform():
    ret = {
        "arch": sys.maxsize > 2**32 and "x64" or "x86",
    }

    if xbmc.getCondVisibility("system.platform.android"):
        ret["os"] = "android"
        if "arm" in os.uname()[4]:
            ret["arch"] = "arm"
    elif xbmc.getCondVisibility("system.platform.linux"):
        ret["os"] = "linux"
        if "arm" in os.uname()[4]:
            ret["arch"] = "arm"
    elif xbmc.getCondVisibility("system.platform.xbox"):
        system_platform = "xbox"
        ret["arch"] = ""
    elif xbmc.getCondVisibility("system.platform.windows"):
        ret["os"] = "windows"
    elif xbmc.getCondVisibility("system.platform.osx"):
        ret["os"] = "darwin"
    elif xbmc.getCondVisibility("system.platform.ios"):
        ret["os"] = "ios"
        ret["arch"] = "arm"

    return ret 
Example #11
Source File: pc_util.py    From H3DNet with MIT License 6 votes vote down vote up
def bbox_corner_dist_measure(crnr1, crnr2):
    """ compute distance between box corners to replace iou
    Args:
        crnr1, crnr2: Nx3 points of box corners in camera axis (y points down)
        output is a scalar between 0 and 1        
    """
    
    dist = sys.maxsize
    for y in range(4):
        rows = ([(x+y)%4 for x in range(4)] + [4+(x+y)%4 for x in range(4)])
        d_ = np.linalg.norm(crnr2[rows, :] - crnr1, axis=1).sum() / 8.0            
        if d_ < dist:
            dist = d_

    u = sum([np.linalg.norm(x[0,:] - x[6,:]) for x in [crnr1, crnr2]])/2.0

    measure = max(1.0 - dist/u, 0)
    print(measure)
    
    
    return measure 
Example #12
Source File: base.py    From linter-pylama with MIT License 6 votes vote down vote up
def leave_module(self, node): # pylint: disable=unused-argument
        for all_groups in six.itervalues(self._bad_names):
            if len(all_groups) < 2:
                continue
            groups = collections.defaultdict(list)
            min_warnings = sys.maxsize
            for group in six.itervalues(all_groups):
                groups[len(group)].append(group)
                min_warnings = min(len(group), min_warnings)
            if len(groups[min_warnings]) > 1:
                by_line = sorted(groups[min_warnings],
                                 key=lambda group: min(warning[0].lineno for warning in group))
                warnings = itertools.chain(*by_line[1:])
            else:
                warnings = groups[min_warnings][0]
            for args in warnings:
                self._raise_name_warning(*args) 
Example #13
Source File: mx_gate.py    From mx with GNU General Public License v2.0 6 votes vote down vote up
def parse_tags_argument(tags_arg, exclude):
    pattern = re.compile(r"^(?P<tag>[^:]*)(?::(?P<from>\d+):(?P<to>\d+)?)?$")
    tags = tags_arg.split(',')
    Task.tags = []
    for tag_spec in tags:
        m = pattern.match(tag_spec)
        if not m:
            mx.abort('--tags option requires the format `name[:from:[to]]`: {0}'.format(tag_spec))
        (tag, t_from, t_to) = m.groups()
        if t_from:
            if exclude:
                mx.abort('-x option cannot be used tag ranges: {0}'.format(tag_spec))
            frm = int(t_from)
            to = int(t_to) if t_to else sys.maxsize
            # insert range tuple
            Task.tags_range[tag] = (frm, to)
            # sanity check
            if to <= frm:
                mx.abort('`from` must be less than `to` for tag ranges: {0}'.format(tag_spec))
            # init counter
            Task.tags_count[tag] = 0
        Task.tags.append(tag) 
Example #14
Source File: rrule.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, item):
        if self._cache_complete:
            return self._cache[item]
        elif isinstance(item, slice):
            if item.step and item.step < 0:
                return list(iter(self))[item]
            else:
                return list(itertools.islice(self,
                                             item.start or 0,
                                             item.stop or sys.maxsize,
                                             item.step or 1))
        elif item >= 0:
            gen = iter(self)
            try:
                for i in range(item+1):
                    res = advance_iterator(gen)
            except StopIteration:
                raise IndexError
            return res
        else:
            return list(iter(self))[item] 
Example #15
Source File: generate.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def generate(grammar, start=None, depth=None, n=None):
    """
    Generates an iterator of all sentences from a CFG.

    :param grammar: The Grammar used to generate sentences.
    :param start: The Nonterminal from which to start generate sentences.
    :param depth: The maximal depth of the generated tree.
    :param n: The maximum number of sentences to return.
    :return: An iterator of lists of terminal tokens.
    """
    if not start:
        start = grammar.start()
    if depth is None:
        depth = sys.maxsize

    iter = _generate_all(grammar, [start], depth)

    if n:
        iter = itertools.islice(iter, n)

    return iter 
Example #16
Source File: DijkstraShortestReach.py    From Advanced-Data-Structures-with-Python with MIT License 6 votes vote down vote up
def dijkstra(self, src):
        dist = [sys.maxsize] * self.vert
        src = src - 1
        dist[src] = 0
        self.pathlist[0].append(src)
        sptSet = [False] * self.vert
        for cout in range(self.vert):
            u = self.findmindist(dist, sptSet)
            #if u == 225 :
            #  break
            sptSet[u] = True
            for v in range(self.vert):
                if self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]:
                        dist[v] = dist[u] + self.graph[u][v]
                        self.pathlist[v] = self.pathlist[u] + [v]
                        #print(dist,"Changing")
        #print("bhavin")
        self.printshortestgraph(dist,src) 
Example #17
Source File: lsof.py    From moler with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _proper_position_value(self, header_index, value_position):
        ret = False
        if header_index < len(self._headers):
            current_header_pos = self._header_pos[header_index]
            if current_header_pos == value_position:
                ret = True
            else:
                prev_header_pos = -1
                if header_index > 0:
                    prev_header_pos = self._header_pos[header_index - 1]
                next_header_pos = sys.maxsize  # larger value than any column
                if header_index < len(self._headers) - 1:
                    next_header_pos = self._header_pos[header_index] + len(self._headers[header_index])
                if value_position > prev_header_pos and value_position < next_header_pos:
                    ret = True
        return ret 
Example #18
Source File: ratelimit.py    From uplink with MIT License 6 votes vote down vote up
def __init__(
        self,
        calls=15,
        period=900,
        raise_on_limit=False,
        group_by=BY_HOST_AND_PORT,
        clock=now,
    ):
        self._max_calls = max(1, min(sys.maxsize, math.floor(calls)))
        self._period = period
        self._clock = clock
        self._limiter_cache = {}
        self._group_by = utils.no_op if group_by is None else group_by

        if utils.is_subclass(raise_on_limit, Exception) or isinstance(
            raise_on_limit, Exception
        ):
            self._create_limit_reached_exception = raise_on_limit
        elif raise_on_limit:
            self._create_limit_reached_exception = (
                self._create_rate_limit_exceeded
            )
        else:
            self._create_limit_reached_exception = None 
Example #19
Source File: repository.py    From git-pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def revs(self, branch='master', limit=None, skip=None, num_datapoints=None):
        """
        Returns a dataframe of all revision tags and their timestamps. It will have the columns:

         * date
         * rev

        :param branch: (optional, default 'master') the branch to work in
        :param limit: (optional, default None), the maximum number of revisions to return, None for no limit
        :param skip: (optional, default None), the number of revisions to skip. Ex: skip=2 returns every other revision, None for no skipping.
        :param num_datapoints: (optional, default=None) if limit and skip are none, and this isn't, then num_datapoints evenly spaced revs will be used
        :return: DataFrame

        """

        if limit is None and skip is None and num_datapoints is not None:
            limit = sum(1 for _ in self.repo.iter_commits())
            skip = int(float(limit) / num_datapoints)
        else:
            if limit is None:
                limit = sys.maxsize
            elif skip is not None:
                limit = limit * skip

        ds = [[x.committed_date, x.name_rev.split(' ')[0]] for x in self.repo.iter_commits(branch, max_count=limit)]
        df = DataFrame(ds, columns=['date', 'rev'])

        if skip is not None:
            if skip == 0:
                skip = 1

            if df.shape[0] >= skip:
                df = df.ix[range(0, df.shape[0], skip)]
                df.reset_index()
            else:
                df = df.ix[[0]]
                df.reset_index()

        return df 
Example #20
Source File: es_utils_2_3_tests.py    From seqr with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_sort(self):
        search_model = VariantSearch.objects.create(search={
            'annotations': {'frameshift': ['frameshift_variant']},
        })
        results_model = VariantSearchResults.objects.create(variant_search=search_model)
        results_model.families.set(Family.objects.filter(project__guid='R0001_1kg'))

        variants, _ = get_es_variants(results_model, sort='primate_ai', num_results=2)
        self.assertExecutedSearch(filters=[ANNOTATION_QUERY], sort=[
            {'primate_ai_score': {'order': 'desc', 'unmapped_type': 'float'}}, 'xpos'])
        self.assertEqual(variants[0]['_sort'][0], maxsize)
        self.assertEqual(variants[1]['_sort'][0], -1)

        variants, _ = get_es_variants(results_model, sort='gnomad', num_results=2)
        self.assertExecutedSearch(filters=[ANNOTATION_QUERY], sort=[
            {
                '_script': {
                    'type': 'number',
                    'script': {
                        'params': {'field': 'gnomad_genomes_AF'},
                        'source': mock.ANY,
                    }
                }
            }, 'xpos'])
        self.assertEqual(variants[0]['_sort'][0], 0.00012925741614425127)
        self.assertEqual(variants[1]['_sort'][0], maxsize)

        variants, _ = get_es_variants(results_model, sort='in_omim', num_results=2)
        self.assertExecutedSearch(filters=[ANNOTATION_QUERY], sort=[
            {
                '_script': {
                    'type': 'number',
                    'order': 'desc',
                    'script': {
                        'params': {
                            'omim_gene_ids': ['ENSG00000223972', 'ENSG00000243485', 'ENSG00000268020']
                        },
                        'source': mock.ANY,
                    }
                }
            }, 'xpos']) 
Example #21
Source File: TradingChart.py    From RLTrader with GNU General Public License v3.0 5 votes vote down vote up
def _render_trades(self, step_range, trades):
        for trade in trades:
            if trade['step'] in range(sys.maxsize)[step_range]:
                date = self.df['Date'].values[trade['step']]
                close = self.df['Close'].values[trade['step']]

                if trade['type'] == 'buy':
                    color = 'g'
                else:
                    color = 'r'

                self.price_ax.annotate(' ', (date, close),
                                       xytext=(date, close),
                                       size="large",
                                       arrowprops=dict(arrowstyle='simple', facecolor=color)) 
Example #22
Source File: py3_test_grammar.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testPlainIntegers(self):
        self.assertEquals(type(000), type(0))
        self.assertEquals(0xff, 255)
        self.assertEquals(0o377, 255)
        self.assertEquals(2147483647, 0o17777777777)
        self.assertEquals(0b1001, 9)
        # "0x" is not a valid literal
        self.assertRaises(SyntaxError, eval, "0x")
        from sys import maxsize
        if maxsize == 2147483647:
            self.assertEquals(-2147483647-1, -0o20000000000)
            # XXX -2147483648
            self.assert_(0o37777777777 > 0)
            self.assert_(0xffffffff > 0)
            self.assert_(0b1111111111111111111111111111111 > 0)
            for s in ('2147483648', '0o40000000000', '0x100000000',
                      '0b10000000000000000000000000000000'):
                try:
                    x = eval(s)
                except OverflowError:
                    self.fail("OverflowError on huge integer literal %r" % s)
        elif maxsize == 9223372036854775807:
            self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
            self.assert_(0o1777777777777777777777 > 0)
            self.assert_(0xffffffffffffffff > 0)
            self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
            for s in '9223372036854775808', '0o2000000000000000000000', \
                     '0x10000000000000000', \
                     '0b100000000000000000000000000000000000000000000000000000000000000':
                try:
                    x = eval(s)
                except OverflowError:
                    self.fail("OverflowError on huge integer literal %r" % s)
        else:
            self.fail('Weird maxsize value %r' % maxsize) 
Example #23
Source File: test_editdistance.py    From symspellpy with MIT License 5 votes vote down vote up
def test_damerau_osa_match_ref_max_huge(self):
        max_distance = sys.maxsize

        comparer = DamerauOsa()
        for s1 in self.test_strings:
            for s2 in self.test_strings:
                self.assertEqual(get_damerau_osa(s1, s2, max_distance),
                                 comparer.distance(s1, s2, max_distance)) 
Example #24
Source File: test_editdistance.py    From symspellpy with MIT License 5 votes vote down vote up
def test_levenshtein_match_ref_max_huge(self):
        max_distance = sys.maxsize

        comparer = Levenshtein()
        for s1 in self.test_strings:
            for s2 in self.test_strings:
                self.assertEqual(get_levenshtein(s1, s2, max_distance),
                                 comparer.distance(s1, s2, max_distance)) 
Example #25
Source File: test_symspellpy.py    From symspellpy with MIT License 5 votes vote down vote up
def test_add_additional_counts_should_not_overflow(self):
        sym_spell = SymSpell()
        word = "hello"
        sym_spell.create_dictionary_entry(word, sys.maxsize - 10)
        result = sym_spell.lookup(word, Verbosity.TOP)
        count = result[0].count if len(result) == 1 else 0
        self.assertEqual(sys.maxsize - 10, count)

        sym_spell.create_dictionary_entry(word, 11)
        result = sym_spell.lookup(word, Verbosity.TOP)
        count = result[0].count if len(result) == 1 else 0
        self.assertEqual(sys.maxsize, count) 
Example #26
Source File: tools.py    From python-esppy with Apache License 2.0 5 votes vote down vote up
def darkest(self):
        color = None
        if len(self._colors) > 0:
            minLuma = sys.maxsize
            index = -1
            for i,l in enumerate(self._luma):
                if l < minLuma:
                    minLuma = l
                    index = i

            if index >= 0:
                color = self._colors[index]

        return(color) 
Example #27
Source File: tools.py    From python-esppy with Apache License 2.0 5 votes vote down vote up
def getClosestTo(self,luma):
        color = None
        if len(self._colors) > 0:
            index = -1
            diff = sys.maxsize
            for i,l in enumerate(self._luma):
                d = abs(luma - l)
                if d < diff:
                    diff = d
                    index = i

            if index >= 0:
                color = self._colors[index]

        return(color) 
Example #28
Source File: test_fastdivmod.py    From hacking-tools with MIT License 5 votes vote down vote up
def test_correctness_big_numbers():
    random.seed(1)
    for _ in range(100):
        x = random.randint(1, 2**32)
        for base in (2, 10, 255, 256):
            for chunk in (base, base**2, base**3, base**4):
                yield runner, x, base, chunk

    for _ in range(10):
        x = random.randint(1, 2**32) * sys.maxsize ** 6
        for base in (2, 10, 255, 256):
            for chunk in (base, base**2, base**3, base**4):
                yield runner, x, base, chunk 
Example #29
Source File: test_bigrange.py    From hacking-tools with MIT License 5 votes vote down vote up
def test_bignum():
    # xrange(start, stop) raises OverflowError in py2.7
    start = sys.maxsize
    stop = sys.maxsize + 5

    l = list(sre_yield._bigrange(start, stop))
    assert len(l) == 5 
Example #30
Source File: test_sre_yield.py    From hacking-tools with MIT License 5 votes vote down vote up
def testCanSliceGiantValues(self):
        v = sre_yield.AllStrings('.+')
        self.assertGreater(v.__len__(), sys.maxsize)
        self.assertEqual(['\x00', '\x01'], list(v[:2]))