Python sys.maxint() Examples

The following are code examples for showing how to use sys.maxint(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: kinect-2-libras   Author: inessadl   File: heap.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def malloc(self, size):
        # return a block of right size (possibly rounded up)
        assert 0 <= size < sys.maxint
        if os.getpid() != self._lastpid:
            self.__init__()                     # reinitialize after fork
        self._lock.acquire()
        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()

#
# Class representing a chunk of an mmap -- can be inherited
# 
Example 2
Project: Flask_Blog   Author: sugarguo   File: posixemulation.py    (GNU General Public License v3.0) View Source Project 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 3
Project: Flask_Blog   Author: sugarguo   File: generator.py    (GNU General Public License v3.0) View Source Project 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 4
Project: SoCFoundationFlow   Author: mattaw   File: cppcheck.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _create_html_table(self, content, files):
		table = ElementTree.fromstring(CPPCHECK_HTML_TABLE)
		for name, val in files.items():
			f = val['htmlfile']
			s = '<tr><td colspan="4"><a href="%s">%s</a></td></tr>\n' % (f,name)
			row = ElementTree.fromstring(s)
			table.append(row)

			errors = sorted(val['errors'], key=lambda e: int(e['line']) if e.has_key('line') else sys.maxint)
			for e in errors:
				if not e.has_key('line'):
					s = '<tr><td></td><td>%s</td><td>%s</td><td>%s</td></tr>\n' % (e['id'], e['severity'], e['msg'])
				else:
					attr = ''
					if e['severity'] == 'error':
						attr = 'class="error"'
					s = '<tr><td><a href="%s#line-%s">%s</a></td>' % (f, e['line'], e['line'])
					s+= '<td>%s</td><td>%s</td><td %s>%s</td></tr>\n' % (e['id'], e['severity'], attr, e['msg'])
				row = ElementTree.fromstring(s)
				table.append(row)
		content.append(table) 
Example 5
Project: SoCFoundationFlow   Author: mattaw   File: cppcheck.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _create_html_table(self, content, files):
		table = ElementTree.fromstring(CPPCHECK_HTML_TABLE)
		for name, val in files.items():
			f = val['htmlfile']
			s = '<tr><td colspan="4"><a href="%s">%s</a></td></tr>\n' % (f,name)
			row = ElementTree.fromstring(s)
			table.append(row)

			errors = sorted(val['errors'], key=lambda e: int(e['line']) if e.has_key('line') else sys.maxint)
			for e in errors:
				if not e.has_key('line'):
					s = '<tr><td></td><td>%s</td><td>%s</td><td>%s</td></tr>\n' % (e['id'], e['severity'], e['msg'])
				else:
					attr = ''
					if e['severity'] == 'error':
						attr = 'class="error"'
					s = '<tr><td><a href="%s#line-%s">%s</a></td>' % (f, e['line'], e['line'])
					s+= '<td>%s</td><td>%s</td><td %s>%s</td></tr>\n' % (e['id'], e['severity'], attr, e['msg'])
				row = ElementTree.fromstring(s)
				table.append(row)
		content.append(table) 
Example 6
Project: SoCFoundationFlow   Author: mattaw   File: cppcheck.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _create_html_table(self, content, files):
		table = ElementTree.fromstring(CPPCHECK_HTML_TABLE)
		for name, val in files.items():
			f = val['htmlfile']
			s = '<tr><td colspan="4"><a href="%s">%s</a></td></tr>\n' % (f,name)
			row = ElementTree.fromstring(s)
			table.append(row)

			errors = sorted(val['errors'], key=lambda e: int(e['line']) if e.has_key('line') else sys.maxint)
			for e in errors:
				if not e.has_key('line'):
					s = '<tr><td></td><td>%s</td><td>%s</td><td>%s</td></tr>\n' % (e['id'], e['severity'], e['msg'])
				else:
					attr = ''
					if e['severity'] == 'error':
						attr = 'class="error"'
					s = '<tr><td><a href="%s#line-%s">%s</a></td>' % (f, e['line'], e['line'])
					s+= '<td>%s</td><td>%s</td><td %s>%s</td></tr>\n' % (e['id'], e['severity'], attr, e['msg'])
				row = ElementTree.fromstring(s)
				table.append(row)
		content.append(table) 
Example 7
Project: AI-Pacman   Author: AUTBS   File: distanceCalculator.py    (license) View Source Project 6 votes vote down vote up
def computeDistances(layout):
    "Runs UCS to all other positions from each position"
    distances = {}
    allNodes = layout.walls.asList(False)
    for source in allNodes:
        dist = {}
        closed = {}
        for node in allNodes:
            dist[node] = sys.maxint
        import util
        queue = util.PriorityQueue()
        queue.push(source, 0)
        dist[source] = 0
        while not queue.isEmpty():
            node = queue.pop()
            if node in closed:
                continue
            closed[node] = True
            nodeDist = dist[node]
            adjacent = []
            x, y = node
            if not layout.isWall((x,y+1)):
                adjacent.append((x,y+1))
            if not layout.isWall((x,y-1)):
                adjacent.append((x,y-1) )
            if not layout.isWall((x+1,y)):
                adjacent.append((x+1,y) )
            if not layout.isWall((x-1,y)):
                adjacent.append((x-1,y))
            for other in adjacent:
                if not other in dist:
                    continue
                oldDist = dist[other]
                newDist = nodeDist+1
                if newDist < oldDist:
                    dist[other] = newDist
                    queue.push(other, newDist)
        for target in allNodes:
            distances[(target, source)] = dist[target]
    return distances 
Example 8
Project: swjtu-pyscraper   Author: Desgard   File: posixemulation.py    (MIT License) View Source Project 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 9
Project: PyGenAlg   Author: RaphDeau   File: Individual.py    (Creative Commons Attribution 4.0) View Source Project 6 votes vote down vote up
def __generateRandomVarValue(cls, iVar):
        # 1- Get the definition domain of the variable
        defDomain = cls.VARIABLES_RANGES[iVar]
        if defDomain is None:
            randFloat = random.uniform(-sys.maxint-1, sys.maxint)
        else:
            # 2- Check the open/closed bounds
            includeFirst = defDomain[0] == '['
            includeLast = defDomain[-1] == ']'
            # 3- Get a random number in the domain
            defDomain = eval('[' + defDomain[1:-1] + ']')
            randFloat = random.random()*(defDomain[1]-defDomain[0]) + defDomain[0]
            # 4- Check the bounds
            while (randFloat == defDomain[0] and not includeFirst) or\
                    (randFloat == defDomain[1] and not includeLast):
                randFloat = random.random()*(defDomain[1]-defDomain[0]) + defDomain[0]
        # 5- Cast the variable type
        return cls.VARIABLES_TYPE(randFloat)
    # ---------------------- 
Example 10
Project: algorithms-tutorial   Author: happylindz   File: perfect_squares.py    (license) View Source Project 6 votes vote down vote up
def numSquares1(n):
    dp = [-1 for i in range(n + 1)]
    dp[1] = 1
    for i in range(2, n + 1):
        j = 1
        m = sys.maxint
        while j * j <= i:
            if j * j == i:
                m = 1
                break
            m = min(m, dp[i - j * j] + 1)
            j += 1
        dp[i] = m
    return dp[n]

# print(numSquares1(10234)) 
Example 11
Project: algorithms-tutorial   Author: happylindz   File: perfect_squares.py    (license) View Source Project 6 votes vote down vote up
def numSquares2(n):
    dp = [sys.maxint for i in range(n + 1)]
    dp[0] = 0
    for i in range(0, n + 1):
        for j in range(1, int(math.sqrt(n - i)) + 1):
            if i + j * j <= n:
                dp[i + j * j] = min(dp[i + j * j], dp[i] + 1)
    return dp[n]


# print(numSquares2(4))

# ??, ????????, ???????????????
# ??: ????????:
# 1. ?????????????????????4????????????????4?????????????????????1,2,3?4?????
# 2. ???????????4????????4?????????????2?8,3?12??
# 3. ???????8?7?????????4????????
# 4. ???????????????????????????1?2?????????????0 
Example 12
Project: CodingDojo   Author: ComputerSocietyUNB   File: http.py    (license) View Source Project 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
Project: CodingDojo   Author: ComputerSocietyUNB   File: http.py    (license) View Source Project 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
Project: zanph   Author: zanph   File: posixemulation.py    (license) View Source Project 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 15
Project: hostapd-mana   Author: adde88   File: heap.py    (license) View Source Project 6 votes vote down vote up
def malloc(self, size):
        # return a block of right size (possibly rounded up)
        assert 0 <= size < sys.maxint
        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()

#
# Class representing a chunk of an mmap -- can be inherited
# 
Example 16
Project: hostapd-mana   Author: adde88   File: generator.py    (license) View Source Project 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 17
Project: vspheretools   Author: devopshq   File: MIMEAttachment.py    (license) View Source Project 6 votes vote down vote up
def _make_boundary(text=None):
    #some code taken from python stdlib
    # 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 = ('=' * 10) + (_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 18
Project: Sci-Finder   Author: snverse   File: posixemulation.py    (license) View Source Project 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 19
Project: Sci-Finder   Author: snverse   File: posixemulation.py    (license) View Source Project 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 20
Project: plucky   Author: randomir   File: structural.py    (license) View Source Project 6 votes vote down vote up
def _sliced_list(self, selector):
        """For slice selectors operating on lists, we need to handle them
        differently, depending on ``skipmissing``. In explicit mode, we may have
        to expand the list with ``default`` values.
        """
        if self.skipmissing:
            return self.obj[selector]

        # TODO: can be optimized by observing list bounds
        keys = xrange(selector.start or 0,
                      selector.stop or sys.maxint,
                      selector.step or 1)
        res = []
        for key in keys:
            self._append(self.obj, key, res, skipmissing=False)
        return res 
Example 21
Project: p2pool-bch   Author: amarian12   File: MIMEAttachment.py    (license) View Source Project 6 votes vote down vote up
def _make_boundary(text=None):
    #some code taken from python stdlib
    # 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 = ('=' * 10) + (_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 22
Project: harbour-sailfinder   Author: DylanVanAssche   File: posixemulation.py    (license) View Source Project 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 23
Project: harbour-sailfinder   Author: DylanVanAssche   File: posixemulation.py    (license) View Source Project 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 24
Project: Texty   Author: sarthfrey   File: posixemulation.py    (license) View Source Project 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 25
Project: nojs   Author: chrisdickinson   File: process-graph.py    (license) View Source Project 6 votes vote down vote up
def detect_cycles():
  for root_edge in roots:
    reset_graph()
    # Mark ignored classes as already visited
    for ignore in args.ignore_classes:
      name = ignore.find("::") > 0 and ignore or ("blink::" + ignore)
      node = graph.get(name)
      if node:
        node.visited = True
    src = graph[root_edge.src]
    dst = graph.get(root_edge.dst)
    if src.visited:
      continue
    if root_edge.dst == "WTF::String":
      continue
    if dst is None:
      print "\nPersistent root to incomplete destination object:"
      print root_edge
      set_reported_error(True)
      continue
    # Find the shortest path from the root target (dst) to its host (src)
    shortest_path(dst, src)
    if src.cost < sys.maxint:
      report_cycle(root_edge) 
Example 26
Project: nojs   Author: chrisdickinson   File: process-graph.py    (license) View Source Project 6 votes vote down vote up
def detect_cycles():
  for root_edge in roots:
    reset_graph()
    # Mark ignored classes as already visited
    for ignore in args.ignore_classes:
      name = ignore.find("::") > 0 and ignore or ("blink::" + ignore)
      node = graph.get(name)
      if node:
        node.visited = True
    src = graph[root_edge.src]
    dst = graph.get(root_edge.dst)
    if src.visited:
      continue
    if root_edge.dst == "WTF::String":
      continue
    if dst is None:
      print "\nPersistent root to incomplete destination object:"
      print root_edge
      set_reported_error(True)
      continue
    # Find the shortest path from the root target (dst) to its host (src)
    shortest_path(dst, src)
    if src.cost < sys.maxint:
      report_cycle(root_edge) 
Example 27
Project: touch-pay-client   Author: HackPucBemobi   File: objects.py    (license) View Source Project 6 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            start = i.start or 0
            stop = i.stop

            db = self.db
            if start < 0:
                pos0 = '(%s - %d)' % (self.len(), abs(start) - 1)
            else:
                pos0 = start + 1

            maxint = sys.maxint if PY2 else sys.maxsize
            if stop is None or stop == maxint:
                length = self.len()
            elif stop < 0:
                length = '(%s - %d - %s)' % (self.len(), abs(stop) - 1, pos0)
            else:
                length = '(%s - %s)' % (stop + 1, pos0)

            return Expression(db, self._dialect.substring,
                              self, (pos0, length), self.type)
        else:
            return self[i:i + 1] 
Example 28
Project: arithmancer   Author: google   File: posixemulation.py    (license) View Source Project 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 29
Project: tesismometro   Author: joapaspe   File: posixemulation.py    (license) View Source Project 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 30
Project: aws-cfn-plex   Author: lordmuffin   File: nodes.py    (license) View Source Project 6 votes vote down vote up
def first_child_matching_class(self, childclass, start=0, end=sys.maxint):
        """
        Return the index of the first child whose class exactly matches.

        Parameters:

        - `childclass`: A `Node` subclass to search for, or a tuple of `Node`
          classes. If a tuple, any of the classes may match.
        - `start`: Initial index to check.
        - `end`: Initial index to *not* check.
        """
        if not isinstance(childclass, tuple):
            childclass = (childclass,)
        for index in range(start, min(len(self), end)):
            for c in childclass:
                if isinstance(self[index], c):
                    return index
        return None 
Example 31
Project: aws-cfn-plex   Author: lordmuffin   File: nodes.py    (license) View Source Project 6 votes vote down vote up
def first_child_not_matching_class(self, childclass, start=0,
                                       end=sys.maxint):
        """
        Return the index of the first child whose class does *not* match.

        Parameters:

        - `childclass`: A `Node` subclass to skip, or a tuple of `Node`
          classes. If a tuple, none of the classes may match.
        - `start`: Initial index to check.
        - `end`: Initial index to *not* check.
        """
        if not isinstance(childclass, tuple):
            childclass = (childclass,)
        for index in range(start, min(len(self), end)):
            for c in childclass:
                if isinstance(self.children[index], c):
                    break
            else:
                return index
        return None 
Example 32
Project: RPoint   Author: george17-meet   File: posixemulation.py    (license) View Source Project 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 33
Project: isni-reconcile   Author: cmh2166   File: posixemulation.py    (license) View Source Project 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 34
Project: AshsSDK   Author: thehappydinoa   File: nodes.py    (license) View Source Project 6 votes vote down vote up
def first_child_matching_class(self, childclass, start=0, end=sys.maxint):
        """
        Return the index of the first child whose class exactly matches.

        Parameters:

        - `childclass`: A `Node` subclass to search for, or a tuple of `Node`
          classes. If a tuple, any of the classes may match.
        - `start`: Initial index to check.
        - `end`: Initial index to *not* check.
        """
        if not isinstance(childclass, tuple):
            childclass = (childclass,)
        for index in range(start, min(len(self), end)):
            for c in childclass:
                if isinstance(self[index], c):
                    return index
        return None 
Example 35
Project: AshsSDK   Author: thehappydinoa   File: nodes.py    (license) View Source Project 6 votes vote down vote up
def first_child_not_matching_class(self, childclass, start=0,
                                       end=sys.maxint):
        """
        Return the index of the first child whose class does *not* match.

        Parameters:

        - `childclass`: A `Node` subclass to skip, or a tuple of `Node`
          classes. If a tuple, none of the classes may match.
        - `start`: Initial index to check.
        - `end`: Initial index to *not* check.
        """
        if not isinstance(childclass, tuple):
            childclass = (childclass,)
        for index in range(start, min(len(self), end)):
            for c in childclass:
                if isinstance(self.children[index], c):
                    break
            else:
                return index
        return None 
Example 36
Project: Intranet-Penetration   Author: yuxiaokui   File: generator.py    (license) View Source Project 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 37
Project: Intranet-Penetration   Author: yuxiaokui   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def version_str_to_tuple(version_str):
    import re
    import sys

    if version_str == 'HEAD':
        return (sys.maxint, sys.maxint, sys.maxint, sys.maxint)

    m = re.match(r'(\d+)\.(\d+)(\.(\d+))?(b(\d+))?', version_str)
    if m is None:
        raise ValueError("Bad version string %r" % version_str)

    major = int(m.group(1))
    minor = int(m.group(2))
    patch = int(m.group(4) or 0)
    beta = int(m.group(6) or sys.maxint)

    return (major, minor, patch, beta) 
Example 38
Project: Intranet-Penetration   Author: yuxiaokui   File: file.py    (license) View Source Project 6 votes vote down vote up
def read(self, size=None):
    """Read data from RAW file.

    Args:
      size: Number of bytes to read as integer. Actual number of bytes
        read is always equal to size unless end if file was reached.

    Returns:
      A string with data read.
    """
    if size is None:
      size = sys.maxint
    data_list = []
    while True:
      result = self.__readBuffer(size)
      data_list.append(result)
      size -= len(result)
      if size == 0 or self._eof:
        return ''.join(data_list)
      self.__refillBuffer() 
Example 39
Project: Intranet-Penetration   Author: yuxiaokui   File: jarfile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, output_directory, base_name, maximum_size=sys.maxint):
    self.base_name = base_name
    self.output_directory = os.path.normpath(output_directory)
    self.maximum_size = maximum_size

    if not os.path.exists(self.output_directory):
      os.makedirs(self.output_directory)
    elif not os.path.isdir(self.output_directory):
      raise JarWriteError('Not a directory: %s' % self.output_directory)




    self.current_jar = None
    self.current_jar_size = 0
    self.jar_suffix = 0 
