Python sys.maxint() Examples

The following are 30 code examples of sys.maxint(). 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: httpserver.py    From mishkal with GNU General Public License v3.0 8 votes vote down vote up
def _auto_ssl_context():
        import OpenSSL, time, random
        pkey = OpenSSL.crypto.PKey()
        pkey.generate_key(OpenSSL.crypto.TYPE_RSA, 768)

        cert = OpenSSL.crypto.X509()

        cert.set_serial_number(random.randint(0, sys.maxint))
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)
        cert.get_subject().CN = '*'
        cert.get_subject().O = 'Dummy Certificate'
        cert.get_issuer().CN = 'Untrusted Authority'
        cert.get_issuer().O = 'Self-Signed'
        cert.set_pubkey(pkey)
        cert.sign(pkey, 'md5')

        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey(pkey)
        ctx.use_certificate(cert)

        return ctx 
Example #2
Source File: generator.py    From meddle with MIT License 6 votes vote down vote up
def _make_boundary(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.maxint)
    boundary = ('=' * 15) + (_fmt % token) + '=='
    if text is None:
        return boundary
    b = boundary
    counter = 0
    while True:
        cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
        if not cre.search(text):
            break
        b = boundary + '.' + str(counter)
        counter += 1
    return b 
Example #3
Source File: posixemulation.py    From cutout with MIT License 6 votes vote down vote up
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
Example #4
Source File: AnalyzerCompareCommand.py    From llvm-zorg with Apache License 2.0 6 votes vote down vote up
def __init__(self):
      buildstep.LogLineObserver.__init__(self)

      # Counts of various reports.
      self.num_reports = None
      self.num_added = 0
      self.num_removed = 0
      self.num_changed = 0

      # Reports to notify the user about; a list of tuples of (title,
      # name, html-report).
      self.reports = []

      # Lines we couldn't parse.
      self.invalid_lines = []

      # Make sure we get all the data.
      self.setMaxLineLength(sys.maxint) 
Example #5
Source File: generator.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _make_boundary(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.maxint)
    boundary = ('=' * 15) + (_fmt % token) + '=='
    if text is None:
        return boundary
    b = boundary
    counter = 0
    while True:
        cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
        if not cre.search(text):
            break
        b = boundary + '.' + str(counter)
        counter += 1
    return b 
Example #6
Source File: posixemulation.py    From lambda-packs with MIT License 6 votes vote down vote up
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
Example #7
Source File: ipfix.py    From exaddos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def read_data (self,setid,epoch,data):
		# unknown template, ignore it !
		if setid not in self.template:
			return

		extracted = {'epoch':epoch,'flows':1}
		format = self.template[setid]

		for what in format:
			offset,size = format[what]
			extracted[NAME[what]], = struct.unpack(CONVERT[(what,size)],data[offset:offset+size])

		# # reports the data decoding rate per thread
		# self.decoded +=1
		# if not self.decoded % 1000:
		# 	print "id %d decoded %ld flows" % (self.id,self.decoded)
		# 	sys.stdout.flush()
		# 	if self.decoded == sys.maxint:
		# 		self.decoded = self.decoded % 1000

		self.callback(extracted) 
Example #8
Source File: BotDigger.py    From BotDigger with GNU General Public License v3.0 6 votes vote down vote up
def distanceDomain(domain, DomainDict, ccTldDict, tldDict):
	similarDomain = ""
	minDistance = sys.maxint
	level = domain.split(".")
	if len(level) <=1:
		return ("not a domain", sys.maxint)
	(domain2LD, domain3LD, domain2LDs, domain3LDs) = extractLevelDomain(domain, ccTldDict, tldDict)
	for popularDomain in DomainDict:
		distance = Levenshtein.distance(domain2LD.decode('utf-8'), popularDomain.decode('utf-8'))
		if distance < minDistance:
			minDistance = distance
			similarDomain = popularDomain
	#debug
	#sys.stdout.write("subdomain: %s, similarDomain: %s, minDistance: %d\n" % (subdomain, similarDomain, minDistance))
	if len(similarDomain) > 0:
		return (similarDomain, minDistance/float(len(similarDomain)))
	else:
		return (domain2LD, 0)

# check whether a domain contains invalid TLD 
Example #9
Source File: posixemulation.py    From jbox with MIT License 6 votes vote down vote up
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
Example #10
Source File: closetsum.py    From interview-with-python with MIT License 6 votes vote down vote up
def threeSumClosest(A, B):
    i , n = 0 , len(A)
    A = sorted(A)
    diff = sys.maxint
    close_sum = 0
    while i <= n-3:
        j , k = i+1 , n-1
        sum = A[i] + A[j] + A[k]
        if sum == B:
            return sum
        if diff > abs(sum - B):
            diff += abs(sum-B)
            close_sum = sum
        if sum < B:
            j += 1
        else:
            k -= 1
        i += 1
    return close_sum 
Example #11
Source File: server.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, interface_dict, rpc_prefix):

		mp_conf = {"use_bin_type":True}
		super().__init__(
				pack_params  = {
						"use_bin_type":True
					},
				# unpack_param = {
				# 		'raw'             : True,
				# 		'max_buffer_size' : sys.maxint,
				# 		'max_str_len'     : sys.maxint,
				# 		'max_bin_len'     : sys.maxint,
				# 		'max_array_len'   : sys.maxint,
				# 		'max_map_len'     : sys.maxint,
				# 		'max_ext_len'     : sys.maxint,
				# 	},
			)

		self.log = logging.getLogger("Main.{}-Interface".format(rpc_prefix))
		self.mdict = interface_dict
		self.log.info("Connection") 
Example #12
Source File: http.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def base36_to_int(s):
    """
    Converts a base 36 string to an ``int``. Raises ``ValueError` if the
    input won't fit into an int.
    """
    # To prevent overconsumption of server resources, reject any
    # base36 string that is long than 13 base36 digits (13 digits
    # is sufficient to base36-encode any 64-bit integer)
    if len(s) > 13:
        raise ValueError("Base36 input too large")
    value = int(s, 36)
    # ... then do a final check that the value will fit into an int to avoid
    # returning a long (#15067). The long type was removed in Python 3.
    if six.PY2 and value > sys.maxint:
        raise ValueError("Base36 input too large")
    return value 
Example #13
Source File: http.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def int_to_base36(i):
    """
    Converts an integer to a base36 string
    """
    char_set = '0123456789abcdefghijklmnopqrstuvwxyz'
    if i < 0:
        raise ValueError("Negative base36 conversion input.")
    if six.PY2:
        if not isinstance(i, six.integer_types):
            raise TypeError("Non-integer base36 conversion input.")
        if i > sys.maxint:
            raise ValueError("Base36 conversion input too large.")
    if i < 36:
        return char_set[i]
    b36 = ''
    while i != 0:
        i, n = divmod(i, 36)
        b36 = char_set[n] + b36
    return b36 
Example #14
Source File: util.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _num_version(libname):
            # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ]
            parts = libname.split(b".")
            nums = []
            try:
                while parts:
                    nums.insert(0, int(parts.pop()))
            except ValueError:
                pass
            return nums or [sys.maxint] 
Example #15
Source File: test_memfunctions.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_overflow(self):
        # string_at and wstring_at must use the Python calling
        # convention (which acquires the GIL and checks the Python
        # error flag).  Provoke an error and catch it; see also issue
        # #3554: <http://bugs.python.org/issue3554>
        self.assertRaises((OverflowError, MemoryError, SystemError),
                          lambda: wstring_at(u"foo", sys.maxint - 1))
        self.assertRaises((OverflowError, MemoryError, SystemError),
                          lambda: string_at("foo", sys.maxint - 1)) 
Example #16
Source File: inspect.py    From meddle with MIT License 5 votes vote down vote up
def cleandoc(doc):
    """Clean up indentation from docstrings.

    Any whitespace that can be uniformly removed from the second line
    onwards is removed."""
    try:
        lines = string.split(string.expandtabs(doc), '\n')
    except UnicodeError:
        return None
    else:
        # Find minimum indentation of any non-blank lines after first line.
        margin = sys.maxint
        for line in lines[1:]:
            content = len(string.lstrip(line))
            if content:
                indent = len(line) - content
                margin = min(margin, indent)
        # Remove indentation.
        if lines:
            lines[0] = lines[0].lstrip()
        if margin < sys.maxint:
            for i in range(1, len(lines)): lines[i] = lines[i][margin:]
        # Remove any trailing or leading blank lines.
        while lines and not lines[-1]:
            lines.pop()
        while lines and not lines[0]:
            lines.pop(0)
        return string.join(lines, '\n') 
Example #17
Source File: subprocess.py    From meddle with MIT License 5 votes vote down vote up
def __del__(self, _maxint=sys.maxint, _active=_active):
        if not self._child_created:
            # We didn't get to successfully create a child process.
            return
        # In case the child hasn't been waited on, check if it's done.
        self._internal_poll(_deadstate=_maxint)
        if self.returncode is None and _active is not None:
            # Child is still running, keep us alive until we can wait on it.
            _active.append(self) 