Example 40
Project: Intranet-Penetration   Author: yuxiaokui   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def version_str_to_tuple(version_str):
    import re
    import sys

    if version_str == 'HEAD':
        return (sys.maxint, sys.maxint, sys.maxint, sys.maxint)

    m = re.match(r'(\d+)\.(\d+)(\.(\d+))?(b(\d+))?', version_str)
    if m is None:
        raise ValueError("Bad version string %r" % version_str)

    major = int(m.group(1))
    minor = int(m.group(2))
    patch = int(m.group(4) or 0)
    beta = int(m.group(6) or sys.maxint)

    return (major, minor, patch, beta) 
Example 41
Project: flasky   Author: RoseOu   File: posixemulation.py    (license) View Source Project 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 42
Project: p2pool-unitus   Author: amarian12   File: MIMEAttachment.py    (license) View Source Project 6 votes vote down vote up
def _make_boundary(text=None):
    #some code taken from python stdlib
    # 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 = ('=' * 10) + (_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 43
Project: MKFQ   Author: maojingios   File: generator.py    (license) View Source Project 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 44
Project: MKFQ   Author: maojingios   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def version_str_to_tuple(version_str):
    import re
    import sys

    if version_str == 'HEAD':
        return (sys.maxint, sys.maxint, sys.maxint, sys.maxint)

    m = re.match(r'(\d+)\.(\d+)(\.(\d+))?(b(\d+))?', version_str)
    if m is None:
        raise ValueError("Bad version string %r" % version_str)

    major = int(m.group(1))
    minor = int(m.group(2))
    patch = int(m.group(4) or 0)
    beta = int(m.group(6) or sys.maxint)

    return (major, minor, patch, beta) 