Example #18
Source File: mhlib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _parseindex(self, seq, all):
        """Internal: parse a message number (or cur, first, etc.)."""
        if isnumeric(seq):
            try:
                return int(seq)
            except (OverflowError, ValueError):
                return sys.maxint
        if seq in ('cur', '.'):
            return self.getcurrent()
        if seq == 'first':
            return all[0]
        if seq == 'last':
            return all[-1]
        if seq == 'next':
            n = self.getcurrent()
            i = bisect(all, n)
            try:
                return all[i]
            except IndexError:
                raise Error, "no next message"
        if seq == 'prev':
            n = self.getcurrent()
            i = bisect(all, n-1)
            if i == 0:
                raise Error, "no prev message"
            try:
                return all[i-1]
            except IndexError:
                raise Error, "no prev message"
        raise Error, None 
Example #19
Source File: subprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __del__(self, _maxint=sys.maxint):
        # If __init__ hasn't had a chance to execute (e.g. if it
        # was passed an undeclared keyword argument), we don't
        # have a _child_created attribute at all.
        if not self._child_created:
            # We didn't get to successfully create a child process.
            return
        # In case the child hasn't been waited on, check if it's done.
        self._internal_poll(_deadstate=_maxint)
        if self.returncode is None and _active is not None:
            # Child is still running, keep us alive until we can wait on it.
            _active.append(self) 
Example #20
Source File: subprocess.py    From meddle with MIT License 5 votes vote down vote up
def _cleanup():
    for inst in _active[:]:
        res = inst._internal_poll(_deadstate=sys.maxint)
        if res is not None and res >= 0:
            try:
                _active.remove(inst)
            except ValueError:
                # This can happen if two threads create a new Popen instance.
                # It's harmless that it was already removed, so ignore.
                pass
        else:
            print inst.args 
Example #21
Source File: mhlib.py    From meddle with MIT License 5 votes vote down vote up
def _parseindex(self, seq, all):
        """Internal: parse a message number (or cur, first, etc.)."""
        if isnumeric(seq):
            try:
                return int(seq)
            except (OverflowError, ValueError):
                return sys.maxint
        if seq in ('cur', '.'):
            return self.getcurrent()
        if seq == 'first':
            return all[0]
        if seq == 'last':
            return all[-1]
        if seq == 'next':
            n = self.getcurrent()
            i = bisect(all, n)
            try:
                return all[i]
            except IndexError:
                raise Error, "no next message"
        if seq == 'prev':
            n = self.getcurrent()
            i = bisect(all, n-1)
            if i == 0:
                raise Error, "no prev message"
            try:
                return all[i-1]
            except IndexError:
                raise Error, "no prev message"
        raise Error, None 
Example #22
Source File: __init__.py    From meddle with MIT License 5 votes vote down vote up
def __repr__(self):
        return "<%s '%s', handle %x at %x>" % \
               (self.__class__.__name__, self._name,
                (self._handle & (_sys.maxint*2 + 1)),
                id(self) & (_sys.maxint*2 + 1)) 
Example #23
Source File: inspect.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def cleandoc(doc):
    """Clean up indentation from docstrings.

    Any whitespace that can be uniformly removed from the second line
    onwards is removed."""
    try:
        lines = string.split(string.expandtabs(doc), '\n')
    except UnicodeError:
        return None
    else:
        # Find minimum indentation of any non-blank lines after first line.
        margin = sys.maxint
        for line in lines[1:]:
            content = len(string.lstrip(line))
            if content:
                indent = len(line) - content
                margin = min(margin, indent)
        # Remove indentation.
        if lines:
            lines[0] = lines[0].lstrip()
        if margin < sys.maxint:
            for i in range(1, len(lines)): lines[i] = lines[i][margin:]
        # Remove any trailing or leading blank lines.
        while lines and not lines[-1]:
            lines.pop()
        while lines and not lines[0]:
            lines.pop(0)
        return string.join(lines, '\n') 
Example #24
Source File: _abcoll.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _hash(self):
        """Compute the hash value of a set.

        Note that we don't define __hash__: not all sets are hashable.
        But if you define a hashable set type, its __hash__ should
        call this function.

        This must be compatible __eq__.

        All sets ought to compare equal if they contain the same
        elements, regardless of how they are implemented, and
        regardless of the order of the elements; so there's not much
        freedom for __eq__ or __hash__.  We match the algorithm used
        by the built-in frozenset type.
        """
        MAX = sys.maxint
        MASK = 2 * MAX + 1
        n = len(self)
        h = 1927868237 * (n + 1)
        h &= MASK
        for x in self:
            hx = hash(x)
            h ^= (hx ^ (hx << 16) ^ 89869747)  * 3644798167
            h &= MASK
        h = h * 69069 + 907133923
        h &= MASK
        if h > MAX:
            h -= MASK + 1
        if h == -1:
            h = 590923713
        return h 