Example 45
Project: MKFQ   Author: maojingios   File: file.py    (license) View Source Project 6 votes vote down vote up
def read(self, size=None):
    """Read data from RAW file.

    Args:
      size: Number of bytes to read as integer. Actual number of bytes
        read is always equal to size unless end if file was reached.

    Returns:
      A string with data read.
    """
    if size is None:
      size = sys.maxint
    data_list = []
    while True:
      result = self.__readBuffer(size)
      data_list.append(result)
      size -= len(result)
      if size == 0 or self._eof:
        return ''.join(data_list)
      self.__refillBuffer() 
Example 46
Project: MKFQ   Author: maojingios   File: jarfile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, output_directory, base_name, maximum_size=sys.maxint):
    self.base_name = base_name
    self.output_directory = os.path.normpath(output_directory)
    self.maximum_size = maximum_size

    if not os.path.exists(self.output_directory):
      os.makedirs(self.output_directory)
    elif not os.path.isdir(self.output_directory):
      raise JarWriteError('Not a directory: %s' % self.output_directory)




    self.current_jar = None
    self.current_jar_size = 0
    self.jar_suffix = 0 
Example 47
Project: MKFQ   Author: maojingios   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def version_str_to_tuple(version_str):
    import re
    import sys

    if version_str == 'HEAD':
        return (sys.maxint, sys.maxint, sys.maxint, sys.maxint)

    m = re.match(r'(\d+)\.(\d+)(\.(\d+))?(b(\d+))?', version_str)
    if m is None:
        raise ValueError("Bad version string %r" % version_str)

    major = int(m.group(1))
    minor = int(m.group(2))
    patch = int(m.group(4) or 0)
    beta = int(m.group(6) or sys.maxint)

    return (major, minor, patch, beta) 
Example 48
Project: sawtooth-mktplace   Author: hyperledger-archives   File: exchange_offer_update.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, objectid=None, minfo=None):
        if minfo is None:
            minfo = {}
        super(ExchangeOfferObject, self).__init__(objectid, minfo)

        self.CreatorID = minfo.get('creator', '**UNKNOWN**')
        self.InputID = minfo.get('input', '**UNKNOWN**')
        self.OutputID = minfo.get('output', '**UNKNOWN**')
        self.Ratio = float(minfo.get('ratio', 0))
        self.Description = minfo.get('description', '')
        self.Name = minfo.get('name', '')
        self.Minimum = int(minfo.get('minimum', 1))
        self.Maximum = int(minfo.get('maximum', sys.maxint))
        self.Execution = minfo.get('execution', 'Any')
        self.ExecutionState = {'ParticipantList': []}

        # the minimum must be high enough so that at least 1 asset
        # is transferred out of the holding as a result of executing the offer
        if self.Ratio < 0:
            self.Minimum = max(self.Minimum, int(1.0 / self.Ratio))
            if self.Minimum * self.Ratio < 1.0:
                self.Minimum += 1 
Example 49
Project: veppy   Author: solvebio   File: test_veppy.py    (license) View Source Project 6 votes vote down vote up
def _test(self, filepath):
        def vcf_row_to_test(vcf_row):
            return (
                vcf_row['info']['TRANSCRIPT'][0],
                (
                    vcf_row['chromosome'],
                    vcf_row['start'],
                    vcf_row['reference_allele'],
                    vcf_row['alternate_alleles'][0]
                ),
                [x for x in vcf_row['info'].get('REQUIRED', []) if x],
                [x for x in vcf_row['info'].get('DISALLOWED', []) if x]
            )

        with VcfReader(self.get_absolute_filepath(filepath)) as reader:
            for row in islice(reader, sys.maxint):
                self.assertTest(vcf_row_to_test(row)) 
Example 50
Project: face-landmark   Author: lsy17096535   File: DataRow.py    (license) View Source Project 6 votes vote down vote up
def createDataRowsFromCSV(csvFilePath, csvParseFunc, DATA_PATH, limit = sys.maxint):
    ''' Returns a list of DataRow from CSV files parsed by csvParseFunc, 
        DATA_PATH is the prefix to add to the csv file names,
        limit can be used to parse only partial file rows.
    ''' 
    data = []  # the array we build
    validObjectsCounter = 0 
    
    with open(csvFilePath, 'r') as csvfile:

        reader = csv.reader(csvfile, delimiter=' ')
        for row in reader:
            d = csvParseFunc(row, DATA_PATH)
            if d is not None:
                data.append(d)
                validObjectsCounter += 1
                if (validObjectsCounter > limit ):  # Stop if reached to limit
                    return data 
    return data