Example #25
Source File: gzip.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def readline(self, size=-1):
        if size < 0:
            # Shortcut common case - newline found in buffer.
            offset = self.offset - self.extrastart
            i = self.extrabuf.find('\n', offset) + 1
            if i > 0:
                self.extrasize -= i - offset
                self.offset += i - offset
                return self.extrabuf[offset: i]

            size = sys.maxint
            readsize = self.min_readsize
        else:
            readsize = size
        bufs = []
        while size != 0:
            c = self.read(readsize)
            i = c.find('\n')

            # We set i=size to break out of the loop under two
            # conditions: 1) there's no newline, and the chunk is
            # larger than size, or 2) there is a newline, but the
            # resulting line would be longer than 'size'.
            if (size <= i) or (i == -1 and len(c) > size):
                i = size - 1

            if i >= 0 or c == '':
                bufs.append(c[:i + 1])    # Add portion of last chunk
                self._unread(c[i + 1:])   # Push back rest of chunk
                break

            # Append chunk to list, decrease 'size',
            bufs.append(c)
            size = size - len(c)
            readsize = min(size, readsize * 2)
        if readsize > self.min_readsize:
            self.min_readsize = min(readsize, self.min_readsize * 2, 512)
        return ''.join(bufs) # Return resulting line 
Example #26
Source File: util.py    From meddle with MIT License 5 votes vote down vote up
def _num_version(libname):
            # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ]
            parts = libname.split(".")
            nums = []
            try:
                while parts:
                    nums.insert(0, int(parts.pop()))
            except ValueError:
                pass
            return nums or [ sys.maxint ] 
Example #27
Source File: popen2.py    From meddle with MIT License 5 votes vote down vote up
def __del__(self):
        # In case the child hasn't been waited on, check if it's done.
        self.poll(_deadstate=sys.maxint)
        if self.sts < 0:
            if _active is not None:
                # Child is still running, keep us alive until we can wait on it.
                _active.append(self) 
Example #28
Source File: popen2.py    From meddle with MIT License 5 votes vote down vote up
def _cleanup():
    for inst in _active[:]:
        if inst.poll(_deadstate=sys.maxint) >= 0:
            try:
                _active.remove(inst)
            except ValueError:
                # This can happen if two threads create a new Popen instance.
                # It's harmless that it was already removed, so ignore.
                pass 
Example #29
Source File: unittest_checker_python3.py    From python-netsurv with MIT License 5 votes vote down vote up
def test_sys_maxint_imort_from(self):
        node = astroid.extract_node(
            """
        from sys import maxint #@
        """
        )
        absolute_import_message = testutils.Message("no-absolute-import", node=node)
        message = testutils.Message("sys-max-int", node=node)
        with self.assertAddsMessages(absolute_import_message, message):
            self.checker.visit_importfrom(node) 
Example #30
Source File: gzip.py    From meddle with MIT License 5 votes vote down vote up
def readline(self, size=-1):
        if size < 0:
            # Shortcut common case - newline found in buffer.
            offset = self.offset - self.extrastart
            i = self.extrabuf.find('\n', offset) + 1
            if i > 0:
                self.extrasize -= i - offset
                self.offset += i - offset
                return self.extrabuf[offset: i]

            size = sys.maxint
            readsize = self.min_readsize
        else:
            readsize = size
        bufs = []
        while size != 0:
            c = self.read(readsize)
            i = c.find('\n')

            # We set i=size to break out of the loop under two
            # conditions: 1) there's no newline, and the chunk is
            # larger than size, or 2) there is a newline, but the
            # resulting line would be longer than 'size'.
            if (size <= i) or (i == -1 and len(c) > size):
                i = size - 1

            if i >= 0 or c == '':
                bufs.append(c[:i + 1])    # Add portion of last chunk
                self._unread(c[i + 1:])   # Push back rest of chunk
                break

            # Append chunk to list, decrease 'size',
            bufs.append(c)
            size = size - len(c)
            readsize = min(size, readsize * 2)
        if readsize > self.min_readsize:
            self.min_readsize = min(readsize, self.min_readsize * 2, 512)
        return ''.join(bufs) # Return resulting line