partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
ByteParser._split_into_chunks
Split the code object into a list of `Chunk` objects. Each chunk is only entered at its first instruction, though there can be many exits from a chunk. Returns a list of `Chunk` objects.
virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py
def _split_into_chunks(self): """Split the code object into a list of `Chunk` objects. Each chunk is only entered at its first instruction, though there can be many exits from a chunk. Returns a list of `Chunk` objects. """ # The list of chunks so far, and the one we're working on. chunks = [] chunk = None # A dict mapping byte offsets of line starts to the line numbers. bytes_lines_map = dict(self._bytes_lines()) # The block stack: loops and try blocks get pushed here for the # implicit jumps that can occur. # Each entry is a tuple: (block type, destination) block_stack = [] # Some op codes are followed by branches that should be ignored. This # is a count of how many ignores are left. ignore_branch = 0 # We have to handle the last two bytecodes specially. ult = penult = None # Get a set of all of the jump-to points. jump_to = set() bytecodes = list(ByteCodes(self.code.co_code)) for bc in bytecodes: if bc.jump_to >= 0: jump_to.add(bc.jump_to) chunk_lineno = 0 # Walk the byte codes building chunks. for bc in bytecodes: # Maybe have to start a new chunk start_new_chunk = False first_chunk = False if bc.offset in bytes_lines_map: # Start a new chunk for each source line number. start_new_chunk = True chunk_lineno = bytes_lines_map[bc.offset] first_chunk = True elif bc.offset in jump_to: # To make chunks have a single entrance, we have to make a new # chunk when we get to a place some bytecode jumps to. start_new_chunk = True elif bc.op in OPS_CHUNK_BEGIN: # Jumps deserve their own unnumbered chunk. This fixes # problems with jumps to jumps getting confused. start_new_chunk = True if not chunk or start_new_chunk: if chunk: chunk.exits.add(bc.offset) chunk = Chunk(bc.offset, chunk_lineno, first_chunk) chunks.append(chunk) # Look at the opcode if bc.jump_to >= 0 and bc.op not in OPS_NO_JUMP: if ignore_branch: # Someone earlier wanted us to ignore this branch. ignore_branch -= 1 else: # The opcode has a jump, it's an exit for this chunk. chunk.exits.add(bc.jump_to) if bc.op in OPS_CODE_END: # The opcode can exit the code object. chunk.exits.add(-self.code.co_firstlineno) if bc.op in OPS_PUSH_BLOCK: # The opcode adds a block to the block_stack. block_stack.append((bc.op, bc.jump_to)) if bc.op in OPS_POP_BLOCK: # The opcode pops a block from the block stack. block_stack.pop() if bc.op in OPS_CHUNK_END: # This opcode forces the end of the chunk. if bc.op == OP_BREAK_LOOP: # A break is implicit: jump where the top of the # block_stack points. chunk.exits.add(block_stack[-1][1]) chunk = None if bc.op == OP_END_FINALLY: # For the finally clause we need to find the closest exception # block, and use its jump target as an exit. for block in reversed(block_stack): if block[0] in OPS_EXCEPT_BLOCKS: chunk.exits.add(block[1]) break if bc.op == OP_COMPARE_OP and bc.arg == COMPARE_EXCEPTION: # This is an except clause. We want to overlook the next # branch, so that except's don't count as branches. ignore_branch += 1 penult = ult ult = bc if chunks: # The last two bytecodes could be a dummy "return None" that # shouldn't be counted as real code. Every Python code object seems # to end with a return, and a "return None" is inserted if there # isn't an explicit return in the source. if ult and penult: if penult.op == OP_LOAD_CONST and ult.op == OP_RETURN_VALUE: if self.code.co_consts[penult.arg] is None: # This is "return None", but is it dummy? A real line # would be a last chunk all by itself. if chunks[-1].byte != penult.offset: ex = -self.code.co_firstlineno # Split the last chunk last_chunk = chunks[-1] last_chunk.exits.remove(ex) last_chunk.exits.add(penult.offset) chunk = Chunk( penult.offset, last_chunk.line, False ) chunk.exits.add(ex) chunks.append(chunk) # Give all the chunks a length. chunks[-1].length = bc.next_offset - chunks[-1].byte # pylint: disable=W0631,C0301 for i in range(len(chunks)-1): chunks[i].length = chunks[i+1].byte - chunks[i].byte #self.validate_chunks(chunks) return chunks
def _split_into_chunks(self): """Split the code object into a list of `Chunk` objects. Each chunk is only entered at its first instruction, though there can be many exits from a chunk. Returns a list of `Chunk` objects. """ # The list of chunks so far, and the one we're working on. chunks = [] chunk = None # A dict mapping byte offsets of line starts to the line numbers. bytes_lines_map = dict(self._bytes_lines()) # The block stack: loops and try blocks get pushed here for the # implicit jumps that can occur. # Each entry is a tuple: (block type, destination) block_stack = [] # Some op codes are followed by branches that should be ignored. This # is a count of how many ignores are left. ignore_branch = 0 # We have to handle the last two bytecodes specially. ult = penult = None # Get a set of all of the jump-to points. jump_to = set() bytecodes = list(ByteCodes(self.code.co_code)) for bc in bytecodes: if bc.jump_to >= 0: jump_to.add(bc.jump_to) chunk_lineno = 0 # Walk the byte codes building chunks. for bc in bytecodes: # Maybe have to start a new chunk start_new_chunk = False first_chunk = False if bc.offset in bytes_lines_map: # Start a new chunk for each source line number. start_new_chunk = True chunk_lineno = bytes_lines_map[bc.offset] first_chunk = True elif bc.offset in jump_to: # To make chunks have a single entrance, we have to make a new # chunk when we get to a place some bytecode jumps to. start_new_chunk = True elif bc.op in OPS_CHUNK_BEGIN: # Jumps deserve their own unnumbered chunk. This fixes # problems with jumps to jumps getting confused. start_new_chunk = True if not chunk or start_new_chunk: if chunk: chunk.exits.add(bc.offset) chunk = Chunk(bc.offset, chunk_lineno, first_chunk) chunks.append(chunk) # Look at the opcode if bc.jump_to >= 0 and bc.op not in OPS_NO_JUMP: if ignore_branch: # Someone earlier wanted us to ignore this branch. ignore_branch -= 1 else: # The opcode has a jump, it's an exit for this chunk. chunk.exits.add(bc.jump_to) if bc.op in OPS_CODE_END: # The opcode can exit the code object. chunk.exits.add(-self.code.co_firstlineno) if bc.op in OPS_PUSH_BLOCK: # The opcode adds a block to the block_stack. block_stack.append((bc.op, bc.jump_to)) if bc.op in OPS_POP_BLOCK: # The opcode pops a block from the block stack. block_stack.pop() if bc.op in OPS_CHUNK_END: # This opcode forces the end of the chunk. if bc.op == OP_BREAK_LOOP: # A break is implicit: jump where the top of the # block_stack points. chunk.exits.add(block_stack[-1][1]) chunk = None if bc.op == OP_END_FINALLY: # For the finally clause we need to find the closest exception # block, and use its jump target as an exit. for block in reversed(block_stack): if block[0] in OPS_EXCEPT_BLOCKS: chunk.exits.add(block[1]) break if bc.op == OP_COMPARE_OP and bc.arg == COMPARE_EXCEPTION: # This is an except clause. We want to overlook the next # branch, so that except's don't count as branches. ignore_branch += 1 penult = ult ult = bc if chunks: # The last two bytecodes could be a dummy "return None" that # shouldn't be counted as real code. Every Python code object seems # to end with a return, and a "return None" is inserted if there # isn't an explicit return in the source. if ult and penult: if penult.op == OP_LOAD_CONST and ult.op == OP_RETURN_VALUE: if self.code.co_consts[penult.arg] is None: # This is "return None", but is it dummy? A real line # would be a last chunk all by itself. if chunks[-1].byte != penult.offset: ex = -self.code.co_firstlineno # Split the last chunk last_chunk = chunks[-1] last_chunk.exits.remove(ex) last_chunk.exits.add(penult.offset) chunk = Chunk( penult.offset, last_chunk.line, False ) chunk.exits.add(ex) chunks.append(chunk) # Give all the chunks a length. chunks[-1].length = bc.next_offset - chunks[-1].byte # pylint: disable=W0631,C0301 for i in range(len(chunks)-1): chunks[i].length = chunks[i+1].byte - chunks[i].byte #self.validate_chunks(chunks) return chunks
[ "Split", "the", "code", "object", "into", "a", "list", "of", "Chunk", "objects", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py#L422-L552
[ "def", "_split_into_chunks", "(", "self", ")", ":", "# The list of chunks so far, and the one we're working on.", "chunks", "=", "[", "]", "chunk", "=", "None", "# A dict mapping byte offsets of line starts to the line numbers.", "bytes_lines_map", "=", "dict", "(", "self", ".", "_bytes_lines", "(", ")", ")", "# The block stack: loops and try blocks get pushed here for the", "# implicit jumps that can occur.", "# Each entry is a tuple: (block type, destination)", "block_stack", "=", "[", "]", "# Some op codes are followed by branches that should be ignored. This", "# is a count of how many ignores are left.", "ignore_branch", "=", "0", "# We have to handle the last two bytecodes specially.", "ult", "=", "penult", "=", "None", "# Get a set of all of the jump-to points.", "jump_to", "=", "set", "(", ")", "bytecodes", "=", "list", "(", "ByteCodes", "(", "self", ".", "code", ".", "co_code", ")", ")", "for", "bc", "in", "bytecodes", ":", "if", "bc", ".", "jump_to", ">=", "0", ":", "jump_to", ".", "add", "(", "bc", ".", "jump_to", ")", "chunk_lineno", "=", "0", "# Walk the byte codes building chunks.", "for", "bc", "in", "bytecodes", ":", "# Maybe have to start a new chunk", "start_new_chunk", "=", "False", "first_chunk", "=", "False", "if", "bc", ".", "offset", "in", "bytes_lines_map", ":", "# Start a new chunk for each source line number.", "start_new_chunk", "=", "True", "chunk_lineno", "=", "bytes_lines_map", "[", "bc", ".", "offset", "]", "first_chunk", "=", "True", "elif", "bc", ".", "offset", "in", "jump_to", ":", "# To make chunks have a single entrance, we have to make a new", "# chunk when we get to a place some bytecode jumps to.", "start_new_chunk", "=", "True", "elif", "bc", ".", "op", "in", "OPS_CHUNK_BEGIN", ":", "# Jumps deserve their own unnumbered chunk. This fixes", "# problems with jumps to jumps getting confused.", "start_new_chunk", "=", "True", "if", "not", "chunk", "or", "start_new_chunk", ":", "if", "chunk", ":", "chunk", ".", "exits", ".", "add", "(", "bc", ".", "offset", ")", "chunk", "=", "Chunk", "(", "bc", ".", "offset", ",", "chunk_lineno", ",", "first_chunk", ")", "chunks", ".", "append", "(", "chunk", ")", "# Look at the opcode", "if", "bc", ".", "jump_to", ">=", "0", "and", "bc", ".", "op", "not", "in", "OPS_NO_JUMP", ":", "if", "ignore_branch", ":", "# Someone earlier wanted us to ignore this branch.", "ignore_branch", "-=", "1", "else", ":", "# The opcode has a jump, it's an exit for this chunk.", "chunk", ".", "exits", ".", "add", "(", "bc", ".", "jump_to", ")", "if", "bc", ".", "op", "in", "OPS_CODE_END", ":", "# The opcode can exit the code object.", "chunk", ".", "exits", ".", "add", "(", "-", "self", ".", "code", ".", "co_firstlineno", ")", "if", "bc", ".", "op", "in", "OPS_PUSH_BLOCK", ":", "# The opcode adds a block to the block_stack.", "block_stack", ".", "append", "(", "(", "bc", ".", "op", ",", "bc", ".", "jump_to", ")", ")", "if", "bc", ".", "op", "in", "OPS_POP_BLOCK", ":", "# The opcode pops a block from the block stack.", "block_stack", ".", "pop", "(", ")", "if", "bc", ".", "op", "in", "OPS_CHUNK_END", ":", "# This opcode forces the end of the chunk.", "if", "bc", ".", "op", "==", "OP_BREAK_LOOP", ":", "# A break is implicit: jump where the top of the", "# block_stack points.", "chunk", ".", "exits", ".", "add", "(", "block_stack", "[", "-", "1", "]", "[", "1", "]", ")", "chunk", "=", "None", "if", "bc", ".", "op", "==", "OP_END_FINALLY", ":", "# For the finally clause we need to find the closest exception", "# block, and use its jump target as an exit.", "for", "block", "in", "reversed", "(", "block_stack", ")", ":", "if", "block", "[", "0", "]", "in", "OPS_EXCEPT_BLOCKS", ":", "chunk", ".", "exits", ".", "add", "(", "block", "[", "1", "]", ")", "break", "if", "bc", ".", "op", "==", "OP_COMPARE_OP", "and", "bc", ".", "arg", "==", "COMPARE_EXCEPTION", ":", "# This is an except clause. We want to overlook the next", "# branch, so that except's don't count as branches.", "ignore_branch", "+=", "1", "penult", "=", "ult", "ult", "=", "bc", "if", "chunks", ":", "# The last two bytecodes could be a dummy \"return None\" that", "# shouldn't be counted as real code. Every Python code object seems", "# to end with a return, and a \"return None\" is inserted if there", "# isn't an explicit return in the source.", "if", "ult", "and", "penult", ":", "if", "penult", ".", "op", "==", "OP_LOAD_CONST", "and", "ult", ".", "op", "==", "OP_RETURN_VALUE", ":", "if", "self", ".", "code", ".", "co_consts", "[", "penult", ".", "arg", "]", "is", "None", ":", "# This is \"return None\", but is it dummy? A real line", "# would be a last chunk all by itself.", "if", "chunks", "[", "-", "1", "]", ".", "byte", "!=", "penult", ".", "offset", ":", "ex", "=", "-", "self", ".", "code", ".", "co_firstlineno", "# Split the last chunk", "last_chunk", "=", "chunks", "[", "-", "1", "]", "last_chunk", ".", "exits", ".", "remove", "(", "ex", ")", "last_chunk", ".", "exits", ".", "add", "(", "penult", ".", "offset", ")", "chunk", "=", "Chunk", "(", "penult", ".", "offset", ",", "last_chunk", ".", "line", ",", "False", ")", "chunk", ".", "exits", ".", "add", "(", "ex", ")", "chunks", ".", "append", "(", "chunk", ")", "# Give all the chunks a length.", "chunks", "[", "-", "1", "]", ".", "length", "=", "bc", ".", "next_offset", "-", "chunks", "[", "-", "1", "]", ".", "byte", "# pylint: disable=W0631,C0301", "for", "i", "in", "range", "(", "len", "(", "chunks", ")", "-", "1", ")", ":", "chunks", "[", "i", "]", ".", "length", "=", "chunks", "[", "i", "+", "1", "]", ".", "byte", "-", "chunks", "[", "i", "]", ".", "byte", "#self.validate_chunks(chunks)", "return", "chunks" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
ByteParser.validate_chunks
Validate the rule that chunks have a single entrance.
virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py
def validate_chunks(self, chunks): """Validate the rule that chunks have a single entrance.""" # starts is the entrances to the chunks starts = set([ch.byte for ch in chunks]) for ch in chunks: assert all([(ex in starts or ex < 0) for ex in ch.exits])
def validate_chunks(self, chunks): """Validate the rule that chunks have a single entrance.""" # starts is the entrances to the chunks starts = set([ch.byte for ch in chunks]) for ch in chunks: assert all([(ex in starts or ex < 0) for ex in ch.exits])
[ "Validate", "the", "rule", "that", "chunks", "have", "a", "single", "entrance", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py#L554-L559
[ "def", "validate_chunks", "(", "self", ",", "chunks", ")", ":", "# starts is the entrances to the chunks", "starts", "=", "set", "(", "[", "ch", ".", "byte", "for", "ch", "in", "chunks", "]", ")", "for", "ch", "in", "chunks", ":", "assert", "all", "(", "[", "(", "ex", "in", "starts", "or", "ex", "<", "0", ")", "for", "ex", "in", "ch", ".", "exits", "]", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
ByteParser._arcs
Find the executable arcs in the code. Yields pairs: (from,to). From and to are integer line numbers. If from is < 0, then the arc is an entrance into the code object. If to is < 0, the arc is an exit from the code object.
virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py
def _arcs(self): """Find the executable arcs in the code. Yields pairs: (from,to). From and to are integer line numbers. If from is < 0, then the arc is an entrance into the code object. If to is < 0, the arc is an exit from the code object. """ chunks = self._split_into_chunks() # A map from byte offsets to chunks jumped into. byte_chunks = dict([(c.byte, c) for c in chunks]) # There's always an entrance at the first chunk. yield (-1, byte_chunks[0].line) # Traverse from the first chunk in each line, and yield arcs where # the trace function will be invoked. for chunk in chunks: if not chunk.first: continue chunks_considered = set() chunks_to_consider = [chunk] while chunks_to_consider: # Get the chunk we're considering, and make sure we don't # consider it again this_chunk = chunks_to_consider.pop() chunks_considered.add(this_chunk) # For each exit, add the line number if the trace function # would be triggered, or add the chunk to those being # considered if not. for ex in this_chunk.exits: if ex < 0: yield (chunk.line, ex) else: next_chunk = byte_chunks[ex] if next_chunk in chunks_considered: continue # The trace function is invoked if visiting the first # bytecode in a line, or if the transition is a # backward jump. backward_jump = next_chunk.byte < this_chunk.byte if next_chunk.first or backward_jump: if next_chunk.line != chunk.line: yield (chunk.line, next_chunk.line) else: chunks_to_consider.append(next_chunk)
def _arcs(self): """Find the executable arcs in the code. Yields pairs: (from,to). From and to are integer line numbers. If from is < 0, then the arc is an entrance into the code object. If to is < 0, the arc is an exit from the code object. """ chunks = self._split_into_chunks() # A map from byte offsets to chunks jumped into. byte_chunks = dict([(c.byte, c) for c in chunks]) # There's always an entrance at the first chunk. yield (-1, byte_chunks[0].line) # Traverse from the first chunk in each line, and yield arcs where # the trace function will be invoked. for chunk in chunks: if not chunk.first: continue chunks_considered = set() chunks_to_consider = [chunk] while chunks_to_consider: # Get the chunk we're considering, and make sure we don't # consider it again this_chunk = chunks_to_consider.pop() chunks_considered.add(this_chunk) # For each exit, add the line number if the trace function # would be triggered, or add the chunk to those being # considered if not. for ex in this_chunk.exits: if ex < 0: yield (chunk.line, ex) else: next_chunk = byte_chunks[ex] if next_chunk in chunks_considered: continue # The trace function is invoked if visiting the first # bytecode in a line, or if the transition is a # backward jump. backward_jump = next_chunk.byte < this_chunk.byte if next_chunk.first or backward_jump: if next_chunk.line != chunk.line: yield (chunk.line, next_chunk.line) else: chunks_to_consider.append(next_chunk)
[ "Find", "the", "executable", "arcs", "in", "the", "code", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py#L561-L610
[ "def", "_arcs", "(", "self", ")", ":", "chunks", "=", "self", ".", "_split_into_chunks", "(", ")", "# A map from byte offsets to chunks jumped into.", "byte_chunks", "=", "dict", "(", "[", "(", "c", ".", "byte", ",", "c", ")", "for", "c", "in", "chunks", "]", ")", "# There's always an entrance at the first chunk.", "yield", "(", "-", "1", ",", "byte_chunks", "[", "0", "]", ".", "line", ")", "# Traverse from the first chunk in each line, and yield arcs where", "# the trace function will be invoked.", "for", "chunk", "in", "chunks", ":", "if", "not", "chunk", ".", "first", ":", "continue", "chunks_considered", "=", "set", "(", ")", "chunks_to_consider", "=", "[", "chunk", "]", "while", "chunks_to_consider", ":", "# Get the chunk we're considering, and make sure we don't", "# consider it again", "this_chunk", "=", "chunks_to_consider", ".", "pop", "(", ")", "chunks_considered", ".", "add", "(", "this_chunk", ")", "# For each exit, add the line number if the trace function", "# would be triggered, or add the chunk to those being", "# considered if not.", "for", "ex", "in", "this_chunk", ".", "exits", ":", "if", "ex", "<", "0", ":", "yield", "(", "chunk", ".", "line", ",", "ex", ")", "else", ":", "next_chunk", "=", "byte_chunks", "[", "ex", "]", "if", "next_chunk", "in", "chunks_considered", ":", "continue", "# The trace function is invoked if visiting the first", "# bytecode in a line, or if the transition is a", "# backward jump.", "backward_jump", "=", "next_chunk", ".", "byte", "<", "this_chunk", ".", "byte", "if", "next_chunk", ".", "first", "or", "backward_jump", ":", "if", "next_chunk", ".", "line", "!=", "chunk", ".", "line", ":", "yield", "(", "chunk", ".", "line", ",", "next_chunk", ".", "line", ")", "else", ":", "chunks_to_consider", ".", "append", "(", "next_chunk", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
ByteParser._all_chunks
Returns a list of `Chunk` objects for this code and its children. See `_split_into_chunks` for details.
virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py
def _all_chunks(self): """Returns a list of `Chunk` objects for this code and its children. See `_split_into_chunks` for details. """ chunks = [] for bp in self.child_parsers(): chunks.extend(bp._split_into_chunks()) return chunks
def _all_chunks(self): """Returns a list of `Chunk` objects for this code and its children. See `_split_into_chunks` for details. """ chunks = [] for bp in self.child_parsers(): chunks.extend(bp._split_into_chunks()) return chunks
[ "Returns", "a", "list", "of", "Chunk", "objects", "for", "this", "code", "and", "its", "children", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py#L612-L622
[ "def", "_all_chunks", "(", "self", ")", ":", "chunks", "=", "[", "]", "for", "bp", "in", "self", ".", "child_parsers", "(", ")", ":", "chunks", ".", "extend", "(", "bp", ".", "_split_into_chunks", "(", ")", ")", "return", "chunks" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
ByteParser._all_arcs
Get the set of all arcs in this code object and its children. See `_arcs` for details.
virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py
def _all_arcs(self): """Get the set of all arcs in this code object and its children. See `_arcs` for details. """ arcs = set() for bp in self.child_parsers(): arcs.update(bp._arcs()) return arcs
def _all_arcs(self): """Get the set of all arcs in this code object and its children. See `_arcs` for details. """ arcs = set() for bp in self.child_parsers(): arcs.update(bp._arcs()) return arcs
[ "Get", "the", "set", "of", "all", "arcs", "in", "this", "code", "object", "and", "its", "children", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py#L624-L634
[ "def", "_all_arcs", "(", "self", ")", ":", "arcs", "=", "set", "(", ")", "for", "bp", "in", "self", ".", "child_parsers", "(", ")", ":", "arcs", ".", "update", "(", "bp", ".", "_arcs", "(", ")", ")", "return", "arcs" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
Coverage.options
Add options to command line.
environment/lib/python2.7/site-packages/nose/plugins/cover.py
def options(self, parser, env): """ Add options to command line. """ super(Coverage, self).options(parser, env) parser.add_option("--cover-package", action="append", default=env.get('NOSE_COVER_PACKAGE'), metavar="PACKAGE", dest="cover_packages", help="Restrict coverage output to selected packages " "[NOSE_COVER_PACKAGE]") parser.add_option("--cover-erase", action="store_true", default=env.get('NOSE_COVER_ERASE'), dest="cover_erase", help="Erase previously collected coverage " "statistics before run") parser.add_option("--cover-tests", action="store_true", dest="cover_tests", default=env.get('NOSE_COVER_TESTS'), help="Include test modules in coverage report " "[NOSE_COVER_TESTS]") parser.add_option("--cover-min-percentage", action="store", dest="cover_min_percentage", default=env.get('NOSE_COVER_MIN_PERCENTAGE'), help="Minimum percentage of coverage for tests" "to pass [NOSE_COVER_MIN_PERCENTAGE]") parser.add_option("--cover-inclusive", action="store_true", dest="cover_inclusive", default=env.get('NOSE_COVER_INCLUSIVE'), help="Include all python files under working " "directory in coverage report. Useful for " "discovering holes in test coverage if not all " "files are imported by the test suite. " "[NOSE_COVER_INCLUSIVE]") parser.add_option("--cover-html", action="store_true", default=env.get('NOSE_COVER_HTML'), dest='cover_html', help="Produce HTML coverage information") parser.add_option('--cover-html-dir', action='store', default=env.get('NOSE_COVER_HTML_DIR', 'cover'), dest='cover_html_dir', metavar='DIR', help='Produce HTML coverage information in dir') parser.add_option("--cover-branches", action="store_true", default=env.get('NOSE_COVER_BRANCHES'), dest="cover_branches", help="Include branch coverage in coverage report " "[NOSE_COVER_BRANCHES]") parser.add_option("--cover-xml", action="store_true", default=env.get('NOSE_COVER_XML'), dest="cover_xml", help="Produce XML coverage information") parser.add_option("--cover-xml-file", action="store", default=env.get('NOSE_COVER_XML_FILE', 'coverage.xml'), dest="cover_xml_file", metavar="FILE", help="Produce XML coverage information in file")
def options(self, parser, env): """ Add options to command line. """ super(Coverage, self).options(parser, env) parser.add_option("--cover-package", action="append", default=env.get('NOSE_COVER_PACKAGE'), metavar="PACKAGE", dest="cover_packages", help="Restrict coverage output to selected packages " "[NOSE_COVER_PACKAGE]") parser.add_option("--cover-erase", action="store_true", default=env.get('NOSE_COVER_ERASE'), dest="cover_erase", help="Erase previously collected coverage " "statistics before run") parser.add_option("--cover-tests", action="store_true", dest="cover_tests", default=env.get('NOSE_COVER_TESTS'), help="Include test modules in coverage report " "[NOSE_COVER_TESTS]") parser.add_option("--cover-min-percentage", action="store", dest="cover_min_percentage", default=env.get('NOSE_COVER_MIN_PERCENTAGE'), help="Minimum percentage of coverage for tests" "to pass [NOSE_COVER_MIN_PERCENTAGE]") parser.add_option("--cover-inclusive", action="store_true", dest="cover_inclusive", default=env.get('NOSE_COVER_INCLUSIVE'), help="Include all python files under working " "directory in coverage report. Useful for " "discovering holes in test coverage if not all " "files are imported by the test suite. " "[NOSE_COVER_INCLUSIVE]") parser.add_option("--cover-html", action="store_true", default=env.get('NOSE_COVER_HTML'), dest='cover_html', help="Produce HTML coverage information") parser.add_option('--cover-html-dir', action='store', default=env.get('NOSE_COVER_HTML_DIR', 'cover'), dest='cover_html_dir', metavar='DIR', help='Produce HTML coverage information in dir') parser.add_option("--cover-branches", action="store_true", default=env.get('NOSE_COVER_BRANCHES'), dest="cover_branches", help="Include branch coverage in coverage report " "[NOSE_COVER_BRANCHES]") parser.add_option("--cover-xml", action="store_true", default=env.get('NOSE_COVER_XML'), dest="cover_xml", help="Produce XML coverage information") parser.add_option("--cover-xml-file", action="store", default=env.get('NOSE_COVER_XML_FILE', 'coverage.xml'), dest="cover_xml_file", metavar="FILE", help="Produce XML coverage information in file")
[ "Add", "options", "to", "command", "line", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/cover.py#L35-L91
[ "def", "options", "(", "self", ",", "parser", ",", "env", ")", ":", "super", "(", "Coverage", ",", "self", ")", ".", "options", "(", "parser", ",", "env", ")", "parser", ".", "add_option", "(", "\"--cover-package\"", ",", "action", "=", "\"append\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_PACKAGE'", ")", ",", "metavar", "=", "\"PACKAGE\"", ",", "dest", "=", "\"cover_packages\"", ",", "help", "=", "\"Restrict coverage output to selected packages \"", "\"[NOSE_COVER_PACKAGE]\"", ")", "parser", ".", "add_option", "(", "\"--cover-erase\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_ERASE'", ")", ",", "dest", "=", "\"cover_erase\"", ",", "help", "=", "\"Erase previously collected coverage \"", "\"statistics before run\"", ")", "parser", ".", "add_option", "(", "\"--cover-tests\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"cover_tests\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_TESTS'", ")", ",", "help", "=", "\"Include test modules in coverage report \"", "\"[NOSE_COVER_TESTS]\"", ")", "parser", ".", "add_option", "(", "\"--cover-min-percentage\"", ",", "action", "=", "\"store\"", ",", "dest", "=", "\"cover_min_percentage\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_MIN_PERCENTAGE'", ")", ",", "help", "=", "\"Minimum percentage of coverage for tests\"", "\"to pass [NOSE_COVER_MIN_PERCENTAGE]\"", ")", "parser", ".", "add_option", "(", "\"--cover-inclusive\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"cover_inclusive\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_INCLUSIVE'", ")", ",", "help", "=", "\"Include all python files under working \"", "\"directory in coverage report. Useful for \"", "\"discovering holes in test coverage if not all \"", "\"files are imported by the test suite. \"", "\"[NOSE_COVER_INCLUSIVE]\"", ")", "parser", ".", "add_option", "(", "\"--cover-html\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_HTML'", ")", ",", "dest", "=", "'cover_html'", ",", "help", "=", "\"Produce HTML coverage information\"", ")", "parser", ".", "add_option", "(", "'--cover-html-dir'", ",", "action", "=", "'store'", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_HTML_DIR'", ",", "'cover'", ")", ",", "dest", "=", "'cover_html_dir'", ",", "metavar", "=", "'DIR'", ",", "help", "=", "'Produce HTML coverage information in dir'", ")", "parser", ".", "add_option", "(", "\"--cover-branches\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_BRANCHES'", ")", ",", "dest", "=", "\"cover_branches\"", ",", "help", "=", "\"Include branch coverage in coverage report \"", "\"[NOSE_COVER_BRANCHES]\"", ")", "parser", ".", "add_option", "(", "\"--cover-xml\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_XML'", ")", ",", "dest", "=", "\"cover_xml\"", ",", "help", "=", "\"Produce XML coverage information\"", ")", "parser", ".", "add_option", "(", "\"--cover-xml-file\"", ",", "action", "=", "\"store\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_COVER_XML_FILE'", ",", "'coverage.xml'", ")", ",", "dest", "=", "\"cover_xml_file\"", ",", "metavar", "=", "\"FILE\"", ",", "help", "=", "\"Produce XML coverage information in file\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Coverage.configure
Configure plugin.
environment/lib/python2.7/site-packages/nose/plugins/cover.py
def configure(self, options, conf): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass super(Coverage, self).configure(options, conf) if conf.worker: return if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = conf self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = [] if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) self.coverBranches = options.cover_branches self.coverXmlFile = None if options.cover_min_percentage: self.coverMinPercentage = int(options.cover_min_percentage.rstrip('%')) if options.cover_xml: self.coverXmlFile = options.cover_xml_file log.debug('Will put XML coverage report in %s', self.coverXmlFile) if self.enabled: self.status['active'] = True self.coverInstance = coverage.coverage(auto_data=False, branch=self.coverBranches, data_suffix=None)
def configure(self, options, conf): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass super(Coverage, self).configure(options, conf) if conf.worker: return if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = conf self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = [] if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) self.coverBranches = options.cover_branches self.coverXmlFile = None if options.cover_min_percentage: self.coverMinPercentage = int(options.cover_min_percentage.rstrip('%')) if options.cover_xml: self.coverXmlFile = options.cover_xml_file log.debug('Will put XML coverage report in %s', self.coverXmlFile) if self.enabled: self.status['active'] = True self.coverInstance = coverage.coverage(auto_data=False, branch=self.coverBranches, data_suffix=None)
[ "Configure", "plugin", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/cover.py#L93-L137
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "try", ":", "self", ".", "status", ".", "pop", "(", "'active'", ")", "except", "KeyError", ":", "pass", "super", "(", "Coverage", ",", "self", ")", ".", "configure", "(", "options", ",", "conf", ")", "if", "conf", ".", "worker", ":", "return", "if", "self", ".", "enabled", ":", "try", ":", "import", "coverage", "except", "ImportError", ":", "log", ".", "error", "(", "\"Coverage not available: \"", "\"unable to import coverage module\"", ")", "self", ".", "enabled", "=", "False", "return", "self", ".", "conf", "=", "conf", "self", ".", "coverErase", "=", "options", ".", "cover_erase", "self", ".", "coverTests", "=", "options", ".", "cover_tests", "self", ".", "coverPackages", "=", "[", "]", "if", "options", ".", "cover_packages", ":", "for", "pkgs", "in", "[", "tolist", "(", "x", ")", "for", "x", "in", "options", ".", "cover_packages", "]", ":", "self", ".", "coverPackages", ".", "extend", "(", "pkgs", ")", "self", ".", "coverInclusive", "=", "options", ".", "cover_inclusive", "if", "self", ".", "coverPackages", ":", "log", ".", "info", "(", "\"Coverage report will include only packages: %s\"", ",", "self", ".", "coverPackages", ")", "self", ".", "coverHtmlDir", "=", "None", "if", "options", ".", "cover_html", ":", "self", ".", "coverHtmlDir", "=", "options", ".", "cover_html_dir", "log", ".", "debug", "(", "'Will put HTML coverage report in %s'", ",", "self", ".", "coverHtmlDir", ")", "self", ".", "coverBranches", "=", "options", ".", "cover_branches", "self", ".", "coverXmlFile", "=", "None", "if", "options", ".", "cover_min_percentage", ":", "self", ".", "coverMinPercentage", "=", "int", "(", "options", ".", "cover_min_percentage", ".", "rstrip", "(", "'%'", ")", ")", "if", "options", ".", "cover_xml", ":", "self", ".", "coverXmlFile", "=", "options", ".", "cover_xml_file", "log", ".", "debug", "(", "'Will put XML coverage report in %s'", ",", "self", ".", "coverXmlFile", ")", "if", "self", ".", "enabled", ":", "self", ".", "status", "[", "'active'", "]", "=", "True", "self", ".", "coverInstance", "=", "coverage", ".", "coverage", "(", "auto_data", "=", "False", ",", "branch", "=", "self", ".", "coverBranches", ",", "data_suffix", "=", "None", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Coverage.begin
Begin recording coverage information.
environment/lib/python2.7/site-packages/nose/plugins/cover.py
def begin(self): """ Begin recording coverage information. """ log.debug("Coverage begin") self.skipModules = sys.modules.keys()[:] if self.coverErase: log.debug("Clearing previously collected coverage statistics") self.coverInstance.combine() self.coverInstance.erase() self.coverInstance.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]') self.coverInstance.load() self.coverInstance.start()
def begin(self): """ Begin recording coverage information. """ log.debug("Coverage begin") self.skipModules = sys.modules.keys()[:] if self.coverErase: log.debug("Clearing previously collected coverage statistics") self.coverInstance.combine() self.coverInstance.erase() self.coverInstance.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]') self.coverInstance.load() self.coverInstance.start()
[ "Begin", "recording", "coverage", "information", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/cover.py#L139-L151
[ "def", "begin", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Coverage begin\"", ")", "self", ".", "skipModules", "=", "sys", ".", "modules", ".", "keys", "(", ")", "[", ":", "]", "if", "self", ".", "coverErase", ":", "log", ".", "debug", "(", "\"Clearing previously collected coverage statistics\"", ")", "self", ".", "coverInstance", ".", "combine", "(", ")", "self", ".", "coverInstance", ".", "erase", "(", ")", "self", ".", "coverInstance", ".", "exclude", "(", "'#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]'", ")", "self", ".", "coverInstance", ".", "load", "(", ")", "self", ".", "coverInstance", ".", "start", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Coverage.report
Output code coverage report.
environment/lib/python2.7/site-packages/nose/plugins/cover.py
def report(self, stream): """ Output code coverage report. """ log.debug("Coverage report") self.coverInstance.stop() self.coverInstance.combine() self.coverInstance.save() modules = [module for name, module in sys.modules.items() if self.wantModuleCoverage(name, module)] log.debug("Coverage report will cover modules: %s", modules) self.coverInstance.report(modules, file=stream) if self.coverHtmlDir: log.debug("Generating HTML coverage report") self.coverInstance.html_report(modules, self.coverHtmlDir) if self.coverXmlFile: log.debug("Generating XML coverage report") self.coverInstance.xml_report(modules, self.coverXmlFile) # make sure we have minimum required coverage if self.coverMinPercentage: f = StringIO.StringIO() self.coverInstance.report(modules, file=f) m = re.search(r'-------\s\w+\s+\d+\s+\d+\s+(\d+)%\s+\d*\s{0,1}$', f.getvalue()) if m: percentage = int(m.groups()[0]) if percentage < self.coverMinPercentage: log.error('TOTAL Coverage did not reach minimum ' 'required: %d%%' % self.coverMinPercentage) sys.exit(1) else: log.error("No total percentage was found in coverage output, " "something went wrong.")
def report(self, stream): """ Output code coverage report. """ log.debug("Coverage report") self.coverInstance.stop() self.coverInstance.combine() self.coverInstance.save() modules = [module for name, module in sys.modules.items() if self.wantModuleCoverage(name, module)] log.debug("Coverage report will cover modules: %s", modules) self.coverInstance.report(modules, file=stream) if self.coverHtmlDir: log.debug("Generating HTML coverage report") self.coverInstance.html_report(modules, self.coverHtmlDir) if self.coverXmlFile: log.debug("Generating XML coverage report") self.coverInstance.xml_report(modules, self.coverXmlFile) # make sure we have minimum required coverage if self.coverMinPercentage: f = StringIO.StringIO() self.coverInstance.report(modules, file=f) m = re.search(r'-------\s\w+\s+\d+\s+\d+\s+(\d+)%\s+\d*\s{0,1}$', f.getvalue()) if m: percentage = int(m.groups()[0]) if percentage < self.coverMinPercentage: log.error('TOTAL Coverage did not reach minimum ' 'required: %d%%' % self.coverMinPercentage) sys.exit(1) else: log.error("No total percentage was found in coverage output, " "something went wrong.")
[ "Output", "code", "coverage", "report", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/cover.py#L153-L186
[ "def", "report", "(", "self", ",", "stream", ")", ":", "log", ".", "debug", "(", "\"Coverage report\"", ")", "self", ".", "coverInstance", ".", "stop", "(", ")", "self", ".", "coverInstance", ".", "combine", "(", ")", "self", ".", "coverInstance", ".", "save", "(", ")", "modules", "=", "[", "module", "for", "name", ",", "module", "in", "sys", ".", "modules", ".", "items", "(", ")", "if", "self", ".", "wantModuleCoverage", "(", "name", ",", "module", ")", "]", "log", ".", "debug", "(", "\"Coverage report will cover modules: %s\"", ",", "modules", ")", "self", ".", "coverInstance", ".", "report", "(", "modules", ",", "file", "=", "stream", ")", "if", "self", ".", "coverHtmlDir", ":", "log", ".", "debug", "(", "\"Generating HTML coverage report\"", ")", "self", ".", "coverInstance", ".", "html_report", "(", "modules", ",", "self", ".", "coverHtmlDir", ")", "if", "self", ".", "coverXmlFile", ":", "log", ".", "debug", "(", "\"Generating XML coverage report\"", ")", "self", ".", "coverInstance", ".", "xml_report", "(", "modules", ",", "self", ".", "coverXmlFile", ")", "# make sure we have minimum required coverage", "if", "self", ".", "coverMinPercentage", ":", "f", "=", "StringIO", ".", "StringIO", "(", ")", "self", ".", "coverInstance", ".", "report", "(", "modules", ",", "file", "=", "f", ")", "m", "=", "re", ".", "search", "(", "r'-------\\s\\w+\\s+\\d+\\s+\\d+\\s+(\\d+)%\\s+\\d*\\s{0,1}$'", ",", "f", ".", "getvalue", "(", ")", ")", "if", "m", ":", "percentage", "=", "int", "(", "m", ".", "groups", "(", ")", "[", "0", "]", ")", "if", "percentage", "<", "self", ".", "coverMinPercentage", ":", "log", ".", "error", "(", "'TOTAL Coverage did not reach minimum '", "'required: %d%%'", "%", "self", ".", "coverMinPercentage", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "log", ".", "error", "(", "\"No total percentage was found in coverage output, \"", "\"something went wrong.\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Coverage.wantFile
If inclusive coverage enabled, return true for all source files in wanted packages.
environment/lib/python2.7/site-packages/nose/plugins/cover.py
def wantFile(self, file, package=None): """If inclusive coverage enabled, return true for all source files in wanted packages. """ if self.coverInclusive: if file.endswith(".py"): if package and self.coverPackages: for want in self.coverPackages: if package.startswith(want): return True else: return True return None
def wantFile(self, file, package=None): """If inclusive coverage enabled, return true for all source files in wanted packages. """ if self.coverInclusive: if file.endswith(".py"): if package and self.coverPackages: for want in self.coverPackages: if package.startswith(want): return True else: return True return None
[ "If", "inclusive", "coverage", "enabled", "return", "true", "for", "all", "source", "files", "in", "wanted", "packages", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/cover.py#L216-L228
[ "def", "wantFile", "(", "self", ",", "file", ",", "package", "=", "None", ")", ":", "if", "self", ".", "coverInclusive", ":", "if", "file", ".", "endswith", "(", "\".py\"", ")", ":", "if", "package", "and", "self", ".", "coverPackages", ":", "for", "want", "in", "self", ".", "coverPackages", ":", "if", "package", ".", "startswith", "(", "want", ")", ":", "return", "True", "else", ":", "return", "True", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
interpret_distro_name
Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to this routine!
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py
def interpret_distro_name(location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to this routine! """ # Generate alternative interpretations of a source distro name # Because some packages are ambiguous as to name/versions split # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc. # So, we generate each possible interepretation (e.g. "adns, python-1.1.0" # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice, # the spurious interpretations should be ignored, because in the event # there's also an "adns" package, the spurious "python-1.1.0" version will # compare lower than any numeric version number, and is therefore unlikely # to match a request for it. It's still a potential problem, though, and # in the long run PyPI and the distutils should go for "safe" names and # versions in distribution archive names (sdist and bdist). parts = basename.split('-') if not py_version: for i,p in enumerate(parts[2:]): if len(p)==5 and p.startswith('py2.'): return # It's a bdist_dumb, not an sdist -- bail out for p in range(1,len(parts)+1): yield Distribution( location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]), py_version=py_version, precedence = precedence, platform = platform )
def interpret_distro_name(location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to this routine! """ # Generate alternative interpretations of a source distro name # Because some packages are ambiguous as to name/versions split # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc. # So, we generate each possible interepretation (e.g. "adns, python-1.1.0" # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice, # the spurious interpretations should be ignored, because in the event # there's also an "adns" package, the spurious "python-1.1.0" version will # compare lower than any numeric version number, and is therefore unlikely # to match a request for it. It's still a potential problem, though, and # in the long run PyPI and the distutils should go for "safe" names and # versions in distribution archive names (sdist and bdist). parts = basename.split('-') if not py_version: for i,p in enumerate(parts[2:]): if len(p)==5 and p.startswith('py2.'): return # It's a bdist_dumb, not an sdist -- bail out for p in range(1,len(parts)+1): yield Distribution( location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]), py_version=py_version, precedence = precedence, platform = platform )
[ "Generate", "alternative", "interpretations", "of", "a", "source", "distro", "name" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py#L103-L135
[ "def", "interpret_distro_name", "(", "location", ",", "basename", ",", "metadata", ",", "py_version", "=", "None", ",", "precedence", "=", "SOURCE_DIST", ",", "platform", "=", "None", ")", ":", "# Generate alternative interpretations of a source distro name", "# Because some packages are ambiguous as to name/versions split", "# e.g. \"adns-python-1.1.0\", \"egenix-mx-commercial\", etc.", "# So, we generate each possible interepretation (e.g. \"adns, python-1.1.0\"", "# \"adns-python, 1.1.0\", and \"adns-python-1.1.0, no version\"). In practice,", "# the spurious interpretations should be ignored, because in the event", "# there's also an \"adns\" package, the spurious \"python-1.1.0\" version will", "# compare lower than any numeric version number, and is therefore unlikely", "# to match a request for it. It's still a potential problem, though, and", "# in the long run PyPI and the distutils should go for \"safe\" names and", "# versions in distribution archive names (sdist and bdist).", "parts", "=", "basename", ".", "split", "(", "'-'", ")", "if", "not", "py_version", ":", "for", "i", ",", "p", "in", "enumerate", "(", "parts", "[", "2", ":", "]", ")", ":", "if", "len", "(", "p", ")", "==", "5", "and", "p", ".", "startswith", "(", "'py2.'", ")", ":", "return", "# It's a bdist_dumb, not an sdist -- bail out", "for", "p", "in", "range", "(", "1", ",", "len", "(", "parts", ")", "+", "1", ")", ":", "yield", "Distribution", "(", "location", ",", "metadata", ",", "'-'", ".", "join", "(", "parts", "[", ":", "p", "]", ")", ",", "'-'", ".", "join", "(", "parts", "[", "p", ":", "]", ")", ",", "py_version", "=", "py_version", ",", "precedence", "=", "precedence", ",", "platform", "=", "platform", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
_encode_auth
A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> _encode_auth('username%3Apassword') u'dXNlcm5hbWU6cGFzc3dvcmQ='
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py
def _encode_auth(auth): """ A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> _encode_auth('username%3Apassword') u'dXNlcm5hbWU6cGFzc3dvcmQ=' """ auth_s = urllib2.unquote(auth) # convert to bytes auth_bytes = auth_s.encode() # use the legacy interface for Python 2.3 support encoded_bytes = base64.encodestring(auth_bytes) # convert back to a string encoded = encoded_bytes.decode() # strip the trailing carriage return return encoded.rstrip()
def _encode_auth(auth): """ A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> _encode_auth('username%3Apassword') u'dXNlcm5hbWU6cGFzc3dvcmQ=' """ auth_s = urllib2.unquote(auth) # convert to bytes auth_bytes = auth_s.encode() # use the legacy interface for Python 2.3 support encoded_bytes = base64.encodestring(auth_bytes) # convert back to a string encoded = encoded_bytes.decode() # strip the trailing carriage return return encoded.rstrip()
[ "A", "function", "compatible", "with", "Python", "2", ".", "3", "-", "3", ".", "3", "that", "will", "encode", "auth", "from", "a", "URL", "suitable", "for", "an", "HTTP", "header", ".", ">>>", "_encode_auth", "(", "username%3Apassword", ")", "u", "dXNlcm5hbWU6cGFzc3dvcmQ", "=" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py#L813-L828
[ "def", "_encode_auth", "(", "auth", ")", ":", "auth_s", "=", "urllib2", ".", "unquote", "(", "auth", ")", "# convert to bytes", "auth_bytes", "=", "auth_s", ".", "encode", "(", ")", "# use the legacy interface for Python 2.3 support", "encoded_bytes", "=", "base64", ".", "encodestring", "(", "auth_bytes", ")", "# convert back to a string", "encoded", "=", "encoded_bytes", ".", "decode", "(", ")", "# strip the trailing carriage return", "return", "encoded", ".", "rstrip", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
open_with_auth
Open a urllib2 request, handling HTTP authentication
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py
def open_with_auth(url): """Open a urllib2 request, handling HTTP authentication""" scheme, netloc, path, params, query, frag = urlparse.urlparse(url) # Double scheme does not raise on Mac OS X as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): raise httplib.InvalidURL("nonnumeric port: ''") if scheme in ('http', 'https'): auth, host = urllib2.splituser(netloc) else: auth = None if auth: auth = "Basic " + _encode_auth(auth) new_url = urlparse.urlunparse((scheme,host,path,params,query,frag)) request = urllib2.Request(new_url) request.add_header("Authorization", auth) else: request = urllib2.Request(url) request.add_header('User-Agent', user_agent) fp = urllib2.urlopen(request) if auth: # Put authentication info back into request URL if same host, # so that links found on the page will work s2, h2, path2, param2, query2, frag2 = urlparse.urlparse(fp.url) if s2==scheme and h2==host: fp.url = urlparse.urlunparse((s2,netloc,path2,param2,query2,frag2)) return fp
def open_with_auth(url): """Open a urllib2 request, handling HTTP authentication""" scheme, netloc, path, params, query, frag = urlparse.urlparse(url) # Double scheme does not raise on Mac OS X as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): raise httplib.InvalidURL("nonnumeric port: ''") if scheme in ('http', 'https'): auth, host = urllib2.splituser(netloc) else: auth = None if auth: auth = "Basic " + _encode_auth(auth) new_url = urlparse.urlunparse((scheme,host,path,params,query,frag)) request = urllib2.Request(new_url) request.add_header("Authorization", auth) else: request = urllib2.Request(url) request.add_header('User-Agent', user_agent) fp = urllib2.urlopen(request) if auth: # Put authentication info back into request URL if same host, # so that links found on the page will work s2, h2, path2, param2, query2, frag2 = urlparse.urlparse(fp.url) if s2==scheme and h2==host: fp.url = urlparse.urlunparse((s2,netloc,path2,param2,query2,frag2)) return fp
[ "Open", "a", "urllib2", "request", "handling", "HTTP", "authentication" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py#L830-L863
[ "def", "open_with_auth", "(", "url", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "frag", "=", "urlparse", ".", "urlparse", "(", "url", ")", "# Double scheme does not raise on Mac OS X as revealed by a", "# failing test. We would expect \"nonnumeric port\". Refs #20.", "if", "netloc", ".", "endswith", "(", "':'", ")", ":", "raise", "httplib", ".", "InvalidURL", "(", "\"nonnumeric port: ''\"", ")", "if", "scheme", "in", "(", "'http'", ",", "'https'", ")", ":", "auth", ",", "host", "=", "urllib2", ".", "splituser", "(", "netloc", ")", "else", ":", "auth", "=", "None", "if", "auth", ":", "auth", "=", "\"Basic \"", "+", "_encode_auth", "(", "auth", ")", "new_url", "=", "urlparse", ".", "urlunparse", "(", "(", "scheme", ",", "host", ",", "path", ",", "params", ",", "query", ",", "frag", ")", ")", "request", "=", "urllib2", ".", "Request", "(", "new_url", ")", "request", ".", "add_header", "(", "\"Authorization\"", ",", "auth", ")", "else", ":", "request", "=", "urllib2", ".", "Request", "(", "url", ")", "request", ".", "add_header", "(", "'User-Agent'", ",", "user_agent", ")", "fp", "=", "urllib2", ".", "urlopen", "(", "request", ")", "if", "auth", ":", "# Put authentication info back into request URL if same host,", "# so that links found on the page will work", "s2", ",", "h2", ",", "path2", ",", "param2", ",", "query2", ",", "frag2", "=", "urlparse", ".", "urlparse", "(", "fp", ".", "url", ")", "if", "s2", "==", "scheme", "and", "h2", "==", "host", ":", "fp", ".", "url", "=", "urlparse", ".", "urlunparse", "(", "(", "s2", ",", "netloc", ",", "path2", ",", "param2", ",", "query2", ",", "frag2", ")", ")", "return", "fp" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PackageIndex.fetch_distribution
Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement` is found, the returned distribution's ``location`` is the value you would have gotten from calling the ``download()`` method with the matching distribution's URL or filename. If no matching distribution is found, ``None`` is returned. If the `source` flag is set, only source distributions and source checkout links will be considered. Unless the `develop_ok` flag is set, development and system eggs (i.e., those using the ``.egg-info`` format) will be ignored.
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py
def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None ): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement` is found, the returned distribution's ``location`` is the value you would have gotten from calling the ``download()`` method with the matching distribution's URL or filename. If no matching distribution is found, ``None`` is returned. If the `source` flag is set, only source distributions and source checkout links will be considered. Unless the `develop_ok` flag is set, development and system eggs (i.e., those using the ``.egg-info`` format) will be ignored. """ # process a Requirement self.info("Searching for %s", requirement) skipped = {} dist = None def find(req, env=None): if env is None: env = self # Find a matching distribution; may be called more than once for dist in env[req.key]: if dist.precedence==DEVELOP_DIST and not develop_ok: if dist not in skipped: self.warn("Skipping development or system egg: %s",dist) skipped[dist] = 1 continue if dist in req and (dist.precedence<=SOURCE_DIST or not source): self.info("Best match: %s", dist) return dist.clone( location=self.download(dist.location, tmpdir) ) if force_scan: self.prescan() self.find_packages(requirement) dist = find(requirement) if local_index is not None: dist = dist or find(requirement, local_index) if dist is None and self.to_scan is not None: self.prescan() dist = find(requirement) if dist is None and not force_scan: self.find_packages(requirement) dist = find(requirement) if dist is None: self.warn( "No local packages or download links found for %s%s", (source and "a source distribution of " or ""), requirement, ) return dist
def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None ): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement` is found, the returned distribution's ``location`` is the value you would have gotten from calling the ``download()`` method with the matching distribution's URL or filename. If no matching distribution is found, ``None`` is returned. If the `source` flag is set, only source distributions and source checkout links will be considered. Unless the `develop_ok` flag is set, development and system eggs (i.e., those using the ``.egg-info`` format) will be ignored. """ # process a Requirement self.info("Searching for %s", requirement) skipped = {} dist = None def find(req, env=None): if env is None: env = self # Find a matching distribution; may be called more than once for dist in env[req.key]: if dist.precedence==DEVELOP_DIST and not develop_ok: if dist not in skipped: self.warn("Skipping development or system egg: %s",dist) skipped[dist] = 1 continue if dist in req and (dist.precedence<=SOURCE_DIST or not source): self.info("Best match: %s", dist) return dist.clone( location=self.download(dist.location, tmpdir) ) if force_scan: self.prescan() self.find_packages(requirement) dist = find(requirement) if local_index is not None: dist = dist or find(requirement, local_index) if dist is None and self.to_scan is not None: self.prescan() dist = find(requirement) if dist is None and not force_scan: self.find_packages(requirement) dist = find(requirement) if dist is None: self.warn( "No local packages or download links found for %s%s", (source and "a source distribution of " or ""), requirement, ) return dist
[ "Obtain", "a", "distribution", "suitable", "for", "fulfilling", "requirement" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py#L434-L501
[ "def", "fetch_distribution", "(", "self", ",", "requirement", ",", "tmpdir", ",", "force_scan", "=", "False", ",", "source", "=", "False", ",", "develop_ok", "=", "False", ",", "local_index", "=", "None", ")", ":", "# process a Requirement", "self", ".", "info", "(", "\"Searching for %s\"", ",", "requirement", ")", "skipped", "=", "{", "}", "dist", "=", "None", "def", "find", "(", "req", ",", "env", "=", "None", ")", ":", "if", "env", "is", "None", ":", "env", "=", "self", "# Find a matching distribution; may be called more than once", "for", "dist", "in", "env", "[", "req", ".", "key", "]", ":", "if", "dist", ".", "precedence", "==", "DEVELOP_DIST", "and", "not", "develop_ok", ":", "if", "dist", "not", "in", "skipped", ":", "self", ".", "warn", "(", "\"Skipping development or system egg: %s\"", ",", "dist", ")", "skipped", "[", "dist", "]", "=", "1", "continue", "if", "dist", "in", "req", "and", "(", "dist", ".", "precedence", "<=", "SOURCE_DIST", "or", "not", "source", ")", ":", "self", ".", "info", "(", "\"Best match: %s\"", ",", "dist", ")", "return", "dist", ".", "clone", "(", "location", "=", "self", ".", "download", "(", "dist", ".", "location", ",", "tmpdir", ")", ")", "if", "force_scan", ":", "self", ".", "prescan", "(", ")", "self", ".", "find_packages", "(", "requirement", ")", "dist", "=", "find", "(", "requirement", ")", "if", "local_index", "is", "not", "None", ":", "dist", "=", "dist", "or", "find", "(", "requirement", ",", "local_index", ")", "if", "dist", "is", "None", "and", "self", ".", "to_scan", "is", "not", "None", ":", "self", ".", "prescan", "(", ")", "dist", "=", "find", "(", "requirement", ")", "if", "dist", "is", "None", "and", "not", "force_scan", ":", "self", ".", "find_packages", "(", "requirement", ")", "dist", "=", "find", "(", "requirement", ")", "if", "dist", "is", "None", ":", "self", ".", "warn", "(", "\"No local packages or download links found for %s%s\"", ",", "(", "source", "and", "\"a source distribution of \"", "or", "\"\"", ")", ",", "requirement", ",", ")", "return", "dist" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
jrepr
customized `repr()`.
jasily/utils/__init__.py
def jrepr(value): '''customized `repr()`.''' if value is None: return repr(value) t = type(value) if t.__repr__ is not object.__repr__: return repr(value) return 'object ' + t.__name__
def jrepr(value): '''customized `repr()`.''' if value is None: return repr(value) t = type(value) if t.__repr__ is not object.__repr__: return repr(value) return 'object ' + t.__name__
[ "customized", "repr", "()", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/utils/__init__.py#L11-L18
[ "def", "jrepr", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "repr", "(", "value", ")", "t", "=", "type", "(", "value", ")", "if", "t", ".", "__repr__", "is", "not", "object", ".", "__repr__", ":", "return", "repr", "(", "value", ")", "return", "'object '", "+", "t", ".", "__name__" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
get_parent
get parent from obj.
jasily/utils/__init__.py
def get_parent(obj): ''' get parent from obj. ''' names = obj.__qualname__.split('.')[:-1] if '<locals>' in names: # locals function raise ValueError('cannot get parent from locals object.') module = sys.modules[obj.__module__] parent = module while names: parent = getattr(parent, names.pop(0)) return parent
def get_parent(obj): ''' get parent from obj. ''' names = obj.__qualname__.split('.')[:-1] if '<locals>' in names: # locals function raise ValueError('cannot get parent from locals object.') module = sys.modules[obj.__module__] parent = module while names: parent = getattr(parent, names.pop(0)) return parent
[ "get", "parent", "from", "obj", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/utils/__init__.py#L21-L32
[ "def", "get_parent", "(", "obj", ")", ":", "names", "=", "obj", ".", "__qualname__", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", "if", "'<locals>'", "in", "names", ":", "# locals function", "raise", "ValueError", "(", "'cannot get parent from locals object.'", ")", "module", "=", "sys", ".", "modules", "[", "obj", ".", "__module__", "]", "parent", "=", "module", "while", "names", ":", "parent", "=", "getattr", "(", "parent", ",", "names", ".", "pop", "(", "0", ")", ")", "return", "parent" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
EnginePUBHandler.root_topic
this is a property, in case the handler is created before the engine gets registered with an id
environment/lib/python2.7/site-packages/IPython/zmq/log.py
def root_topic(self): """this is a property, in case the handler is created before the engine gets registered with an id""" if isinstance(getattr(self.engine, 'id', None), int): return "engine.%i"%self.engine.id else: return "engine"
def root_topic(self): """this is a property, in case the handler is created before the engine gets registered with an id""" if isinstance(getattr(self.engine, 'id', None), int): return "engine.%i"%self.engine.id else: return "engine"
[ "this", "is", "a", "property", "in", "case", "the", "handler", "is", "created", "before", "the", "engine", "gets", "registered", "with", "an", "id" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/log.py#L16-L22
[ "def", "root_topic", "(", "self", ")", ":", "if", "isinstance", "(", "getattr", "(", "self", ".", "engine", ",", "'id'", ",", "None", ")", ",", "int", ")", ":", "return", "\"engine.%i\"", "%", "self", ".", "engine", ".", "id", "else", ":", "return", "\"engine\"" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
init_fakemod_dict
Initialize a FakeModule instance __dict__. Kept as a standalone function and not a method so the FakeModule API can remain basically empty. This should be considered for private IPython use, used in managing namespaces for %run. Parameters ---------- fm : FakeModule instance adict : dict, optional
environment/lib/python2.7/site-packages/IPython/core/fakemodule.py
def init_fakemod_dict(fm,adict=None): """Initialize a FakeModule instance __dict__. Kept as a standalone function and not a method so the FakeModule API can remain basically empty. This should be considered for private IPython use, used in managing namespaces for %run. Parameters ---------- fm : FakeModule instance adict : dict, optional """ dct = {} # It seems pydoc (and perhaps others) needs any module instance to # implement a __nonzero__ method, so we add it if missing: dct.setdefault('__nonzero__',lambda : True) dct.setdefault('__file__',__file__) if adict is not None: dct.update(adict) # Hard assignment of the object's __dict__. This is nasty but deliberate. fm.__dict__.clear() fm.__dict__.update(dct)
def init_fakemod_dict(fm,adict=None): """Initialize a FakeModule instance __dict__. Kept as a standalone function and not a method so the FakeModule API can remain basically empty. This should be considered for private IPython use, used in managing namespaces for %run. Parameters ---------- fm : FakeModule instance adict : dict, optional """ dct = {} # It seems pydoc (and perhaps others) needs any module instance to # implement a __nonzero__ method, so we add it if missing: dct.setdefault('__nonzero__',lambda : True) dct.setdefault('__file__',__file__) if adict is not None: dct.update(adict) # Hard assignment of the object's __dict__. This is nasty but deliberate. fm.__dict__.clear() fm.__dict__.update(dct)
[ "Initialize", "a", "FakeModule", "instance", "__dict__", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/fakemodule.py#L18-L46
[ "def", "init_fakemod_dict", "(", "fm", ",", "adict", "=", "None", ")", ":", "dct", "=", "{", "}", "# It seems pydoc (and perhaps others) needs any module instance to", "# implement a __nonzero__ method, so we add it if missing:", "dct", ".", "setdefault", "(", "'__nonzero__'", ",", "lambda", ":", "True", ")", "dct", ".", "setdefault", "(", "'__file__'", ",", "__file__", ")", "if", "adict", "is", "not", "None", ":", "dct", ".", "update", "(", "adict", ")", "# Hard assignment of the object's __dict__. This is nasty but deliberate.", "fm", ".", "__dict__", ".", "clear", "(", ")", "fm", ".", "__dict__", ".", "update", "(", "dct", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
render_template
renders context aware template
toolware/utils/template.py
def render_template(content, context): """ renders context aware template """ rendered = Template(content).render(Context(context)) return rendered
def render_template(content, context): """ renders context aware template """ rendered = Template(content).render(Context(context)) return rendered
[ "renders", "context", "aware", "template" ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/template.py#L4-L7
[ "def", "render_template", "(", "content", ",", "context", ")", ":", "rendered", "=", "Template", "(", "content", ")", ".", "render", "(", "Context", "(", "context", ")", ")", "return", "rendered" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
Capture.configure
Configure plugin. Plugin is enabled by default.
environment/lib/python2.7/site-packages/nose/plugins/capture.py
def configure(self, options, conf): """Configure plugin. Plugin is enabled by default. """ self.conf = conf if not options.capture: self.enabled = False
def configure(self, options, conf): """Configure plugin. Plugin is enabled by default. """ self.conf = conf if not options.capture: self.enabled = False
[ "Configure", "plugin", ".", "Plugin", "is", "enabled", "by", "default", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/capture.py#L47-L52
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "self", ".", "conf", "=", "conf", "if", "not", "options", ".", "capture", ":", "self", ".", "enabled", "=", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Capture.formatError
Add captured output to error report.
environment/lib/python2.7/site-packages/nose/plugins/capture.py
def formatError(self, test, err): """Add captured output to error report. """ test.capturedOutput = output = self.buffer self._buf = None if not output: # Don't return None as that will prevent other # formatters from formatting and remove earlier formatters # formats, instead return the err we got return err ec, ev, tb = err return (ec, self.addCaptureToErr(ev, output), tb)
def formatError(self, test, err): """Add captured output to error report. """ test.capturedOutput = output = self.buffer self._buf = None if not output: # Don't return None as that will prevent other # formatters from formatting and remove earlier formatters # formats, instead return the err we got return err ec, ev, tb = err return (ec, self.addCaptureToErr(ev, output), tb)
[ "Add", "captured", "output", "to", "error", "report", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/capture.py#L70-L81
[ "def", "formatError", "(", "self", ",", "test", ",", "err", ")", ":", "test", ".", "capturedOutput", "=", "output", "=", "self", ".", "buffer", "self", ".", "_buf", "=", "None", "if", "not", "output", ":", "# Don't return None as that will prevent other", "# formatters from formatting and remove earlier formatters", "# formats, instead return the err we got", "return", "err", "ec", ",", "ev", ",", "tb", "=", "err", "return", "(", "ec", ",", "self", ".", "addCaptureToErr", "(", "ev", ",", "output", ")", ",", "tb", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
splitBy
Turn a list to list of list
toolware/templatetags/generic.py
def splitBy(data, num): """ Turn a list to list of list """ return [data[i:i + num] for i in range(0, len(data), num)]
def splitBy(data, num): """ Turn a list to list of list """ return [data[i:i + num] for i in range(0, len(data), num)]
[ "Turn", "a", "list", "to", "list", "of", "list" ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/templatetags/generic.py#L18-L20
[ "def", "splitBy", "(", "data", ",", "num", ")", ":", "return", "[", "data", "[", "i", ":", "i", "+", "num", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "num", ")", "]" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
convert_to_this_nbformat
Convert a notebook to the v3 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. orig_version : int The original version of the notebook to convert. orig_minor : int The original minor version of the notebook to convert (only relevant for v >= 3).
environment/lib/python2.7/site-packages/IPython/nbformat/v3/convert.py
def convert_to_this_nbformat(nb, orig_version=2, orig_minor=0): """Convert a notebook to the v3 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. orig_version : int The original version of the notebook to convert. orig_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). """ if orig_version == 1: nb = v2.convert_to_this_nbformat(nb) orig_version = 2 if orig_version == 2: # Mark the original nbformat so consumers know it has been converted. nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor nb.orig_nbformat = 2 return nb elif orig_version == 3: if orig_minor != nbformat_minor: nb.orig_nbformat_minor = orig_minor nb.nbformat_minor = nbformat_minor return nb else: raise ValueError('Cannot convert a notebook from v%s to v3' % orig_version)
def convert_to_this_nbformat(nb, orig_version=2, orig_minor=0): """Convert a notebook to the v3 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. orig_version : int The original version of the notebook to convert. orig_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). """ if orig_version == 1: nb = v2.convert_to_this_nbformat(nb) orig_version = 2 if orig_version == 2: # Mark the original nbformat so consumers know it has been converted. nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor nb.orig_nbformat = 2 return nb elif orig_version == 3: if orig_minor != nbformat_minor: nb.orig_nbformat_minor = orig_minor nb.nbformat_minor = nbformat_minor return nb else: raise ValueError('Cannot convert a notebook from v%s to v3' % orig_version)
[ "Convert", "a", "notebook", "to", "the", "v3", "format", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v3/convert.py#L30-L58
[ "def", "convert_to_this_nbformat", "(", "nb", ",", "orig_version", "=", "2", ",", "orig_minor", "=", "0", ")", ":", "if", "orig_version", "==", "1", ":", "nb", "=", "v2", ".", "convert_to_this_nbformat", "(", "nb", ")", "orig_version", "=", "2", "if", "orig_version", "==", "2", ":", "# Mark the original nbformat so consumers know it has been converted.", "nb", ".", "nbformat", "=", "nbformat", "nb", ".", "nbformat_minor", "=", "nbformat_minor", "nb", ".", "orig_nbformat", "=", "2", "return", "nb", "elif", "orig_version", "==", "3", ":", "if", "orig_minor", "!=", "nbformat_minor", ":", "nb", ".", "orig_nbformat_minor", "=", "orig_minor", "nb", ".", "nbformat_minor", "=", "nbformat_minor", "return", "nb", "else", ":", "raise", "ValueError", "(", "'Cannot convert a notebook from v%s to v3'", "%", "orig_version", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
hex_to_rgb
Convert a hex color to rgb integer tuple.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/styles.py
def hex_to_rgb(color): """Convert a hex color to rgb integer tuple.""" if color.startswith('#'): color = color[1:] if len(color) == 3: color = ''.join([c*2 for c in color]) if len(color) != 6: return False try: r = int(color[:2],16) g = int(color[2:4],16) b = int(color[4:],16) except ValueError: return False else: return r,g,b
def hex_to_rgb(color): """Convert a hex color to rgb integer tuple.""" if color.startswith('#'): color = color[1:] if len(color) == 3: color = ''.join([c*2 for c in color]) if len(color) != 6: return False try: r = int(color[:2],16) g = int(color[2:4],16) b = int(color[4:],16) except ValueError: return False else: return r,g,b
[ "Convert", "a", "hex", "color", "to", "rgb", "integer", "tuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/styles.py#L60-L75
[ "def", "hex_to_rgb", "(", "color", ")", ":", "if", "color", ".", "startswith", "(", "'#'", ")", ":", "color", "=", "color", "[", "1", ":", "]", "if", "len", "(", "color", ")", "==", "3", ":", "color", "=", "''", ".", "join", "(", "[", "c", "*", "2", "for", "c", "in", "color", "]", ")", "if", "len", "(", "color", ")", "!=", "6", ":", "return", "False", "try", ":", "r", "=", "int", "(", "color", "[", ":", "2", "]", ",", "16", ")", "g", "=", "int", "(", "color", "[", "2", ":", "4", "]", ",", "16", ")", "b", "=", "int", "(", "color", "[", "4", ":", "]", ",", "16", ")", "except", "ValueError", ":", "return", "False", "else", ":", "return", "r", ",", "g", ",", "b" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_colors
Construct the keys to be used building the base stylesheet from a templatee.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/styles.py
def get_colors(stylename): """Construct the keys to be used building the base stylesheet from a templatee.""" style = get_style_by_name(stylename) fgcolor = style.style_for_token(Token.Text)['color'] or '' if len(fgcolor) in (3,6): # could be 'abcdef' or 'ace' hex, which needs '#' prefix try: int(fgcolor, 16) except TypeError: pass else: fgcolor = "#"+fgcolor return dict( bgcolor = style.background_color, select = style.highlight_color, fgcolor = fgcolor )
def get_colors(stylename): """Construct the keys to be used building the base stylesheet from a templatee.""" style = get_style_by_name(stylename) fgcolor = style.style_for_token(Token.Text)['color'] or '' if len(fgcolor) in (3,6): # could be 'abcdef' or 'ace' hex, which needs '#' prefix try: int(fgcolor, 16) except TypeError: pass else: fgcolor = "#"+fgcolor return dict( bgcolor = style.background_color, select = style.highlight_color, fgcolor = fgcolor )
[ "Construct", "the", "keys", "to", "be", "used", "building", "the", "base", "stylesheet", "from", "a", "templatee", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/styles.py#L92-L110
[ "def", "get_colors", "(", "stylename", ")", ":", "style", "=", "get_style_by_name", "(", "stylename", ")", "fgcolor", "=", "style", ".", "style_for_token", "(", "Token", ".", "Text", ")", "[", "'color'", "]", "or", "''", "if", "len", "(", "fgcolor", ")", "in", "(", "3", ",", "6", ")", ":", "# could be 'abcdef' or 'ace' hex, which needs '#' prefix", "try", ":", "int", "(", "fgcolor", ",", "16", ")", "except", "TypeError", ":", "pass", "else", ":", "fgcolor", "=", "\"#\"", "+", "fgcolor", "return", "dict", "(", "bgcolor", "=", "style", ".", "background_color", ",", "select", "=", "style", ".", "highlight_color", ",", "fgcolor", "=", "fgcolor", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
sheet_from_template
Use one of the base templates, and set bg/fg/select colors.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/styles.py
def sheet_from_template(name, colors='lightbg'): """Use one of the base templates, and set bg/fg/select colors.""" colors = colors.lower() if colors=='lightbg': return default_light_style_template%get_colors(name) elif colors=='linux': return default_dark_style_template%get_colors(name) elif colors=='nocolor': return default_bw_style_sheet else: raise KeyError("No such color scheme: %s"%colors)
def sheet_from_template(name, colors='lightbg'): """Use one of the base templates, and set bg/fg/select colors.""" colors = colors.lower() if colors=='lightbg': return default_light_style_template%get_colors(name) elif colors=='linux': return default_dark_style_template%get_colors(name) elif colors=='nocolor': return default_bw_style_sheet else: raise KeyError("No such color scheme: %s"%colors)
[ "Use", "one", "of", "the", "base", "templates", "and", "set", "bg", "/", "fg", "/", "select", "colors", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/styles.py#L112-L122
[ "def", "sheet_from_template", "(", "name", ",", "colors", "=", "'lightbg'", ")", ":", "colors", "=", "colors", ".", "lower", "(", ")", "if", "colors", "==", "'lightbg'", ":", "return", "default_light_style_template", "%", "get_colors", "(", "name", ")", "elif", "colors", "==", "'linux'", ":", "return", "default_dark_style_template", "%", "get_colors", "(", "name", ")", "elif", "colors", "==", "'nocolor'", ":", "return", "default_bw_style_sheet", "else", ":", "raise", "KeyError", "(", "\"No such color scheme: %s\"", "%", "colors", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_font
Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object
environment/lib/python2.7/site-packages/IPython/frontend/qt/util.py
def get_font(family, fallback=None): """Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object """ font = QtGui.QFont(family) # Check whether we got what we wanted using QFontInfo, since exactMatch() # is overly strict and returns false in too many cases. font_info = QtGui.QFontInfo(font) if fallback is not None and font_info.family() != family: font = QtGui.QFont(fallback) return font
def get_font(family, fallback=None): """Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object """ font = QtGui.QFont(family) # Check whether we got what we wanted using QFontInfo, since exactMatch() # is overly strict and returns false in too many cases. font_info = QtGui.QFontInfo(font) if fallback is not None and font_info.family() != family: font = QtGui.QFont(fallback) return font
[ "Return", "a", "font", "of", "the", "requested", "family", "using", "fallback", "as", "alternative", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/util.py#L82-L106
[ "def", "get_font", "(", "family", ",", "fallback", "=", "None", ")", ":", "font", "=", "QtGui", ".", "QFont", "(", "family", ")", "# Check whether we got what we wanted using QFontInfo, since exactMatch()", "# is overly strict and returns false in too many cases.", "font_info", "=", "QtGui", ".", "QFontInfo", "(", "font", ")", "if", "fallback", "is", "not", "None", "and", "font_info", ".", "family", "(", ")", "!=", "family", ":", "font", "=", "QtGui", ".", "QFont", "(", "fallback", ")", "return", "font" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._handle_complete_reply
Reimplemented to support IPython's improved completion machinery.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _handle_complete_reply(self, rep): """ Reimplemented to support IPython's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): matches = rep['content']['matches'] text = rep['content']['matched_text'] offset = len(text) # Clean up matches with period and path separators if the matched # text has not been transformed. This is done by truncating all # but the last component and then suitably decreasing the offset # between the current cursor position and the start of completion. if len(matches) > 1 and matches[0][:offset] == text: parts = re.split(r'[./\\]', text) sep_count = len(parts) - 1 if sep_count: chop_length = sum(map(len, parts[:sep_count])) + sep_count matches = [ match[chop_length:] for match in matches ] offset -= chop_length # Move the cursor to the start of the match and complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches)
def _handle_complete_reply(self, rep): """ Reimplemented to support IPython's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): matches = rep['content']['matches'] text = rep['content']['matched_text'] offset = len(text) # Clean up matches with period and path separators if the matched # text has not been transformed. This is done by truncating all # but the last component and then suitably decreasing the offset # between the current cursor position and the start of completion. if len(matches) > 1 and matches[0][:offset] == text: parts = re.split(r'[./\\]', text) sep_count = len(parts) - 1 if sep_count: chop_length = sum(map(len, parts[:sep_count])) + sep_count matches = [ match[chop_length:] for match in matches ] offset -= chop_length # Move the cursor to the start of the match and complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches)
[ "Reimplemented", "to", "support", "IPython", "s", "improved", "completion", "machinery", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L138-L164
[ "def", "_handle_complete_reply", "(", "self", ",", "rep", ")", ":", "self", ".", "log", ".", "debug", "(", "\"complete: %s\"", ",", "rep", ".", "get", "(", "'content'", ",", "''", ")", ")", "cursor", "=", "self", ".", "_get_cursor", "(", ")", "info", "=", "self", ".", "_request_info", ".", "get", "(", "'complete'", ")", "if", "info", "and", "info", ".", "id", "==", "rep", "[", "'parent_header'", "]", "[", "'msg_id'", "]", "and", "info", ".", "pos", "==", "cursor", ".", "position", "(", ")", ":", "matches", "=", "rep", "[", "'content'", "]", "[", "'matches'", "]", "text", "=", "rep", "[", "'content'", "]", "[", "'matched_text'", "]", "offset", "=", "len", "(", "text", ")", "# Clean up matches with period and path separators if the matched", "# text has not been transformed. This is done by truncating all", "# but the last component and then suitably decreasing the offset", "# between the current cursor position and the start of completion.", "if", "len", "(", "matches", ")", ">", "1", "and", "matches", "[", "0", "]", "[", ":", "offset", "]", "==", "text", ":", "parts", "=", "re", ".", "split", "(", "r'[./\\\\]'", ",", "text", ")", "sep_count", "=", "len", "(", "parts", ")", "-", "1", "if", "sep_count", ":", "chop_length", "=", "sum", "(", "map", "(", "len", ",", "parts", "[", ":", "sep_count", "]", ")", ")", "+", "sep_count", "matches", "=", "[", "match", "[", "chop_length", ":", "]", "for", "match", "in", "matches", "]", "offset", "-=", "chop_length", "# Move the cursor to the start of the match and complete.", "cursor", ".", "movePosition", "(", "QtGui", ".", "QTextCursor", ".", "Left", ",", "n", "=", "offset", ")", "self", ".", "_complete_with_items", "(", "cursor", ",", "matches", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._handle_execute_reply
Reimplemented to support prompt requests.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': number = msg['content']['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(IPythonWidget, self)._handle_execute_reply(msg)
def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': number = msg['content']['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(IPythonWidget, self)._handle_execute_reply(msg)
[ "Reimplemented", "to", "support", "prompt", "requests", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L166-L176
[ "def", "_handle_execute_reply", "(", "self", ",", "msg", ")", ":", "msg_id", "=", "msg", "[", "'parent_header'", "]", ".", "get", "(", "'msg_id'", ")", "info", "=", "self", ".", "_request_info", "[", "'execute'", "]", ".", "get", "(", "msg_id", ")", "if", "info", "and", "info", ".", "kind", "==", "'prompt'", ":", "number", "=", "msg", "[", "'content'", "]", "[", "'execution_count'", "]", "+", "1", "self", ".", "_show_interpreter_prompt", "(", "number", ")", "self", ".", "_request_info", "[", "'execute'", "]", ".", "pop", "(", "msg_id", ")", "else", ":", "super", "(", "IPythonWidget", ",", "self", ")", ".", "_handle_execute_reply", "(", "msg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._handle_history_reply
Implemented to handle history tail replies, which are only supported by the IPython kernel.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _handle_history_reply(self, msg): """ Implemented to handle history tail replies, which are only supported by the IPython kernel. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed at 0.1s time.sleep(0.25) self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug("Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items)
def _handle_history_reply(self, msg): """ Implemented to handle history tail replies, which are only supported by the IPython kernel. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed at 0.1s time.sleep(0.25) self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug("Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items)
[ "Implemented", "to", "handle", "history", "tail", "replies", "which", "are", "only", "supported", "by", "the", "IPython", "kernel", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L178-L209
[ "def", "_handle_history_reply", "(", "self", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "if", "'history'", "not", "in", "content", ":", "self", ".", "log", ".", "error", "(", "\"History request failed: %r\"", "%", "content", ")", "if", "content", ".", "get", "(", "'status'", ",", "''", ")", "==", "'aborted'", "and", "not", "self", ".", "_retrying_history_request", ":", "# a *different* action caused this request to be aborted, so", "# we should try again.", "self", ".", "log", ".", "error", "(", "\"Retrying aborted history request\"", ")", "# prevent multiple retries of aborted requests:", "self", ".", "_retrying_history_request", "=", "True", "# wait out the kernel's queue flush, which is currently timed at 0.1s", "time", ".", "sleep", "(", "0.25", ")", "self", ".", "kernel_manager", ".", "shell_channel", ".", "history", "(", "hist_access_type", "=", "'tail'", ",", "n", "=", "1000", ")", "else", ":", "self", ".", "_retrying_history_request", "=", "False", "return", "# reset retry flag", "self", ".", "_retrying_history_request", "=", "False", "history_items", "=", "content", "[", "'history'", "]", "self", ".", "log", ".", "debug", "(", "\"Received history reply with %i entries\"", ",", "len", "(", "history_items", ")", ")", "items", "=", "[", "]", "last_cell", "=", "u\"\"", "for", "_", ",", "_", ",", "cell", "in", "history_items", ":", "cell", "=", "cell", ".", "rstrip", "(", ")", "if", "cell", "!=", "last_cell", ":", "items", ".", "append", "(", "cell", ")", "last_cell", "=", "cell", "self", ".", "_set_history", "(", "items", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._handle_pyout
Reimplemented for IPython-style "display hook".
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _handle_pyout(self, msg): """ Reimplemented for IPython-style "display hook". """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data.has_key('text/html'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) html = data['text/html'] self._append_plain_text('\n', True) self._append_html(html + self.output_sep2, True) elif data.has_key('text/plain'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True)
def _handle_pyout(self, msg): """ Reimplemented for IPython-style "display hook". """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data.has_key('text/html'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) html = data['text/html'] self._append_plain_text('\n', True) self._append_html(html + self.output_sep2, True) elif data.has_key('text/plain'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True)
[ "Reimplemented", "for", "IPython", "-", "style", "display", "hook", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L211-L233
[ "def", "_handle_pyout", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"pyout: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "if", "not", "self", ".", "_hidden", "and", "self", ".", "_is_from_this_session", "(", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "prompt_number", "=", "content", ".", "get", "(", "'execution_count'", ",", "0", ")", "data", "=", "content", "[", "'data'", "]", "if", "data", ".", "has_key", "(", "'text/html'", ")", ":", "self", ".", "_append_plain_text", "(", "self", ".", "output_sep", ",", "True", ")", "self", ".", "_append_html", "(", "self", ".", "_make_out_prompt", "(", "prompt_number", ")", ",", "True", ")", "html", "=", "data", "[", "'text/html'", "]", "self", ".", "_append_plain_text", "(", "'\\n'", ",", "True", ")", "self", ".", "_append_html", "(", "html", "+", "self", ".", "output_sep2", ",", "True", ")", "elif", "data", ".", "has_key", "(", "'text/plain'", ")", ":", "self", ".", "_append_plain_text", "(", "self", ".", "output_sep", ",", "True", ")", "self", ".", "_append_html", "(", "self", ".", "_make_out_prompt", "(", "prompt_number", ")", ",", "True", ")", "text", "=", "data", "[", "'text/plain'", "]", "# If the repr is multiline, make sure we start on a new line,", "# so that its lines are aligned.", "if", "\"\\n\"", "in", "text", "and", "not", "self", ".", "output_sep", ".", "endswith", "(", "\"\\n\"", ")", ":", "self", ".", "_append_plain_text", "(", "'\\n'", ",", "True", ")", "self", ".", "_append_plain_text", "(", "text", "+", "self", ".", "output_sep2", ",", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._handle_display_data
The base handler for the ``display_data`` message.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _handle_display_data(self, msg): """ The base handler for the ``display_data`` message. """ self.log.debug("display: %s", msg.get('content', '')) # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular IPythonWidget, we simply print the plain text # representation. if data.has_key('text/html'): html = data['text/html'] self._append_html(html, True) elif data.has_key('text/plain'): text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True)
def _handle_display_data(self, msg): """ The base handler for the ``display_data`` message. """ self.log.debug("display: %s", msg.get('content', '')) # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular IPythonWidget, we simply print the plain text # representation. if data.has_key('text/html'): html = data['text/html'] self._append_html(html, True) elif data.has_key('text/plain'): text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True)
[ "The", "base", "handler", "for", "the", "display_data", "message", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L235-L255
[ "def", "_handle_display_data", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"display: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "# For now, we don't display data from other frontends, but we", "# eventually will as this allows all frontends to monitor the display", "# data. But we need to figure out how to handle this in the GUI.", "if", "not", "self", ".", "_hidden", "and", "self", ".", "_is_from_this_session", "(", "msg", ")", ":", "source", "=", "msg", "[", "'content'", "]", "[", "'source'", "]", "data", "=", "msg", "[", "'content'", "]", "[", "'data'", "]", "metadata", "=", "msg", "[", "'content'", "]", "[", "'metadata'", "]", "# In the regular IPythonWidget, we simply print the plain text", "# representation.", "if", "data", ".", "has_key", "(", "'text/html'", ")", ":", "html", "=", "data", "[", "'text/html'", "]", "self", ".", "_append_html", "(", "html", ",", "True", ")", "elif", "data", ".", "has_key", "(", "'text/plain'", ")", ":", "text", "=", "data", "[", "'text/plain'", "]", "self", ".", "_append_plain_text", "(", "text", ",", "True", ")", "# This newline seems to be needed for text and html output.", "self", ".", "_append_plain_text", "(", "u'\\n'", ",", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._started_channels
Reimplemented to make a history request and load %guiref.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _started_channels(self): """Reimplemented to make a history request and load %guiref.""" super(IPythonWidget, self)._started_channels() self._load_guiref_magic() self.kernel_manager.shell_channel.history(hist_access_type='tail', n=1000)
def _started_channels(self): """Reimplemented to make a history request and load %guiref.""" super(IPythonWidget, self)._started_channels() self._load_guiref_magic() self.kernel_manager.shell_channel.history(hist_access_type='tail', n=1000)
[ "Reimplemented", "to", "make", "a", "history", "request", "and", "load", "%guiref", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L257-L262
[ "def", "_started_channels", "(", "self", ")", ":", "super", "(", "IPythonWidget", ",", "self", ")", ".", "_started_channels", "(", ")", "self", ".", "_load_guiref_magic", "(", ")", "self", ".", "kernel_manager", ".", "shell_channel", ".", "history", "(", "hist_access_type", "=", "'tail'", ",", "n", "=", "1000", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget.execute_file
Reimplemented to use the 'run' magic.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using %run directly, but while we # are, it is necessary to quote or escape filenames containing spaces # or quotes. # In earlier code here, to minimize escaping, we sometimes quoted the # filename with single quotes. But to do this, this code must be # platform-aware, because run uses shlex rather than python string # parsing, so that: # * In Win: single quotes can be used in the filename without quoting, # and we cannot use single quotes to quote the filename. # * In *nix: we can escape double quotes in a double quoted filename, # but can't escape single quotes in a single quoted filename. # So to keep this code non-platform-specific and simple, we now only # use double quotes to quote filenames, and escape when needed: if ' ' in path or "'" in path or '"' in path: path = '"%s"' % path.replace('"', '\\"') self.execute('%%run %s' % path, hidden=hidden)
def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using %run directly, but while we # are, it is necessary to quote or escape filenames containing spaces # or quotes. # In earlier code here, to minimize escaping, we sometimes quoted the # filename with single quotes. But to do this, this code must be # platform-aware, because run uses shlex rather than python string # parsing, so that: # * In Win: single quotes can be used in the filename without quoting, # and we cannot use single quotes to quote the filename. # * In *nix: we can escape double quotes in a double quoted filename, # but can't escape single quotes in a single quoted filename. # So to keep this code non-platform-specific and simple, we now only # use double quotes to quote filenames, and escape when needed: if ' ' in path or "'" in path or '"' in path: path = '"%s"' % path.replace('"', '\\"') self.execute('%%run %s' % path, hidden=hidden)
[ "Reimplemented", "to", "use", "the", "run", "magic", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L287-L311
[ "def", "execute_file", "(", "self", ",", "path", ",", "hidden", "=", "False", ")", ":", "# Use forward slashes on Windows to avoid escaping each separator.", "if", "sys", ".", "platform", "==", "'win32'", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "# Perhaps we should not be using %run directly, but while we", "# are, it is necessary to quote or escape filenames containing spaces ", "# or quotes. ", "# In earlier code here, to minimize escaping, we sometimes quoted the ", "# filename with single quotes. But to do this, this code must be", "# platform-aware, because run uses shlex rather than python string", "# parsing, so that:", "# * In Win: single quotes can be used in the filename without quoting,", "# and we cannot use single quotes to quote the filename.", "# * In *nix: we can escape double quotes in a double quoted filename,", "# but can't escape single quotes in a single quoted filename.", "# So to keep this code non-platform-specific and simple, we now only", "# use double quotes to quote filenames, and escape when needed:", "if", "' '", "in", "path", "or", "\"'\"", "in", "path", "or", "'\"'", "in", "path", ":", "path", "=", "'\"%s\"'", "%", "path", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "self", ".", "execute", "(", "'%%run %s'", "%", "path", ",", "hidden", "=", "hidden", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._complete
Reimplemented to support IPython's improved completion machinery.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _complete(self): """ Reimplemented to support IPython's improved completion machinery. """ # We let the kernel split the input line, so we *always* send an empty # text field. Readline-based frontends do get a real text field which # they can use. text = '' # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( text, # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info
def _complete(self): """ Reimplemented to support IPython's improved completion machinery. """ # We let the kernel split the input line, so we *always* send an empty # text field. Readline-based frontends do get a real text field which # they can use. text = '' # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( text, # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info
[ "Reimplemented", "to", "support", "IPython", "s", "improved", "completion", "machinery", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L317-L333
[ "def", "_complete", "(", "self", ")", ":", "# We let the kernel split the input line, so we *always* send an empty", "# text field. Readline-based frontends do get a real text field which", "# they can use.", "text", "=", "''", "# Send the completion request to the kernel", "msg_id", "=", "self", ".", "kernel_manager", ".", "shell_channel", ".", "complete", "(", "text", ",", "# text", "self", ".", "_get_input_buffer_cursor_line", "(", ")", ",", "# line", "self", ".", "_get_input_buffer_cursor_column", "(", ")", ",", "# cursor_pos", "self", ".", "input_buffer", ")", "# block", "pos", "=", "self", ".", "_get_cursor", "(", ")", ".", "position", "(", ")", "info", "=", "self", ".", "_CompletionRequest", "(", "msg_id", ",", "pos", ")", "self", ".", "_request_info", "[", "'complete'", "]", "=", "info" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._process_execute_error
Reimplemented for IPython-style traceback formatting.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # the html renderer yet. Once we refactor ultratb to produce # properly styled tracebacks, this branch should be the default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi escapes self._append_plain_text(traceback)
def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # the html renderer yet. Once we refactor ultratb to produce # properly styled tracebacks, this branch should be the default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi escapes self._append_plain_text(traceback)
[ "Reimplemented", "for", "IPython", "-", "style", "traceback", "formatting", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L335-L354
[ "def", "_process_execute_error", "(", "self", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "traceback", "=", "'\\n'", ".", "join", "(", "content", "[", "'traceback'", "]", ")", "+", "'\\n'", "if", "False", ":", "# FIXME: For now, tracebacks come as plain text, so we can't use", "# the html renderer yet. Once we refactor ultratb to produce", "# properly styled tracebacks, this branch should be the default", "traceback", "=", "traceback", ".", "replace", "(", "' '", ",", "'&nbsp;'", ")", "traceback", "=", "traceback", ".", "replace", "(", "'\\n'", ",", "'<br/>'", ")", "ename", "=", "content", "[", "'ename'", "]", "ename_styled", "=", "'<span class=\"error\">%s</span>'", "%", "ename", "traceback", "=", "traceback", ".", "replace", "(", "ename", ",", "ename_styled", ")", "self", ".", "_append_html", "(", "traceback", ")", "else", ":", "# This is the fallback for now, using plain text with ansi escapes", "self", ".", "_append_plain_text", "(", "traceback", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._process_execute_payload
Reimplemented to dispatch payloads to handler methods.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True
def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True
[ "Reimplemented", "to", "dispatch", "payloads", "to", "handler", "methods", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L356-L365
[ "def", "_process_execute_payload", "(", "self", ",", "item", ")", ":", "handler", "=", "self", ".", "_payload_handlers", ".", "get", "(", "item", "[", "'source'", "]", ")", "if", "handler", "is", "None", ":", "# We have no handler for this type of payload, simply ignore it", "return", "False", "else", ":", "handler", "(", "item", ")", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._show_interpreter_prompt
Reimplemented for IPython-style prompts.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_manager.shell_channel.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True)
def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_manager.shell_channel.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True)
[ "Reimplemented", "for", "IPython", "-", "style", "prompts", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L367-L387
[ "def", "_show_interpreter_prompt", "(", "self", ",", "number", "=", "None", ")", ":", "# If a number was not specified, make a prompt number request.", "if", "number", "is", "None", ":", "msg_id", "=", "self", ".", "kernel_manager", ".", "shell_channel", ".", "execute", "(", "''", ",", "silent", "=", "True", ")", "info", "=", "self", ".", "_ExecutionRequest", "(", "msg_id", ",", "'prompt'", ")", "self", ".", "_request_info", "[", "'execute'", "]", "[", "msg_id", "]", "=", "info", "return", "# Show a new prompt and save information about it so that it can be", "# updated later if the prompt number turns out to be wrong.", "self", ".", "_prompt_sep", "=", "self", ".", "input_sep", "self", ".", "_show_prompt", "(", "self", ".", "_make_in_prompt", "(", "number", ")", ",", "html", "=", "True", ")", "block", "=", "self", ".", "_control", ".", "document", "(", ")", ".", "lastBlock", "(", ")", "length", "=", "len", "(", "self", ".", "_prompt", ")", "self", ".", "_previous_prompt_obj", "=", "self", ".", "_PromptBlock", "(", "block", ",", "length", ",", "number", ")", "# Update continuation prompt to reflect (possibly) new prompt length.", "self", ".", "_set_continuation_prompt", "(", "self", ".", "_make_continuation_prompt", "(", "self", ".", "_prompt", ")", ",", "html", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._show_interpreter_prompt_for_reply
Reimplemented for IPython-style prompts.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1)
def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1)
[ "Reimplemented", "for", "IPython", "-", "style", "prompts", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L389-L425
[ "def", "_show_interpreter_prompt_for_reply", "(", "self", ",", "msg", ")", ":", "# Update the old prompt number if necessary.", "content", "=", "msg", "[", "'content'", "]", "# abort replies do not have any keys:", "if", "content", "[", "'status'", "]", "==", "'aborted'", ":", "if", "self", ".", "_previous_prompt_obj", ":", "previous_prompt_number", "=", "self", ".", "_previous_prompt_obj", ".", "number", "else", ":", "previous_prompt_number", "=", "0", "else", ":", "previous_prompt_number", "=", "content", "[", "'execution_count'", "]", "if", "self", ".", "_previous_prompt_obj", "and", "self", ".", "_previous_prompt_obj", ".", "number", "!=", "previous_prompt_number", ":", "block", "=", "self", ".", "_previous_prompt_obj", ".", "block", "# Make sure the prompt block has not been erased.", "if", "block", ".", "isValid", "(", ")", "and", "block", ".", "text", "(", ")", ":", "# Remove the old prompt and insert a new prompt.", "cursor", "=", "QtGui", ".", "QTextCursor", "(", "block", ")", "cursor", ".", "movePosition", "(", "QtGui", ".", "QTextCursor", ".", "Right", ",", "QtGui", ".", "QTextCursor", ".", "KeepAnchor", ",", "self", ".", "_previous_prompt_obj", ".", "length", ")", "prompt", "=", "self", ".", "_make_in_prompt", "(", "previous_prompt_number", ")", "self", ".", "_prompt", "=", "self", ".", "_insert_html_fetching_plain_text", "(", "cursor", ",", "prompt", ")", "# When the HTML is inserted, Qt blows away the syntax", "# highlighting for the line, so we need to rehighlight it.", "self", ".", "_highlighter", ".", "rehighlightBlock", "(", "cursor", ".", "block", "(", ")", ")", "self", ".", "_previous_prompt_obj", "=", "None", "# Show a new prompt with the kernel's estimated prompt number.", "self", ".", "_show_interpreter_prompt", "(", "previous_prompt_number", "+", "1", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget.set_default_style
Sets the widget style to the class defaults. Parameters: ----------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters: ----------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. """ colors = colors.lower() if colors=='lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors=='linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors=='nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s"%colors)
def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters: ----------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. """ colors = colors.lower() if colors=='lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors=='linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors=='nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s"%colors)
[ "Sets", "the", "widget", "style", "to", "the", "class", "defaults", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L431-L451
[ "def", "set_default_style", "(", "self", ",", "colors", "=", "'lightbg'", ")", ":", "colors", "=", "colors", ".", "lower", "(", ")", "if", "colors", "==", "'lightbg'", ":", "self", ".", "style_sheet", "=", "styles", ".", "default_light_style_sheet", "self", ".", "syntax_style", "=", "styles", ".", "default_light_syntax_style", "elif", "colors", "==", "'linux'", ":", "self", ".", "style_sheet", "=", "styles", ".", "default_dark_style_sheet", "self", ".", "syntax_style", "=", "styles", ".", "default_dark_syntax_style", "elif", "colors", "==", "'nocolor'", ":", "self", ".", "style_sheet", "=", "styles", ".", "default_bw_style_sheet", "self", ".", "syntax_style", "=", "styles", ".", "default_bw_syntax_style", "else", ":", "raise", "KeyError", "(", "\"No such color scheme: %s\"", "%", "colors", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._edit
Opens a Python script for editing. Parameters: ----------- filename : str A path to a local system file. line : int, optional A line of interest in the file.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters: ----------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `IPythonWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command)
def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters: ----------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `IPythonWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command)
[ "Opens", "a", "Python", "script", "for", "editing", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L457-L494
[ "def", "_edit", "(", "self", ",", "filename", ",", "line", "=", "None", ")", ":", "if", "self", ".", "custom_edit", ":", "self", ".", "custom_edit_requested", ".", "emit", "(", "filename", ",", "line", ")", "elif", "not", "self", ".", "editor", ":", "self", ".", "_append_plain_text", "(", "'No default editor available.\\n'", "'Specify a GUI text editor in the `IPythonWidget.editor` '", "'configurable to enable the %edit magic'", ")", "else", ":", "try", ":", "filename", "=", "'\"%s\"'", "%", "filename", "if", "line", "and", "self", ".", "editor_line", ":", "command", "=", "self", ".", "editor_line", ".", "format", "(", "filename", "=", "filename", ",", "line", "=", "line", ")", "else", ":", "try", ":", "command", "=", "self", ".", "editor", ".", "format", "(", ")", "except", "KeyError", ":", "command", "=", "self", ".", "editor", ".", "format", "(", "filename", "=", "filename", ")", "else", ":", "command", "+=", "' '", "+", "filename", "except", "KeyError", ":", "self", ".", "_append_plain_text", "(", "'Invalid editor command.\\n'", ")", "else", ":", "try", ":", "Popen", "(", "command", ",", "shell", "=", "True", ")", "except", "OSError", ":", "msg", "=", "'Opening editor with command \"%s\" failed.\\n'", "self", ".", "_append_plain_text", "(", "msg", "%", "command", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._make_in_prompt
Given a prompt number, returns an HTML In prompt.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' body = self.in_prompt return '<span class="in-prompt">%s</span>' % body
def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' body = self.in_prompt return '<span class="in-prompt">%s</span>' % body
[ "Given", "a", "prompt", "number", "returns", "an", "HTML", "In", "prompt", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L496-L504
[ "def", "_make_in_prompt", "(", "self", ",", "number", ")", ":", "try", ":", "body", "=", "self", ".", "in_prompt", "%", "number", "except", "TypeError", ":", "# allow in_prompt to leave out number, e.g. '>>> '", "body", "=", "self", ".", "in_prompt", "return", "'<span class=\"in-prompt\">%s</span>'", "%", "body" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._make_continuation_prompt
Given a plain text version of an In prompt, returns an HTML continuation prompt.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body
def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body
[ "Given", "a", "plain", "text", "version", "of", "an", "In", "prompt", "returns", "an", "HTML", "continuation", "prompt", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L506-L513
[ "def", "_make_continuation_prompt", "(", "self", ",", "prompt", ")", ":", "end_chars", "=", "'...: '", "space_count", "=", "len", "(", "prompt", ".", "lstrip", "(", "'\\n'", ")", ")", "-", "len", "(", "end_chars", ")", "body", "=", "'&nbsp;'", "*", "space_count", "+", "end_chars", "return", "'<span class=\"in-prompt\">%s</span>'", "%", "body" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._style_sheet_changed
Set the style sheets of the underlying widgets.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().color() self._ansi_processor.set_background_color(bg_color) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet(self.style_sheet)
def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().color() self._ansi_processor.set_background_color(bg_color) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet(self.style_sheet)
[ "Set", "the", "style", "sheets", "of", "the", "underlying", "widgets", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L548-L558
[ "def", "_style_sheet_changed", "(", "self", ")", ":", "self", ".", "setStyleSheet", "(", "self", ".", "style_sheet", ")", "if", "self", ".", "_control", "is", "not", "None", ":", "self", ".", "_control", ".", "document", "(", ")", ".", "setDefaultStyleSheet", "(", "self", ".", "style_sheet", ")", "bg_color", "=", "self", ".", "_control", ".", "palette", "(", ")", ".", "window", "(", ")", ".", "color", "(", ")", "self", ".", "_ansi_processor", ".", "set_background_color", "(", "bg_color", ")", "if", "self", ".", "_page_control", "is", "not", "None", ":", "self", ".", "_page_control", ".", "document", "(", ")", ".", "setDefaultStyleSheet", "(", "self", ".", "style_sheet", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonWidget._syntax_style_changed
Set the style for the syntax highlighter.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py
def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet)
def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet)
[ "Set", "the", "style", "for", "the", "syntax", "highlighter", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ipython_widget.py#L562-L571
[ "def", "_syntax_style_changed", "(", "self", ")", ":", "if", "self", ".", "_highlighter", "is", "None", ":", "# ignore premature calls", "return", "if", "self", ".", "syntax_style", ":", "self", ".", "_highlighter", ".", "set_style", "(", "self", ".", "syntax_style", ")", "else", ":", "self", ".", "_highlighter", ".", "set_style_sheet", "(", "self", ".", "style_sheet", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CloudStack.request
Async co-routine to perform requests to a CloudStackAPI. The parameters needs to include the command string, which refers to the API to be called. In principle any available and future CloudStack API can be called. The `**kwargs` magic allows us to all add supported parameters to the given API call. A list of all available APIs can found at https://cloudstack.apache.org/api/apidocs-4.8/TOC_User.html :param command: Command string indicating the CloudStack API to be called. :type command: str :param kwargs: Parameters to be passed to the CloudStack API :return: Dictionary containing the decoded json reply of the CloudStack API :rtype: dict
CloudStackAIO/CloudStack.py
async def request(self, command: str, **kwargs) -> dict: """ Async co-routine to perform requests to a CloudStackAPI. The parameters needs to include the command string, which refers to the API to be called. In principle any available and future CloudStack API can be called. The `**kwargs` magic allows us to all add supported parameters to the given API call. A list of all available APIs can found at https://cloudstack.apache.org/api/apidocs-4.8/TOC_User.html :param command: Command string indicating the CloudStack API to be called. :type command: str :param kwargs: Parameters to be passed to the CloudStack API :return: Dictionary containing the decoded json reply of the CloudStack API :rtype: dict """ kwargs.update(dict(apikey=self.api_key, command=command, response='json')) if 'list' in command.lower(): # list APIs can be paginated, therefore include max_page_size and page parameter kwargs.update(dict(pagesize=self.max_page_size, page=1)) final_data = dict() while True: async with self.client_session.get(self.end_point, params=self._sign(kwargs)) as response: data = await self._handle_response(response=response, await_final_result='queryasyncjobresult' not in command.lower()) try: count = data.pop('count') except KeyError: if not data: # Empty dictionary is returned in case a query does not contain any results. # Can happen also if a listAPI is called with a page that does not exits. Therefore, final_data # has to be returned in order to return all results from preceding pages. return final_data else: # Only list API calls have a 'count' key inside the response, # return data as it is in other cases! return data else: # update final_data using paginated results, dictionaries of the response contain the count key # and one key pointing to the actual data values for key, value in data.items(): final_data.setdefault(key, []).extend(value) final_data['count'] = final_data.setdefault('count', 0) + count kwargs['page'] += 1 if count < self.max_page_size: # no more pages exists return final_data
async def request(self, command: str, **kwargs) -> dict: """ Async co-routine to perform requests to a CloudStackAPI. The parameters needs to include the command string, which refers to the API to be called. In principle any available and future CloudStack API can be called. The `**kwargs` magic allows us to all add supported parameters to the given API call. A list of all available APIs can found at https://cloudstack.apache.org/api/apidocs-4.8/TOC_User.html :param command: Command string indicating the CloudStack API to be called. :type command: str :param kwargs: Parameters to be passed to the CloudStack API :return: Dictionary containing the decoded json reply of the CloudStack API :rtype: dict """ kwargs.update(dict(apikey=self.api_key, command=command, response='json')) if 'list' in command.lower(): # list APIs can be paginated, therefore include max_page_size and page parameter kwargs.update(dict(pagesize=self.max_page_size, page=1)) final_data = dict() while True: async with self.client_session.get(self.end_point, params=self._sign(kwargs)) as response: data = await self._handle_response(response=response, await_final_result='queryasyncjobresult' not in command.lower()) try: count = data.pop('count') except KeyError: if not data: # Empty dictionary is returned in case a query does not contain any results. # Can happen also if a listAPI is called with a page that does not exits. Therefore, final_data # has to be returned in order to return all results from preceding pages. return final_data else: # Only list API calls have a 'count' key inside the response, # return data as it is in other cases! return data else: # update final_data using paginated results, dictionaries of the response contain the count key # and one key pointing to the actual data values for key, value in data.items(): final_data.setdefault(key, []).extend(value) final_data['count'] = final_data.setdefault('count', 0) + count kwargs['page'] += 1 if count < self.max_page_size: # no more pages exists return final_data
[ "Async", "co", "-", "routine", "to", "perform", "requests", "to", "a", "CloudStackAPI", ".", "The", "parameters", "needs", "to", "include", "the", "command", "string", "which", "refers", "to", "the", "API", "to", "be", "called", ".", "In", "principle", "any", "available", "and", "future", "CloudStack", "API", "can", "be", "called", ".", "The", "**", "kwargs", "magic", "allows", "us", "to", "all", "add", "supported", "parameters", "to", "the", "given", "API", "call", ".", "A", "list", "of", "all", "available", "APIs", "can", "found", "at", "https", ":", "//", "cloudstack", ".", "apache", ".", "org", "/", "api", "/", "apidocs", "-", "4", ".", "8", "/", "TOC_User", ".", "html" ]
giffels/CloudStackAIO
python
https://github.com/giffels/CloudStackAIO/blob/f9df856622eb8966a6816f8008cc16d75b0067e5/CloudStackAIO/CloudStack.py#L112-L155
[ "async", "def", "request", "(", "self", ",", "command", ":", "str", ",", "*", "*", "kwargs", ")", "->", "dict", ":", "kwargs", ".", "update", "(", "dict", "(", "apikey", "=", "self", ".", "api_key", ",", "command", "=", "command", ",", "response", "=", "'json'", ")", ")", "if", "'list'", "in", "command", ".", "lower", "(", ")", ":", "# list APIs can be paginated, therefore include max_page_size and page parameter", "kwargs", ".", "update", "(", "dict", "(", "pagesize", "=", "self", ".", "max_page_size", ",", "page", "=", "1", ")", ")", "final_data", "=", "dict", "(", ")", "while", "True", ":", "async", "with", "self", ".", "client_session", ".", "get", "(", "self", ".", "end_point", ",", "params", "=", "self", ".", "_sign", "(", "kwargs", ")", ")", "as", "response", ":", "data", "=", "await", "self", ".", "_handle_response", "(", "response", "=", "response", ",", "await_final_result", "=", "'queryasyncjobresult'", "not", "in", "command", ".", "lower", "(", ")", ")", "try", ":", "count", "=", "data", ".", "pop", "(", "'count'", ")", "except", "KeyError", ":", "if", "not", "data", ":", "# Empty dictionary is returned in case a query does not contain any results.", "# Can happen also if a listAPI is called with a page that does not exits. Therefore, final_data", "# has to be returned in order to return all results from preceding pages.", "return", "final_data", "else", ":", "# Only list API calls have a 'count' key inside the response,", "# return data as it is in other cases!", "return", "data", "else", ":", "# update final_data using paginated results, dictionaries of the response contain the count key", "# and one key pointing to the actual data values", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "final_data", ".", "setdefault", "(", "key", ",", "[", "]", ")", ".", "extend", "(", "value", ")", "final_data", "[", "'count'", "]", "=", "final_data", ".", "setdefault", "(", "'count'", ",", "0", ")", "+", "count", "kwargs", "[", "'page'", "]", "+=", "1", "if", "count", "<", "self", ".", "max_page_size", ":", "# no more pages exists", "return", "final_data" ]
f9df856622eb8966a6816f8008cc16d75b0067e5
test
CloudStack._handle_response
Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which means that the API call returns just a job id. The actually expected API response is postponed and a specific asyncJobResults API has to be polled using the job id to get the final result once the API call has been processed. :param response: The response returned by the aiohttp call. :type response: aiohttp.client_reqrep.ClientResponse :param await_final_result: Specifier that indicates whether the function should poll the asyncJobResult API until the asynchronous API call has been processed :type await_final_result: bool :return: Dictionary containing the JSON response of the API call :rtype: dict
CloudStackAIO/CloudStack.py
async def _handle_response(self, response: aiohttp.client_reqrep.ClientResponse, await_final_result: bool) -> dict: """ Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which means that the API call returns just a job id. The actually expected API response is postponed and a specific asyncJobResults API has to be polled using the job id to get the final result once the API call has been processed. :param response: The response returned by the aiohttp call. :type response: aiohttp.client_reqrep.ClientResponse :param await_final_result: Specifier that indicates whether the function should poll the asyncJobResult API until the asynchronous API call has been processed :type await_final_result: bool :return: Dictionary containing the JSON response of the API call :rtype: dict """ try: data = await response.json() except aiohttp.client_exceptions.ContentTypeError: text = await response.text() logging.debug('Content returned by server not of type "application/json"\n Content: {}'.format(text)) raise CloudStackClientException(message="Could not decode content. Server did not return json content!") else: data = self._transform_data(data) if response.status != 200: raise CloudStackClientException(message="Async CloudStack call failed!", error_code=data.get("errorcode", response.status), error_text=data.get("errortext"), response=data) while await_final_result and ('jobid' in data): await asyncio.sleep(self.async_poll_latency) data = await self.queryAsyncJobResult(jobid=data['jobid']) if data['jobstatus']: # jobstatus is 0 for pending async CloudStack calls if not data['jobresultcode']: # exit code is zero try: return data['jobresult'] except KeyError: pass logging.debug("Async CloudStack call returned {}".format(str(data))) raise CloudStackClientException(message="Async CloudStack call failed!", error_code=data.get("errorcode"), error_text=data.get("errortext"), response=data) return data
async def _handle_response(self, response: aiohttp.client_reqrep.ClientResponse, await_final_result: bool) -> dict: """ Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which means that the API call returns just a job id. The actually expected API response is postponed and a specific asyncJobResults API has to be polled using the job id to get the final result once the API call has been processed. :param response: The response returned by the aiohttp call. :type response: aiohttp.client_reqrep.ClientResponse :param await_final_result: Specifier that indicates whether the function should poll the asyncJobResult API until the asynchronous API call has been processed :type await_final_result: bool :return: Dictionary containing the JSON response of the API call :rtype: dict """ try: data = await response.json() except aiohttp.client_exceptions.ContentTypeError: text = await response.text() logging.debug('Content returned by server not of type "application/json"\n Content: {}'.format(text)) raise CloudStackClientException(message="Could not decode content. Server did not return json content!") else: data = self._transform_data(data) if response.status != 200: raise CloudStackClientException(message="Async CloudStack call failed!", error_code=data.get("errorcode", response.status), error_text=data.get("errortext"), response=data) while await_final_result and ('jobid' in data): await asyncio.sleep(self.async_poll_latency) data = await self.queryAsyncJobResult(jobid=data['jobid']) if data['jobstatus']: # jobstatus is 0 for pending async CloudStack calls if not data['jobresultcode']: # exit code is zero try: return data['jobresult'] except KeyError: pass logging.debug("Async CloudStack call returned {}".format(str(data))) raise CloudStackClientException(message="Async CloudStack call failed!", error_code=data.get("errorcode"), error_text=data.get("errortext"), response=data) return data
[ "Handles", "the", "response", "returned", "from", "the", "CloudStack", "API", ".", "Some", "CloudStack", "API", "are", "implemented", "asynchronous", "which", "means", "that", "the", "API", "call", "returns", "just", "a", "job", "id", ".", "The", "actually", "expected", "API", "response", "is", "postponed", "and", "a", "specific", "asyncJobResults", "API", "has", "to", "be", "polled", "using", "the", "job", "id", "to", "get", "the", "final", "result", "once", "the", "API", "call", "has", "been", "processed", "." ]
giffels/CloudStackAIO
python
https://github.com/giffels/CloudStackAIO/blob/f9df856622eb8966a6816f8008cc16d75b0067e5/CloudStackAIO/CloudStack.py#L157-L201
[ "async", "def", "_handle_response", "(", "self", ",", "response", ":", "aiohttp", ".", "client_reqrep", ".", "ClientResponse", ",", "await_final_result", ":", "bool", ")", "->", "dict", ":", "try", ":", "data", "=", "await", "response", ".", "json", "(", ")", "except", "aiohttp", ".", "client_exceptions", ".", "ContentTypeError", ":", "text", "=", "await", "response", ".", "text", "(", ")", "logging", ".", "debug", "(", "'Content returned by server not of type \"application/json\"\\n Content: {}'", ".", "format", "(", "text", ")", ")", "raise", "CloudStackClientException", "(", "message", "=", "\"Could not decode content. Server did not return json content!\"", ")", "else", ":", "data", "=", "self", ".", "_transform_data", "(", "data", ")", "if", "response", ".", "status", "!=", "200", ":", "raise", "CloudStackClientException", "(", "message", "=", "\"Async CloudStack call failed!\"", ",", "error_code", "=", "data", ".", "get", "(", "\"errorcode\"", ",", "response", ".", "status", ")", ",", "error_text", "=", "data", ".", "get", "(", "\"errortext\"", ")", ",", "response", "=", "data", ")", "while", "await_final_result", "and", "(", "'jobid'", "in", "data", ")", ":", "await", "asyncio", ".", "sleep", "(", "self", ".", "async_poll_latency", ")", "data", "=", "await", "self", ".", "queryAsyncJobResult", "(", "jobid", "=", "data", "[", "'jobid'", "]", ")", "if", "data", "[", "'jobstatus'", "]", ":", "# jobstatus is 0 for pending async CloudStack calls", "if", "not", "data", "[", "'jobresultcode'", "]", ":", "# exit code is zero", "try", ":", "return", "data", "[", "'jobresult'", "]", "except", "KeyError", ":", "pass", "logging", ".", "debug", "(", "\"Async CloudStack call returned {}\"", ".", "format", "(", "str", "(", "data", ")", ")", ")", "raise", "CloudStackClientException", "(", "message", "=", "\"Async CloudStack call failed!\"", ",", "error_code", "=", "data", ".", "get", "(", "\"errorcode\"", ")", ",", "error_text", "=", "data", ".", "get", "(", "\"errortext\"", ")", ",", "response", "=", "data", ")", "return", "data" ]
f9df856622eb8966a6816f8008cc16d75b0067e5
test
CloudStack._sign
According to the CloudStack documentation, each request needs to be signed in order to authenticate the user account executing the API command. The signature is generated using a combination of the api secret and a SHA-1 hash of the url parameters including the command string. In order to generate a unique identifier, the url parameters have to be transformed to lower case and ordered alphabetically. :param url_parameters: The url parameters of the API call including the command string :type url_parameters: dict :return: The url parameters including a new key, which contains the signature :rtype: dict
CloudStackAIO/CloudStack.py
def _sign(self, url_parameters: dict) -> dict: """ According to the CloudStack documentation, each request needs to be signed in order to authenticate the user account executing the API command. The signature is generated using a combination of the api secret and a SHA-1 hash of the url parameters including the command string. In order to generate a unique identifier, the url parameters have to be transformed to lower case and ordered alphabetically. :param url_parameters: The url parameters of the API call including the command string :type url_parameters: dict :return: The url parameters including a new key, which contains the signature :rtype: dict """ if url_parameters: url_parameters.pop('signature', None) # remove potential existing signature from url parameters request_string = urlencode(sorted(url_parameters.items()), safe='.-*_', quote_via=quote).lower() digest = hmac.new(self.api_secret.encode('utf-8'), request_string.encode('utf-8'), hashlib.sha1).digest() url_parameters['signature'] = base64.b64encode(digest).decode('utf-8').strip() return url_parameters
def _sign(self, url_parameters: dict) -> dict: """ According to the CloudStack documentation, each request needs to be signed in order to authenticate the user account executing the API command. The signature is generated using a combination of the api secret and a SHA-1 hash of the url parameters including the command string. In order to generate a unique identifier, the url parameters have to be transformed to lower case and ordered alphabetically. :param url_parameters: The url parameters of the API call including the command string :type url_parameters: dict :return: The url parameters including a new key, which contains the signature :rtype: dict """ if url_parameters: url_parameters.pop('signature', None) # remove potential existing signature from url parameters request_string = urlencode(sorted(url_parameters.items()), safe='.-*_', quote_via=quote).lower() digest = hmac.new(self.api_secret.encode('utf-8'), request_string.encode('utf-8'), hashlib.sha1).digest() url_parameters['signature'] = base64.b64encode(digest).decode('utf-8').strip() return url_parameters
[ "According", "to", "the", "CloudStack", "documentation", "each", "request", "needs", "to", "be", "signed", "in", "order", "to", "authenticate", "the", "user", "account", "executing", "the", "API", "command", ".", "The", "signature", "is", "generated", "using", "a", "combination", "of", "the", "api", "secret", "and", "a", "SHA", "-", "1", "hash", "of", "the", "url", "parameters", "including", "the", "command", "string", ".", "In", "order", "to", "generate", "a", "unique", "identifier", "the", "url", "parameters", "have", "to", "be", "transformed", "to", "lower", "case", "and", "ordered", "alphabetically", "." ]
giffels/CloudStackAIO
python
https://github.com/giffels/CloudStackAIO/blob/f9df856622eb8966a6816f8008cc16d75b0067e5/CloudStackAIO/CloudStack.py#L203-L220
[ "def", "_sign", "(", "self", ",", "url_parameters", ":", "dict", ")", "->", "dict", ":", "if", "url_parameters", ":", "url_parameters", ".", "pop", "(", "'signature'", ",", "None", ")", "# remove potential existing signature from url parameters", "request_string", "=", "urlencode", "(", "sorted", "(", "url_parameters", ".", "items", "(", ")", ")", ",", "safe", "=", "'.-*_'", ",", "quote_via", "=", "quote", ")", ".", "lower", "(", ")", "digest", "=", "hmac", ".", "new", "(", "self", ".", "api_secret", ".", "encode", "(", "'utf-8'", ")", ",", "request_string", ".", "encode", "(", "'utf-8'", ")", ",", "hashlib", ".", "sha1", ")", ".", "digest", "(", ")", "url_parameters", "[", "'signature'", "]", "=", "base64", ".", "b64encode", "(", "digest", ")", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "return", "url_parameters" ]
f9df856622eb8966a6816f8008cc16d75b0067e5
test
CloudStack._transform_data
Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating the API that originated the response. This function removes that first level from the data returned to the caller. :param data: Response of the API call :type data: dict :return: Simplified response without the information about the API that originated the response. :rtype: dict
CloudStackAIO/CloudStack.py
def _transform_data(data: dict) -> dict: """ Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating the API that originated the response. This function removes that first level from the data returned to the caller. :param data: Response of the API call :type data: dict :return: Simplified response without the information about the API that originated the response. :rtype: dict """ for key in data.keys(): return_value = data[key] if isinstance(return_value, dict): return return_value return data
def _transform_data(data: dict) -> dict: """ Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating the API that originated the response. This function removes that first level from the data returned to the caller. :param data: Response of the API call :type data: dict :return: Simplified response without the information about the API that originated the response. :rtype: dict """ for key in data.keys(): return_value = data[key] if isinstance(return_value, dict): return return_value return data
[ "Each", "CloudStack", "API", "call", "returns", "a", "nested", "dictionary", "structure", ".", "The", "first", "level", "contains", "only", "one", "key", "indicating", "the", "API", "that", "originated", "the", "response", ".", "This", "function", "removes", "that", "first", "level", "from", "the", "data", "returned", "to", "the", "caller", "." ]
giffels/CloudStackAIO
python
https://github.com/giffels/CloudStackAIO/blob/f9df856622eb8966a6816f8008cc16d75b0067e5/CloudStackAIO/CloudStack.py#L223-L238
[ "def", "_transform_data", "(", "data", ":", "dict", ")", "->", "dict", ":", "for", "key", "in", "data", ".", "keys", "(", ")", ":", "return_value", "=", "data", "[", "key", "]", "if", "isinstance", "(", "return_value", ",", "dict", ")", ":", "return", "return_value", "return", "data" ]
f9df856622eb8966a6816f8008cc16d75b0067e5
test
virtual_memory
System virtual memory as a namedutple.
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def virtual_memory(): """System virtual memory as a namedutple.""" mem = _psutil_bsd.get_virtual_mem() total, free, active, inactive, wired, cached, buffers, shared = mem avail = inactive + cached + free used = active + wired + cached percent = usage_percent((total - avail), total, _round=1) return nt_virtmem_info(total, avail, percent, used, free, active, inactive, buffers, cached, shared, wired)
def virtual_memory(): """System virtual memory as a namedutple.""" mem = _psutil_bsd.get_virtual_mem() total, free, active, inactive, wired, cached, buffers, shared = mem avail = inactive + cached + free used = active + wired + cached percent = usage_percent((total - avail), total, _round=1) return nt_virtmem_info(total, avail, percent, used, free, active, inactive, buffers, cached, shared, wired)
[ "System", "virtual", "memory", "as", "a", "namedutple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L46-L54
[ "def", "virtual_memory", "(", ")", ":", "mem", "=", "_psutil_bsd", ".", "get_virtual_mem", "(", ")", "total", ",", "free", ",", "active", ",", "inactive", ",", "wired", ",", "cached", ",", "buffers", ",", "shared", "=", "mem", "avail", "=", "inactive", "+", "cached", "+", "free", "used", "=", "active", "+", "wired", "+", "cached", "percent", "=", "usage_percent", "(", "(", "total", "-", "avail", ")", ",", "total", ",", "_round", "=", "1", ")", "return", "nt_virtmem_info", "(", "total", ",", "avail", ",", "percent", ",", "used", ",", "free", ",", "active", ",", "inactive", ",", "buffers", ",", "cached", ",", "shared", ",", "wired", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
swap_memory
System swap memory as (total, used, free, sin, sout) namedtuple.
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def swap_memory(): """System swap memory as (total, used, free, sin, sout) namedtuple.""" total, used, free, sin, sout = \ [x * _PAGESIZE for x in _psutil_bsd.get_swap_mem()] percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, sin, sout)
def swap_memory(): """System swap memory as (total, used, free, sin, sout) namedtuple.""" total, used, free, sin, sout = \ [x * _PAGESIZE for x in _psutil_bsd.get_swap_mem()] percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, sin, sout)
[ "System", "swap", "memory", "as", "(", "total", "used", "free", "sin", "sout", ")", "namedtuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L56-L61
[ "def", "swap_memory", "(", ")", ":", "total", ",", "used", ",", "free", ",", "sin", ",", "sout", "=", "[", "x", "*", "_PAGESIZE", "for", "x", "in", "_psutil_bsd", ".", "get_swap_mem", "(", ")", "]", "percent", "=", "usage_percent", "(", "used", ",", "total", ",", "_round", "=", "1", ")", "return", "nt_swapmeminfo", "(", "total", ",", "used", ",", "free", ",", "percent", ",", "sin", ",", "sout", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_system_cpu_times
Return system per-CPU times as a named tuple
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def get_system_cpu_times(): """Return system per-CPU times as a named tuple""" user, nice, system, idle, irq = _psutil_bsd.get_system_cpu_times() return _cputimes_ntuple(user, nice, system, idle, irq)
def get_system_cpu_times(): """Return system per-CPU times as a named tuple""" user, nice, system, idle, irq = _psutil_bsd.get_system_cpu_times() return _cputimes_ntuple(user, nice, system, idle, irq)
[ "Return", "system", "per", "-", "CPU", "times", "as", "a", "named", "tuple" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L63-L66
[ "def", "get_system_cpu_times", "(", ")", ":", "user", ",", "nice", ",", "system", ",", "idle", ",", "irq", "=", "_psutil_bsd", ".", "get_system_cpu_times", "(", ")", "return", "_cputimes_ntuple", "(", "user", ",", "nice", ",", "system", ",", "idle", ",", "irq", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_system_per_cpu_times
Return system CPU times as a named tuple
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def get_system_per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in _psutil_bsd.get_system_per_cpu_times(): user, nice, system, idle, irq = cpu_t item = _cputimes_ntuple(user, nice, system, idle, irq) ret.append(item) return ret
def get_system_per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in _psutil_bsd.get_system_per_cpu_times(): user, nice, system, idle, irq = cpu_t item = _cputimes_ntuple(user, nice, system, idle, irq) ret.append(item) return ret
[ "Return", "system", "CPU", "times", "as", "a", "named", "tuple" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L68-L75
[ "def", "get_system_per_cpu_times", "(", ")", ":", "ret", "=", "[", "]", "for", "cpu_t", "in", "_psutil_bsd", ".", "get_system_per_cpu_times", "(", ")", ":", "user", ",", "nice", ",", "system", ",", "idle", ",", "irq", "=", "cpu_t", "item", "=", "_cputimes_ntuple", "(", "user", ",", "nice", ",", "system", ",", "idle", ",", "irq", ")", "ret", ".", "append", "(", "item", ")", "return", "ret" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_process_uids
Return real, effective and saved user ids.
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def get_process_uids(self): """Return real, effective and saved user ids.""" real, effective, saved = _psutil_bsd.get_process_uids(self.pid) return nt_uids(real, effective, saved)
def get_process_uids(self): """Return real, effective and saved user ids.""" real, effective, saved = _psutil_bsd.get_process_uids(self.pid) return nt_uids(real, effective, saved)
[ "Return", "real", "effective", "and", "saved", "user", "ids", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L202-L205
[ "def", "get_process_uids", "(", "self", ")", ":", "real", ",", "effective", ",", "saved", "=", "_psutil_bsd", ".", "get_process_uids", "(", "self", ".", "pid", ")", "return", "nt_uids", "(", "real", ",", "effective", ",", "saved", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_process_gids
Return real, effective and saved group ids.
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def get_process_gids(self): """Return real, effective and saved group ids.""" real, effective, saved = _psutil_bsd.get_process_gids(self.pid) return nt_gids(real, effective, saved)
def get_process_gids(self): """Return real, effective and saved group ids.""" real, effective, saved = _psutil_bsd.get_process_gids(self.pid) return nt_gids(real, effective, saved)
[ "Return", "real", "effective", "and", "saved", "group", "ids", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L208-L211
[ "def", "get_process_gids", "(", "self", ")", ":", "real", ",", "effective", ",", "saved", "=", "_psutil_bsd", ".", "get_process_gids", "(", "self", ".", "pid", ")", "return", "nt_gids", "(", "real", ",", "effective", ",", "saved", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_cpu_times
return a tuple containing process user/kernel time.
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def get_cpu_times(self): """return a tuple containing process user/kernel time.""" user, system = _psutil_bsd.get_process_cpu_times(self.pid) return nt_cputimes(user, system)
def get_cpu_times(self): """return a tuple containing process user/kernel time.""" user, system = _psutil_bsd.get_process_cpu_times(self.pid) return nt_cputimes(user, system)
[ "return", "a", "tuple", "containing", "process", "user", "/", "kernel", "time", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L214-L217
[ "def", "get_cpu_times", "(", "self", ")", ":", "user", ",", "system", "=", "_psutil_bsd", ".", "get_process_cpu_times", "(", "self", ".", "pid", ")", "return", "nt_cputimes", "(", "user", ",", "system", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_memory_info
Return a tuple with the process' RSS and VMS size.
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def get_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms = _psutil_bsd.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
def get_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms = _psutil_bsd.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
[ "Return", "a", "tuple", "with", "the", "process", "RSS", "and", "VMS", "size", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L220-L223
[ "def", "get_memory_info", "(", "self", ")", ":", "rss", ",", "vms", "=", "_psutil_bsd", ".", "get_process_memory_info", "(", "self", ".", "pid", ")", "[", ":", "2", "]", "return", "nt_meminfo", "(", "rss", ",", "vms", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_process_threads
Return the number of threads belonging to the process.
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def get_process_threads(self): """Return the number of threads belonging to the process.""" rawlist = _psutil_bsd.get_process_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = nt_thread(thread_id, utime, stime) retlist.append(ntuple) return retlist
def get_process_threads(self): """Return the number of threads belonging to the process.""" rawlist = _psutil_bsd.get_process_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = nt_thread(thread_id, utime, stime) retlist.append(ntuple) return retlist
[ "Return", "the", "number", "of", "threads", "belonging", "to", "the", "process", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L252-L259
[ "def", "get_process_threads", "(", "self", ")", ":", "rawlist", "=", "_psutil_bsd", ".", "get_process_threads", "(", "self", ".", "pid", ")", "retlist", "=", "[", "]", "for", "thread_id", ",", "utime", ",", "stime", "in", "rawlist", ":", "ntuple", "=", "nt_thread", "(", "thread_id", ",", "utime", ",", "stime", ")", "retlist", ".", "append", "(", "ntuple", ")", "return", "retlist" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_open_files
Return files opened by process as a list of namedtuples.
environment/lib/python2.7/site-packages/psutil/_psbsd.py
def get_open_files(self): """Return files opened by process as a list of namedtuples.""" # XXX - C implementation available on FreeBSD >= 8 only # else fallback on lsof parser if hasattr(_psutil_bsd, "get_process_open_files"): rawlist = _psutil_bsd.get_process_open_files(self.pid) return [nt_openfile(path, fd) for path, fd in rawlist] else: lsof = _psposix.LsofParser(self.pid, self._process_name) return lsof.get_process_open_files()
def get_open_files(self): """Return files opened by process as a list of namedtuples.""" # XXX - C implementation available on FreeBSD >= 8 only # else fallback on lsof parser if hasattr(_psutil_bsd, "get_process_open_files"): rawlist = _psutil_bsd.get_process_open_files(self.pid) return [nt_openfile(path, fd) for path, fd in rawlist] else: lsof = _psposix.LsofParser(self.pid, self._process_name) return lsof.get_process_open_files()
[ "Return", "files", "opened", "by", "process", "as", "a", "list", "of", "namedtuples", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psbsd.py#L262-L271
[ "def", "get_open_files", "(", "self", ")", ":", "# XXX - C implementation available on FreeBSD >= 8 only", "# else fallback on lsof parser", "if", "hasattr", "(", "_psutil_bsd", ",", "\"get_process_open_files\"", ")", ":", "rawlist", "=", "_psutil_bsd", ".", "get_process_open_files", "(", "self", ".", "pid", ")", "return", "[", "nt_openfile", "(", "path", ",", "fd", ")", "for", "path", ",", "fd", "in", "rawlist", "]", "else", ":", "lsof", "=", "_psposix", ".", "LsofParser", "(", "self", ".", "pid", ",", "self", ".", "_process_name", ")", "return", "lsof", ".", "get_process_open_files", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_connection_file
Return the path to the connection file of an app Parameters ---------- app : KernelApp instance [optional] If unspecified, the currently running app will be used
environment/lib/python2.7/site-packages/IPython/lib/kernel.py
def get_connection_file(app=None): """Return the path to the connection file of an app Parameters ---------- app : KernelApp instance [optional] If unspecified, the currently running app will be used """ if app is None: from IPython.zmq.ipkernel import IPKernelApp if not IPKernelApp.initialized(): raise RuntimeError("app not specified, and not in a running Kernel") app = IPKernelApp.instance() return filefind(app.connection_file, ['.', app.profile_dir.security_dir])
def get_connection_file(app=None): """Return the path to the connection file of an app Parameters ---------- app : KernelApp instance [optional] If unspecified, the currently running app will be used """ if app is None: from IPython.zmq.ipkernel import IPKernelApp if not IPKernelApp.initialized(): raise RuntimeError("app not specified, and not in a running Kernel") app = IPKernelApp.instance() return filefind(app.connection_file, ['.', app.profile_dir.security_dir])
[ "Return", "the", "path", "to", "the", "connection", "file", "of", "an", "app", "Parameters", "----------", "app", ":", "KernelApp", "instance", "[", "optional", "]", "If", "unspecified", "the", "currently", "running", "app", "will", "be", "used" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/kernel.py#L40-L54
[ "def", "get_connection_file", "(", "app", "=", "None", ")", ":", "if", "app", "is", "None", ":", "from", "IPython", ".", "zmq", ".", "ipkernel", "import", "IPKernelApp", "if", "not", "IPKernelApp", ".", "initialized", "(", ")", ":", "raise", "RuntimeError", "(", "\"app not specified, and not in a running Kernel\"", ")", "app", "=", "IPKernelApp", ".", "instance", "(", ")", "return", "filefind", "(", "app", ".", "connection_file", ",", "[", "'.'", ",", "app", ".", "profile_dir", ".", "security_dir", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
find_connection_file
find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file.
environment/lib/python2.7/site-packages/IPython/lib/kernel.py
def find_connection_file(filename, profile=None): """find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) security_dir = profile_dir.security_dir try: # first, try explicit name return filefind(filename, ['.', security_dir]) except IOError: pass # not found by full name if '*' in filename: # given as a glob already pat = filename else: # accept any substring match pat = '*%s*' % filename matches = glob.glob( os.path.join(security_dir, pat) ) if not matches: raise IOError("Could not find %r in %r" % (filename, security_dir)) elif len(matches) == 1: return matches[0] else: # get most recent match, by access time: return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]
def find_connection_file(filename, profile=None): """find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) security_dir = profile_dir.security_dir try: # first, try explicit name return filefind(filename, ['.', security_dir]) except IOError: pass # not found by full name if '*' in filename: # given as a glob already pat = filename else: # accept any substring match pat = '*%s*' % filename matches = glob.glob( os.path.join(security_dir, pat) ) if not matches: raise IOError("Could not find %r in %r" % (filename, security_dir)) elif len(matches) == 1: return matches[0] else: # get most recent match, by access time: return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]
[ "find", "a", "connection", "file", "and", "return", "its", "absolute", "path", ".", "The", "current", "working", "directory", "and", "the", "profile", "s", "security", "directory", "will", "be", "searched", "for", "the", "file", "if", "it", "is", "not", "given", "by", "absolute", "path", ".", "If", "profile", "is", "unspecified", "then", "the", "current", "running", "application", "s", "profile", "will", "be", "used", "or", "default", "if", "not", "run", "from", "IPython", ".", "If", "the", "argument", "does", "not", "match", "an", "existing", "file", "it", "will", "be", "interpreted", "as", "a", "fileglob", "and", "the", "matching", "file", "in", "the", "profile", "s", "security", "dir", "with", "the", "latest", "access", "time", "will", "be", "used", ".", "Parameters", "----------", "filename", ":", "str", "The", "connection", "file", "or", "fileglob", "to", "search", "for", ".", "profile", ":", "str", "[", "optional", "]", "The", "name", "of", "the", "profile", "to", "use", "when", "searching", "for", "the", "connection", "file", "if", "different", "from", "the", "current", "IPython", "session", "or", "default", ".", "Returns", "-------", "str", ":", "The", "absolute", "path", "of", "the", "connection", "file", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/kernel.py#L56-L123
[ "def", "find_connection_file", "(", "filename", ",", "profile", "=", "None", ")", ":", "from", "IPython", ".", "core", ".", "application", "import", "BaseIPythonApplication", "as", "IPApp", "try", ":", "# quick check for absolute path, before going through logic", "return", "filefind", "(", "filename", ")", "except", "IOError", ":", "pass", "if", "profile", "is", "None", ":", "# profile unspecified, check if running from an IPython app", "if", "IPApp", ".", "initialized", "(", ")", ":", "app", "=", "IPApp", ".", "instance", "(", ")", "profile_dir", "=", "app", ".", "profile_dir", "else", ":", "# not running in IPython, use default profile", "profile_dir", "=", "ProfileDir", ".", "find_profile_dir_by_name", "(", "get_ipython_dir", "(", ")", ",", "'default'", ")", "else", ":", "# find profiledir by profile name:", "profile_dir", "=", "ProfileDir", ".", "find_profile_dir_by_name", "(", "get_ipython_dir", "(", ")", ",", "profile", ")", "security_dir", "=", "profile_dir", ".", "security_dir", "try", ":", "# first, try explicit name", "return", "filefind", "(", "filename", ",", "[", "'.'", ",", "security_dir", "]", ")", "except", "IOError", ":", "pass", "# not found by full name", "if", "'*'", "in", "filename", ":", "# given as a glob already", "pat", "=", "filename", "else", ":", "# accept any substring match", "pat", "=", "'*%s*'", "%", "filename", "matches", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "security_dir", ",", "pat", ")", ")", "if", "not", "matches", ":", "raise", "IOError", "(", "\"Could not find %r in %r\"", "%", "(", "filename", ",", "security_dir", ")", ")", "elif", "len", "(", "matches", ")", "==", "1", ":", "return", "matches", "[", "0", "]", "else", ":", "# get most recent match, by access time:", "return", "sorted", "(", "matches", ",", "key", "=", "lambda", "f", ":", "os", ".", "stat", "(", "f", ")", ".", "st_atime", ")", "[", "-", "1", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_connection_info
Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. unpack : bool [default: False] if True, return the unpacked dict, otherwise just the string contents of the file. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- The connection dictionary of the current kernel, as string or dict, depending on `unpack`.
environment/lib/python2.7/site-packages/IPython/lib/kernel.py
def get_connection_info(connection_file=None, unpack=False, profile=None): """Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. unpack : bool [default: False] if True, return the unpacked dict, otherwise just the string contents of the file. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- The connection dictionary of the current kernel, as string or dict, depending on `unpack`. """ if connection_file is None: # get connection file from current kernel cf = get_connection_file() else: # connection file specified, allow shortnames: cf = find_connection_file(connection_file, profile=profile) with open(cf) as f: info = f.read() if unpack: info = json.loads(info) # ensure key is bytes: info['key'] = str_to_bytes(info.get('key', '')) return info
def get_connection_info(connection_file=None, unpack=False, profile=None): """Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. unpack : bool [default: False] if True, return the unpacked dict, otherwise just the string contents of the file. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- The connection dictionary of the current kernel, as string or dict, depending on `unpack`. """ if connection_file is None: # get connection file from current kernel cf = get_connection_file() else: # connection file specified, allow shortnames: cf = find_connection_file(connection_file, profile=profile) with open(cf) as f: info = f.read() if unpack: info = json.loads(info) # ensure key is bytes: info['key'] = str_to_bytes(info.get('key', '')) return info
[ "Return", "the", "connection", "information", "for", "the", "current", "Kernel", ".", "Parameters", "----------", "connection_file", ":", "str", "[", "optional", "]", "The", "connection", "file", "to", "be", "used", ".", "Can", "be", "given", "by", "absolute", "path", "or", "IPython", "will", "search", "in", "the", "security", "directory", "of", "a", "given", "profile", ".", "If", "run", "from", "IPython", "If", "unspecified", "the", "connection", "file", "for", "the", "currently", "running", "IPython", "Kernel", "will", "be", "used", "which", "is", "only", "allowed", "from", "inside", "a", "kernel", ".", "unpack", ":", "bool", "[", "default", ":", "False", "]", "if", "True", "return", "the", "unpacked", "dict", "otherwise", "just", "the", "string", "contents", "of", "the", "file", ".", "profile", ":", "str", "[", "optional", "]", "The", "name", "of", "the", "profile", "to", "use", "when", "searching", "for", "the", "connection", "file", "if", "different", "from", "the", "current", "IPython", "session", "or", "default", ".", "Returns", "-------", "The", "connection", "dictionary", "of", "the", "current", "kernel", "as", "string", "or", "dict", "depending", "on", "unpack", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/kernel.py#L125-L164
[ "def", "get_connection_info", "(", "connection_file", "=", "None", ",", "unpack", "=", "False", ",", "profile", "=", "None", ")", ":", "if", "connection_file", "is", "None", ":", "# get connection file from current kernel", "cf", "=", "get_connection_file", "(", ")", "else", ":", "# connection file specified, allow shortnames:", "cf", "=", "find_connection_file", "(", "connection_file", ",", "profile", "=", "profile", ")", "with", "open", "(", "cf", ")", "as", "f", ":", "info", "=", "f", ".", "read", "(", ")", "if", "unpack", ":", "info", "=", "json", ".", "loads", "(", "info", ")", "# ensure key is bytes:", "info", "[", "'key'", "]", "=", "str_to_bytes", "(", "info", ".", "get", "(", "'key'", ",", "''", ")", ")", "return", "info" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
connect_qtconsole
Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. argv : list [optional] Any extra args to be passed to the console. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- subprocess.Popen instance running the qtconsole frontend
environment/lib/python2.7/site-packages/IPython/lib/kernel.py
def connect_qtconsole(connection_file=None, argv=None, profile=None): """Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. argv : list [optional] Any extra args to be passed to the console. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- subprocess.Popen instance running the qtconsole frontend """ argv = [] if argv is None else argv if connection_file is None: # get connection file from current kernel cf = get_connection_file() else: cf = find_connection_file(connection_file, profile=profile) cmd = ';'.join([ "from IPython.frontend.qt.console import qtconsoleapp", "qtconsoleapp.main()" ]) return Popen([sys.executable, '-c', cmd, '--existing', cf] + argv, stdout=PIPE, stderr=PIPE)
def connect_qtconsole(connection_file=None, argv=None, profile=None): """Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. argv : list [optional] Any extra args to be passed to the console. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- subprocess.Popen instance running the qtconsole frontend """ argv = [] if argv is None else argv if connection_file is None: # get connection file from current kernel cf = get_connection_file() else: cf = find_connection_file(connection_file, profile=profile) cmd = ';'.join([ "from IPython.frontend.qt.console import qtconsoleapp", "qtconsoleapp.main()" ]) return Popen([sys.executable, '-c', cmd, '--existing', cf] + argv, stdout=PIPE, stderr=PIPE)
[ "Connect", "a", "qtconsole", "to", "the", "current", "kernel", ".", "This", "is", "useful", "for", "connecting", "a", "second", "qtconsole", "to", "a", "kernel", "or", "to", "a", "local", "notebook", ".", "Parameters", "----------", "connection_file", ":", "str", "[", "optional", "]", "The", "connection", "file", "to", "be", "used", ".", "Can", "be", "given", "by", "absolute", "path", "or", "IPython", "will", "search", "in", "the", "security", "directory", "of", "a", "given", "profile", ".", "If", "run", "from", "IPython", "If", "unspecified", "the", "connection", "file", "for", "the", "currently", "running", "IPython", "Kernel", "will", "be", "used", "which", "is", "only", "allowed", "from", "inside", "a", "kernel", ".", "argv", ":", "list", "[", "optional", "]", "Any", "extra", "args", "to", "be", "passed", "to", "the", "console", ".", "profile", ":", "str", "[", "optional", "]", "The", "name", "of", "the", "profile", "to", "use", "when", "searching", "for", "the", "connection", "file", "if", "different", "from", "the", "current", "IPython", "session", "or", "default", ".", "Returns", "-------", "subprocess", ".", "Popen", "instance", "running", "the", "qtconsole", "frontend" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/kernel.py#L166-L205
[ "def", "connect_qtconsole", "(", "connection_file", "=", "None", ",", "argv", "=", "None", ",", "profile", "=", "None", ")", ":", "argv", "=", "[", "]", "if", "argv", "is", "None", "else", "argv", "if", "connection_file", "is", "None", ":", "# get connection file from current kernel", "cf", "=", "get_connection_file", "(", ")", "else", ":", "cf", "=", "find_connection_file", "(", "connection_file", ",", "profile", "=", "profile", ")", "cmd", "=", "';'", ".", "join", "(", "[", "\"from IPython.frontend.qt.console import qtconsoleapp\"", ",", "\"qtconsoleapp.main()\"", "]", ")", "return", "Popen", "(", "[", "sys", ".", "executable", ",", "'-c'", ",", "cmd", ",", "'--existing'", ",", "cf", "]", "+", "argv", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
tunnel_to_kernel
tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Parameters ---------- connection_info : dict or str (path) Either a connection dict, or the path to a JSON connection file sshserver : str The ssh sever to use to tunnel to the kernel. Can be a full `user@server:port` string. ssh config aliases are respected. sshkey : str [optional] Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host. Returns ------- (shell, iopub, stdin, hb) : ints The four ports on localhost that have been forwarded to the kernel.
environment/lib/python2.7/site-packages/IPython/lib/kernel.py
def tunnel_to_kernel(connection_info, sshserver, sshkey=None): """tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Parameters ---------- connection_info : dict or str (path) Either a connection dict, or the path to a JSON connection file sshserver : str The ssh sever to use to tunnel to the kernel. Can be a full `user@server:port` string. ssh config aliases are respected. sshkey : str [optional] Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host. Returns ------- (shell, iopub, stdin, hb) : ints The four ports on localhost that have been forwarded to the kernel. """ if isinstance(connection_info, basestring): # it's a path, unpack it with open(connection_info) as f: connection_info = json.loads(f.read()) cf = connection_info lports = tunnel.select_random_ports(4) rports = cf['shell_port'], cf['iopub_port'], cf['stdin_port'], cf['hb_port'] remote_ip = cf['ip'] if tunnel.try_passwordless_ssh(sshserver, sshkey): password=False else: password = getpass("SSH Password for %s: "%sshserver) for lp,rp in zip(lports, rports): tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password) return tuple(lports)
def tunnel_to_kernel(connection_info, sshserver, sshkey=None): """tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Parameters ---------- connection_info : dict or str (path) Either a connection dict, or the path to a JSON connection file sshserver : str The ssh sever to use to tunnel to the kernel. Can be a full `user@server:port` string. ssh config aliases are respected. sshkey : str [optional] Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host. Returns ------- (shell, iopub, stdin, hb) : ints The four ports on localhost that have been forwarded to the kernel. """ if isinstance(connection_info, basestring): # it's a path, unpack it with open(connection_info) as f: connection_info = json.loads(f.read()) cf = connection_info lports = tunnel.select_random_ports(4) rports = cf['shell_port'], cf['iopub_port'], cf['stdin_port'], cf['hb_port'] remote_ip = cf['ip'] if tunnel.try_passwordless_ssh(sshserver, sshkey): password=False else: password = getpass("SSH Password for %s: "%sshserver) for lp,rp in zip(lports, rports): tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password) return tuple(lports)
[ "tunnel", "connections", "to", "a", "kernel", "via", "ssh", "This", "will", "open", "four", "SSH", "tunnels", "from", "localhost", "on", "this", "machine", "to", "the", "ports", "associated", "with", "the", "kernel", ".", "They", "can", "be", "either", "direct", "localhost", "-", "localhost", "tunnels", "or", "if", "an", "intermediate", "server", "is", "necessary", "the", "kernel", "must", "be", "listening", "on", "a", "public", "IP", ".", "Parameters", "----------", "connection_info", ":", "dict", "or", "str", "(", "path", ")", "Either", "a", "connection", "dict", "or", "the", "path", "to", "a", "JSON", "connection", "file", "sshserver", ":", "str", "The", "ssh", "sever", "to", "use", "to", "tunnel", "to", "the", "kernel", ".", "Can", "be", "a", "full", "user" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/kernel.py#L207-L253
[ "def", "tunnel_to_kernel", "(", "connection_info", ",", "sshserver", ",", "sshkey", "=", "None", ")", ":", "if", "isinstance", "(", "connection_info", ",", "basestring", ")", ":", "# it's a path, unpack it", "with", "open", "(", "connection_info", ")", "as", "f", ":", "connection_info", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "cf", "=", "connection_info", "lports", "=", "tunnel", ".", "select_random_ports", "(", "4", ")", "rports", "=", "cf", "[", "'shell_port'", "]", ",", "cf", "[", "'iopub_port'", "]", ",", "cf", "[", "'stdin_port'", "]", ",", "cf", "[", "'hb_port'", "]", "remote_ip", "=", "cf", "[", "'ip'", "]", "if", "tunnel", ".", "try_passwordless_ssh", "(", "sshserver", ",", "sshkey", ")", ":", "password", "=", "False", "else", ":", "password", "=", "getpass", "(", "\"SSH Password for %s: \"", "%", "sshserver", ")", "for", "lp", ",", "rp", "in", "zip", "(", "lports", ",", "rports", ")", ":", "tunnel", ".", "ssh_tunnel", "(", "lp", ",", "rp", ",", "sshserver", ",", "remote_ip", ",", "sshkey", ",", "password", ")", "return", "tuple", "(", "lports", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
swallow_argv
strip frontend-specific aliases and flags from an argument list For use primarily in frontend apps that want to pass a subset of command-line arguments through to a subprocess, where frontend-specific flags and aliases should be removed from the list. Parameters ---------- argv : list(str) The starting argv, to be filtered aliases : container of aliases (dict, list, set, etc.) The frontend-specific aliases to be removed flags : container of flags (dict, list, set, etc.) The frontend-specific flags to be removed Returns ------- argv : list(str) The argv list, excluding flags and aliases that have been stripped
environment/lib/python2.7/site-packages/IPython/lib/kernel.py
def swallow_argv(argv, aliases=None, flags=None): """strip frontend-specific aliases and flags from an argument list For use primarily in frontend apps that want to pass a subset of command-line arguments through to a subprocess, where frontend-specific flags and aliases should be removed from the list. Parameters ---------- argv : list(str) The starting argv, to be filtered aliases : container of aliases (dict, list, set, etc.) The frontend-specific aliases to be removed flags : container of flags (dict, list, set, etc.) The frontend-specific flags to be removed Returns ------- argv : list(str) The argv list, excluding flags and aliases that have been stripped """ if aliases is None: aliases = set() if flags is None: flags = set() stripped = list(argv) # copy swallow_next = False was_flag = False for a in argv: if swallow_next: swallow_next = False # last arg was an alias, remove the next one # *unless* the last alias has a no-arg flag version, in which # case, don't swallow the next arg if it's also a flag: if not (was_flag and a.startswith('-')): stripped.remove(a) continue if a.startswith('-'): split = a.lstrip('-').split('=') alias = split[0] if alias in aliases: stripped.remove(a) if len(split) == 1: # alias passed with arg via space swallow_next = True # could have been a flag that matches an alias, e.g. `existing` # in which case, we might not swallow the next arg was_flag = alias in flags elif alias in flags and len(split) == 1: # strip flag, but don't swallow next, as flags don't take args stripped.remove(a) # return shortened list return stripped
def swallow_argv(argv, aliases=None, flags=None): """strip frontend-specific aliases and flags from an argument list For use primarily in frontend apps that want to pass a subset of command-line arguments through to a subprocess, where frontend-specific flags and aliases should be removed from the list. Parameters ---------- argv : list(str) The starting argv, to be filtered aliases : container of aliases (dict, list, set, etc.) The frontend-specific aliases to be removed flags : container of flags (dict, list, set, etc.) The frontend-specific flags to be removed Returns ------- argv : list(str) The argv list, excluding flags and aliases that have been stripped """ if aliases is None: aliases = set() if flags is None: flags = set() stripped = list(argv) # copy swallow_next = False was_flag = False for a in argv: if swallow_next: swallow_next = False # last arg was an alias, remove the next one # *unless* the last alias has a no-arg flag version, in which # case, don't swallow the next arg if it's also a flag: if not (was_flag and a.startswith('-')): stripped.remove(a) continue if a.startswith('-'): split = a.lstrip('-').split('=') alias = split[0] if alias in aliases: stripped.remove(a) if len(split) == 1: # alias passed with arg via space swallow_next = True # could have been a flag that matches an alias, e.g. `existing` # in which case, we might not swallow the next arg was_flag = alias in flags elif alias in flags and len(split) == 1: # strip flag, but don't swallow next, as flags don't take args stripped.remove(a) # return shortened list return stripped
[ "strip", "frontend", "-", "specific", "aliases", "and", "flags", "from", "an", "argument", "list", "For", "use", "primarily", "in", "frontend", "apps", "that", "want", "to", "pass", "a", "subset", "of", "command", "-", "line", "arguments", "through", "to", "a", "subprocess", "where", "frontend", "-", "specific", "flags", "and", "aliases", "should", "be", "removed", "from", "the", "list", ".", "Parameters", "----------", "argv", ":", "list", "(", "str", ")", "The", "starting", "argv", "to", "be", "filtered", "aliases", ":", "container", "of", "aliases", "(", "dict", "list", "set", "etc", ".", ")", "The", "frontend", "-", "specific", "aliases", "to", "be", "removed", "flags", ":", "container", "of", "flags", "(", "dict", "list", "set", "etc", ".", ")", "The", "frontend", "-", "specific", "flags", "to", "be", "removed", "Returns", "-------", "argv", ":", "list", "(", "str", ")", "The", "argv", "list", "excluding", "flags", "and", "aliases", "that", "have", "been", "stripped" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/kernel.py#L256-L314
[ "def", "swallow_argv", "(", "argv", ",", "aliases", "=", "None", ",", "flags", "=", "None", ")", ":", "if", "aliases", "is", "None", ":", "aliases", "=", "set", "(", ")", "if", "flags", "is", "None", ":", "flags", "=", "set", "(", ")", "stripped", "=", "list", "(", "argv", ")", "# copy", "swallow_next", "=", "False", "was_flag", "=", "False", "for", "a", "in", "argv", ":", "if", "swallow_next", ":", "swallow_next", "=", "False", "# last arg was an alias, remove the next one", "# *unless* the last alias has a no-arg flag version, in which", "# case, don't swallow the next arg if it's also a flag:", "if", "not", "(", "was_flag", "and", "a", ".", "startswith", "(", "'-'", ")", ")", ":", "stripped", ".", "remove", "(", "a", ")", "continue", "if", "a", ".", "startswith", "(", "'-'", ")", ":", "split", "=", "a", ".", "lstrip", "(", "'-'", ")", ".", "split", "(", "'='", ")", "alias", "=", "split", "[", "0", "]", "if", "alias", "in", "aliases", ":", "stripped", ".", "remove", "(", "a", ")", "if", "len", "(", "split", ")", "==", "1", ":", "# alias passed with arg via space", "swallow_next", "=", "True", "# could have been a flag that matches an alias, e.g. `existing`", "# in which case, we might not swallow the next arg", "was_flag", "=", "alias", "in", "flags", "elif", "alias", "in", "flags", "and", "len", "(", "split", ")", "==", "1", ":", "# strip flag, but don't swallow next, as flags don't take args", "stripped", ".", "remove", "(", "a", ")", "# return shortened list", "return", "stripped" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
pkg_commit_hash
Get short form of commit hash given directory `pkg_path` We get the commit hash from (in order of preference): * IPython.utils._sysinfo.commit * git output, if we are in a git repository If these fail, we return a not-found placeholder tuple Parameters ---------- pkg_path : str directory containing package only used for getting commit from active repo Returns ------- hash_from : str Where we got the hash from - description hash_str : str short form of hash
environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py
def pkg_commit_hash(pkg_path): """Get short form of commit hash given directory `pkg_path` We get the commit hash from (in order of preference): * IPython.utils._sysinfo.commit * git output, if we are in a git repository If these fail, we return a not-found placeholder tuple Parameters ---------- pkg_path : str directory containing package only used for getting commit from active repo Returns ------- hash_from : str Where we got the hash from - description hash_str : str short form of hash """ # Try and get commit from written commit text file if _sysinfo.commit: return "installation", _sysinfo.commit # maybe we are in a repository proc = subprocess.Popen('git rev-parse --short HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=pkg_path, shell=True) repo_commit, _ = proc.communicate() if repo_commit: return 'repository', repo_commit.strip() return '(none found)', '<not found>'
def pkg_commit_hash(pkg_path): """Get short form of commit hash given directory `pkg_path` We get the commit hash from (in order of preference): * IPython.utils._sysinfo.commit * git output, if we are in a git repository If these fail, we return a not-found placeholder tuple Parameters ---------- pkg_path : str directory containing package only used for getting commit from active repo Returns ------- hash_from : str Where we got the hash from - description hash_str : str short form of hash """ # Try and get commit from written commit text file if _sysinfo.commit: return "installation", _sysinfo.commit # maybe we are in a repository proc = subprocess.Popen('git rev-parse --short HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=pkg_path, shell=True) repo_commit, _ = proc.communicate() if repo_commit: return 'repository', repo_commit.strip() return '(none found)', '<not found>'
[ "Get", "short", "form", "of", "commit", "hash", "given", "directory", "pkg_path" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py#L32-L67
[ "def", "pkg_commit_hash", "(", "pkg_path", ")", ":", "# Try and get commit from written commit text file", "if", "_sysinfo", ".", "commit", ":", "return", "\"installation\"", ",", "_sysinfo", ".", "commit", "# maybe we are in a repository", "proc", "=", "subprocess", ".", "Popen", "(", "'git rev-parse --short HEAD'", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "pkg_path", ",", "shell", "=", "True", ")", "repo_commit", ",", "_", "=", "proc", ".", "communicate", "(", ")", "if", "repo_commit", ":", "return", "'repository'", ",", "repo_commit", ".", "strip", "(", ")", "return", "'(none found)'", ",", "'<not found>'" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
pkg_info
Return dict describing the context of this package Parameters ---------- pkg_path : str path containing __init__.py for package Returns ------- context : dict with named parameters of interest
environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py
def pkg_info(pkg_path): """Return dict describing the context of this package Parameters ---------- pkg_path : str path containing __init__.py for package Returns ------- context : dict with named parameters of interest """ src, hsh = pkg_commit_hash(pkg_path) return dict( ipython_version=release.version, ipython_path=pkg_path, commit_source=src, commit_hash=hsh, sys_version=sys.version, sys_executable=sys.executable, sys_platform=sys.platform, platform=platform.platform(), os_name=os.name, default_encoding=encoding.DEFAULT_ENCODING, )
def pkg_info(pkg_path): """Return dict describing the context of this package Parameters ---------- pkg_path : str path containing __init__.py for package Returns ------- context : dict with named parameters of interest """ src, hsh = pkg_commit_hash(pkg_path) return dict( ipython_version=release.version, ipython_path=pkg_path, commit_source=src, commit_hash=hsh, sys_version=sys.version, sys_executable=sys.executable, sys_platform=sys.platform, platform=platform.platform(), os_name=os.name, default_encoding=encoding.DEFAULT_ENCODING, )
[ "Return", "dict", "describing", "the", "context", "of", "this", "package" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py#L70-L95
[ "def", "pkg_info", "(", "pkg_path", ")", ":", "src", ",", "hsh", "=", "pkg_commit_hash", "(", "pkg_path", ")", "return", "dict", "(", "ipython_version", "=", "release", ".", "version", ",", "ipython_path", "=", "pkg_path", ",", "commit_source", "=", "src", ",", "commit_hash", "=", "hsh", ",", "sys_version", "=", "sys", ".", "version", ",", "sys_executable", "=", "sys", ".", "executable", ",", "sys_platform", "=", "sys", ".", "platform", ",", "platform", "=", "platform", ".", "platform", "(", ")", ",", "os_name", "=", "os", ".", "name", ",", "default_encoding", "=", "encoding", ".", "DEFAULT_ENCODING", ",", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
sys_info
Return useful information about IPython and the system, as a string. Example ------- In [2]: print sys_info() {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick', 'sys_executable': '/usr/bin/python', 'sys_platform': 'linux2', 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'}
environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py
def sys_info(): """Return useful information about IPython and the system, as a string. Example ------- In [2]: print sys_info() {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick', 'sys_executable': '/usr/bin/python', 'sys_platform': 'linux2', 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'} """ p = os.path path = p.dirname(p.abspath(p.join(__file__, '..'))) return pprint.pformat(pkg_info(path))
def sys_info(): """Return useful information about IPython and the system, as a string. Example ------- In [2]: print sys_info() {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick', 'sys_executable': '/usr/bin/python', 'sys_platform': 'linux2', 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'} """ p = os.path path = p.dirname(p.abspath(p.join(__file__, '..'))) return pprint.pformat(pkg_info(path))
[ "Return", "useful", "information", "about", "IPython", "and", "the", "system", "as", "a", "string", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py#L99-L117
[ "def", "sys_info", "(", ")", ":", "p", "=", "os", ".", "path", "path", "=", "p", ".", "dirname", "(", "p", ".", "abspath", "(", "p", ".", "join", "(", "__file__", ",", "'..'", ")", ")", ")", "return", "pprint", ".", "pformat", "(", "pkg_info", "(", "path", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
_num_cpus_darwin
Return the number of active CPUs on a Darwin system.
environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py
def _num_cpus_darwin(): """Return the number of active CPUs on a Darwin system.""" p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) return p.stdout.read()
def _num_cpus_darwin(): """Return the number of active CPUs on a Darwin system.""" p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) return p.stdout.read()
[ "Return", "the", "number", "of", "active", "CPUs", "on", "a", "Darwin", "system", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py#L125-L128
[ "def", "_num_cpus_darwin", "(", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'sysctl'", ",", "'-n'", ",", "'hw.ncpu'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "return", "p", ".", "stdout", ".", "read", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
num_cpus
Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make it return a large positive number that's actually incorrect).
environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py
def num_cpus(): """Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make it return a large positive number that's actually incorrect). """ # Many thanks to the Parallel Python project (http://www.parallelpython.com) # for the names of the keys we needed to look up for this function. This # code was inspired by their equivalent function. ncpufuncs = {'Linux':_num_cpus_unix, 'Darwin':_num_cpus_darwin, 'Windows':_num_cpus_windows, # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' # See http://bugs.python.org/issue1082 for details. 'Microsoft':_num_cpus_windows, } ncpufunc = ncpufuncs.get(platform.system(), # default to unix version (Solaris, AIX, etc) _num_cpus_unix) try: ncpus = max(1,int(ncpufunc())) except: ncpus = 1 return ncpus
def num_cpus(): """Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make it return a large positive number that's actually incorrect). """ # Many thanks to the Parallel Python project (http://www.parallelpython.com) # for the names of the keys we needed to look up for this function. This # code was inspired by their equivalent function. ncpufuncs = {'Linux':_num_cpus_unix, 'Darwin':_num_cpus_darwin, 'Windows':_num_cpus_windows, # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' # See http://bugs.python.org/issue1082 for details. 'Microsoft':_num_cpus_windows, } ncpufunc = ncpufuncs.get(platform.system(), # default to unix version (Solaris, AIX, etc) _num_cpus_unix) try: ncpus = max(1,int(ncpufunc())) except: ncpus = 1 return ncpus
[ "Return", "the", "effective", "number", "of", "CPUs", "in", "the", "system", "as", "an", "integer", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/sysinfo.py#L136-L167
[ "def", "num_cpus", "(", ")", ":", "# Many thanks to the Parallel Python project (http://www.parallelpython.com)", "# for the names of the keys we needed to look up for this function. This", "# code was inspired by their equivalent function.", "ncpufuncs", "=", "{", "'Linux'", ":", "_num_cpus_unix", ",", "'Darwin'", ":", "_num_cpus_darwin", ",", "'Windows'", ":", "_num_cpus_windows", ",", "# On Vista, python < 2.5.2 has a bug and returns 'Microsoft'", "# See http://bugs.python.org/issue1082 for details.", "'Microsoft'", ":", "_num_cpus_windows", ",", "}", "ncpufunc", "=", "ncpufuncs", ".", "get", "(", "platform", ".", "system", "(", ")", ",", "# default to unix version (Solaris, AIX, etc)", "_num_cpus_unix", ")", "try", ":", "ncpus", "=", "max", "(", "1", ",", "int", "(", "ncpufunc", "(", ")", ")", ")", "except", ":", "ncpus", "=", "1", "return", "ncpus" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Command.handle
[1, 2, 3, 4] {'accumulate': <built-in function max>}
example/management/commands/positional.py
def handle(self, integers, **options): """ [1, 2, 3, 4] {'accumulate': <built-in function max>} """ print integers, options return super(Command, self).handle(integers, **options)
def handle(self, integers, **options): """ [1, 2, 3, 4] {'accumulate': <built-in function max>} """ print integers, options return super(Command, self).handle(integers, **options)
[ "[", "1", "2", "3", "4", "]", "{", "accumulate", ":", "<built", "-", "in", "function", "max", ">", "}" ]
allanlei/django-argparse-command
python
https://github.com/allanlei/django-argparse-command/blob/27ea77e1dd0cf2f0567223735762a5ebd14fdaef/example/management/commands/positional.py#L13-L18
[ "def", "handle", "(", "self", ",", "integers", ",", "*", "*", "options", ")", ":", "print", "integers", ",", "options", "return", "super", "(", "Command", ",", "self", ")", ".", "handle", "(", "integers", ",", "*", "*", "options", ")" ]
27ea77e1dd0cf2f0567223735762a5ebd14fdaef
test
BaseCursor.nextset
Advance to the next result set. Returns None if there are no more result sets.
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py
def nextset(self): """Advance to the next result set. Returns None if there are no more result sets. """ if self._executed: self.fetchall() del self.messages[:] db = self._get_db() nr = db.next_result() if nr == -1: return None self._do_get_result() self._post_get_result() self._warning_check() return 1
def nextset(self): """Advance to the next result set. Returns None if there are no more result sets. """ if self._executed: self.fetchall() del self.messages[:] db = self._get_db() nr = db.next_result() if nr == -1: return None self._do_get_result() self._post_get_result() self._warning_check() return 1
[ "Advance", "to", "the", "next", "result", "set", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py#L122-L138
[ "def", "nextset", "(", "self", ")", ":", "if", "self", ".", "_executed", ":", "self", ".", "fetchall", "(", ")", "del", "self", ".", "messages", "[", ":", "]", "db", "=", "self", ".", "_get_db", "(", ")", "nr", "=", "db", ".", "next_result", "(", ")", "if", "nr", "==", "-", "1", ":", "return", "None", "self", ".", "_do_get_result", "(", ")", "self", ".", "_post_get_result", "(", ")", "self", ".", "_warning_check", "(", ")", "return", "1" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseCursor.execute
Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py
def execute(self, query, args=None): """Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any """ del self.messages[:] db = self._get_db() if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) if args is not None: query = query % db.literal(args) try: r = None r = self._query(query) except TypeError, m: if m.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.messages.append((ProgrammingError, m.args[0])) self.errorhandler(self, ProgrammingError, m.args[0]) else: self.messages.append((TypeError, m)) self.errorhandler(self, TypeError, m) except (SystemExit, KeyboardInterrupt): raise except: exc, value, tb = sys.exc_info() del tb self.messages.append((exc, value)) self.errorhandler(self, exc, value) self._executed = query if not self._defer_warnings: self._warning_check() return r
def execute(self, query, args=None): """Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any """ del self.messages[:] db = self._get_db() if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) if args is not None: query = query % db.literal(args) try: r = None r = self._query(query) except TypeError, m: if m.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.messages.append((ProgrammingError, m.args[0])) self.errorhandler(self, ProgrammingError, m.args[0]) else: self.messages.append((TypeError, m)) self.errorhandler(self, TypeError, m) except (SystemExit, KeyboardInterrupt): raise except: exc, value, tb = sys.exc_info() del tb self.messages.append((exc, value)) self.errorhandler(self, exc, value) self._executed = query if not self._defer_warnings: self._warning_check() return r
[ "Execute", "a", "query", ".", "query", "--", "string", "query", "to", "execute", "on", "server", "args", "--", "optional", "sequence", "or", "mapping", "parameters", "to", "use", "with", "query", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py#L164-L204
[ "def", "execute", "(", "self", ",", "query", ",", "args", "=", "None", ")", ":", "del", "self", ".", "messages", "[", ":", "]", "db", "=", "self", ".", "_get_db", "(", ")", "if", "isinstance", "(", "query", ",", "unicode", ")", ":", "query", "=", "query", ".", "encode", "(", "db", ".", "unicode_literal", ".", "charset", ")", "if", "args", "is", "not", "None", ":", "query", "=", "query", "%", "db", ".", "literal", "(", "args", ")", "try", ":", "r", "=", "None", "r", "=", "self", ".", "_query", "(", "query", ")", "except", "TypeError", ",", "m", ":", "if", "m", ".", "args", "[", "0", "]", "in", "(", "\"not enough arguments for format string\"", ",", "\"not all arguments converted\"", ")", ":", "self", ".", "messages", ".", "append", "(", "(", "ProgrammingError", ",", "m", ".", "args", "[", "0", "]", ")", ")", "self", ".", "errorhandler", "(", "self", ",", "ProgrammingError", ",", "m", ".", "args", "[", "0", "]", ")", "else", ":", "self", ".", "messages", ".", "append", "(", "(", "TypeError", ",", "m", ")", ")", "self", ".", "errorhandler", "(", "self", ",", "TypeError", ",", "m", ")", "except", "(", "SystemExit", ",", "KeyboardInterrupt", ")", ":", "raise", "except", ":", "exc", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "del", "tb", "self", ".", "messages", ".", "append", "(", "(", "exc", ",", "value", ")", ")", "self", ".", "errorhandler", "(", "self", ",", "exc", ",", "value", ")", "self", ".", "_executed", "=", "query", "if", "not", "self", ".", "_defer_warnings", ":", "self", ".", "_warning_check", "(", ")", "return", "r" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseCursor.executemany
Execute a multi-row query. query -- string, query to execute on server args Sequence of sequences or mappings, parameters to use with query. Returns long integer rows affected, if any. This method improves performance on multiple-row INSERT and REPLACE. Otherwise it is equivalent to looping over args with execute().
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py
def executemany(self, query, args): """Execute a multi-row query. query -- string, query to execute on server args Sequence of sequences or mappings, parameters to use with query. Returns long integer rows affected, if any. This method improves performance on multiple-row INSERT and REPLACE. Otherwise it is equivalent to looping over args with execute(). """ del self.messages[:] db = self._get_db() if not args: return if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) m = insert_values.search(query) if not m: r = 0 for a in args: r = r + self.execute(query, a) return r p = m.start(1) e = m.end(1) qv = m.group(1) try: q = [ qv % db.literal(a) for a in args ] except TypeError, msg: if msg.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.errorhandler(self, ProgrammingError, msg.args[0]) else: self.errorhandler(self, TypeError, msg) except (SystemExit, KeyboardInterrupt): raise except: exc, value, tb = sys.exc_info() del tb self.errorhandler(self, exc, value) r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]])) if not self._defer_warnings: self._warning_check() return r
def executemany(self, query, args): """Execute a multi-row query. query -- string, query to execute on server args Sequence of sequences or mappings, parameters to use with query. Returns long integer rows affected, if any. This method improves performance on multiple-row INSERT and REPLACE. Otherwise it is equivalent to looping over args with execute(). """ del self.messages[:] db = self._get_db() if not args: return if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) m = insert_values.search(query) if not m: r = 0 for a in args: r = r + self.execute(query, a) return r p = m.start(1) e = m.end(1) qv = m.group(1) try: q = [ qv % db.literal(a) for a in args ] except TypeError, msg: if msg.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.errorhandler(self, ProgrammingError, msg.args[0]) else: self.errorhandler(self, TypeError, msg) except (SystemExit, KeyboardInterrupt): raise except: exc, value, tb = sys.exc_info() del tb self.errorhandler(self, exc, value) r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]])) if not self._defer_warnings: self._warning_check() return r
[ "Execute", "a", "multi", "-", "row", "query", ".", "query", "--", "string", "query", "to", "execute", "on", "server" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py#L206-L254
[ "def", "executemany", "(", "self", ",", "query", ",", "args", ")", ":", "del", "self", ".", "messages", "[", ":", "]", "db", "=", "self", ".", "_get_db", "(", ")", "if", "not", "args", ":", "return", "if", "isinstance", "(", "query", ",", "unicode", ")", ":", "query", "=", "query", ".", "encode", "(", "db", ".", "unicode_literal", ".", "charset", ")", "m", "=", "insert_values", ".", "search", "(", "query", ")", "if", "not", "m", ":", "r", "=", "0", "for", "a", "in", "args", ":", "r", "=", "r", "+", "self", ".", "execute", "(", "query", ",", "a", ")", "return", "r", "p", "=", "m", ".", "start", "(", "1", ")", "e", "=", "m", ".", "end", "(", "1", ")", "qv", "=", "m", ".", "group", "(", "1", ")", "try", ":", "q", "=", "[", "qv", "%", "db", ".", "literal", "(", "a", ")", "for", "a", "in", "args", "]", "except", "TypeError", ",", "msg", ":", "if", "msg", ".", "args", "[", "0", "]", "in", "(", "\"not enough arguments for format string\"", ",", "\"not all arguments converted\"", ")", ":", "self", ".", "errorhandler", "(", "self", ",", "ProgrammingError", ",", "msg", ".", "args", "[", "0", "]", ")", "else", ":", "self", ".", "errorhandler", "(", "self", ",", "TypeError", ",", "msg", ")", "except", "(", "SystemExit", ",", "KeyboardInterrupt", ")", ":", "raise", "except", ":", "exc", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "del", "tb", "self", ".", "errorhandler", "(", "self", ",", "exc", ",", "value", ")", "r", "=", "self", ".", "_query", "(", "'\\n'", ".", "join", "(", "[", "query", "[", ":", "p", "]", ",", "',\\n'", ".", "join", "(", "q", ")", ",", "query", "[", "e", ":", "]", "]", ")", ")", "if", "not", "self", ".", "_defer_warnings", ":", "self", ".", "_warning_check", "(", ")", "return", "r" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseCursor.callproc
Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are only available by storing them in a server variable and then retrieved by a query. Since stored procedures return zero or more result sets, there is no reliable way to get at OUT or INOUT parameters via callproc. The server variables are named @_procname_n, where procname is the parameter above and n is the position of the parameter (from zero). Once all result sets generated by the procedure have been fetched, you can issue a SELECT @_procname_0, ... query using .execute() to get any OUT or INOUT values. Compatibility warning: The act of calling a stored procedure itself creates an empty result set. This appears after any result sets generated by the procedure. This is non-standard behavior with respect to the DB-API. Be sure to use nextset() to advance through all result sets; otherwise you may get disconnected.
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py
def callproc(self, procname, args=()): """Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are only available by storing them in a server variable and then retrieved by a query. Since stored procedures return zero or more result sets, there is no reliable way to get at OUT or INOUT parameters via callproc. The server variables are named @_procname_n, where procname is the parameter above and n is the position of the parameter (from zero). Once all result sets generated by the procedure have been fetched, you can issue a SELECT @_procname_0, ... query using .execute() to get any OUT or INOUT values. Compatibility warning: The act of calling a stored procedure itself creates an empty result set. This appears after any result sets generated by the procedure. This is non-standard behavior with respect to the DB-API. Be sure to use nextset() to advance through all result sets; otherwise you may get disconnected. """ db = self._get_db() for index, arg in enumerate(args): q = "SET @_%s_%d=%s" % (procname, index, db.literal(arg)) if isinstance(q, unicode): q = q.encode(db.unicode_literal.charset) self._query(q) self.nextset() q = "CALL %s(%s)" % (procname, ','.join(['@_%s_%d' % (procname, i) for i in range(len(args))])) if type(q) is UnicodeType: q = q.encode(db.unicode_literal.charset) self._query(q) self._executed = q if not self._defer_warnings: self._warning_check() return args
def callproc(self, procname, args=()): """Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are only available by storing them in a server variable and then retrieved by a query. Since stored procedures return zero or more result sets, there is no reliable way to get at OUT or INOUT parameters via callproc. The server variables are named @_procname_n, where procname is the parameter above and n is the position of the parameter (from zero). Once all result sets generated by the procedure have been fetched, you can issue a SELECT @_procname_0, ... query using .execute() to get any OUT or INOUT values. Compatibility warning: The act of calling a stored procedure itself creates an empty result set. This appears after any result sets generated by the procedure. This is non-standard behavior with respect to the DB-API. Be sure to use nextset() to advance through all result sets; otherwise you may get disconnected. """ db = self._get_db() for index, arg in enumerate(args): q = "SET @_%s_%d=%s" % (procname, index, db.literal(arg)) if isinstance(q, unicode): q = q.encode(db.unicode_literal.charset) self._query(q) self.nextset() q = "CALL %s(%s)" % (procname, ','.join(['@_%s_%d' % (procname, i) for i in range(len(args))])) if type(q) is UnicodeType: q = q.encode(db.unicode_literal.charset) self._query(q) self._executed = q if not self._defer_warnings: self._warning_check() return args
[ "Execute", "stored", "procedure", "procname", "with", "args", "procname", "--", "string", "name", "of", "procedure", "to", "execute", "on", "server" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py#L256-L303
[ "def", "callproc", "(", "self", ",", "procname", ",", "args", "=", "(", ")", ")", ":", "db", "=", "self", ".", "_get_db", "(", ")", "for", "index", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "q", "=", "\"SET @_%s_%d=%s\"", "%", "(", "procname", ",", "index", ",", "db", ".", "literal", "(", "arg", ")", ")", "if", "isinstance", "(", "q", ",", "unicode", ")", ":", "q", "=", "q", ".", "encode", "(", "db", ".", "unicode_literal", ".", "charset", ")", "self", ".", "_query", "(", "q", ")", "self", ".", "nextset", "(", ")", "q", "=", "\"CALL %s(%s)\"", "%", "(", "procname", ",", "','", ".", "join", "(", "[", "'@_%s_%d'", "%", "(", "procname", ",", "i", ")", "for", "i", "in", "range", "(", "len", "(", "args", ")", ")", "]", ")", ")", "if", "type", "(", "q", ")", "is", "UnicodeType", ":", "q", "=", "q", ".", "encode", "(", "db", ".", "unicode_literal", ".", "charset", ")", "self", ".", "_query", "(", "q", ")", "self", ".", "_executed", "=", "q", "if", "not", "self", ".", "_defer_warnings", ":", "self", ".", "_warning_check", "(", ")", "return", "args" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CursorUseResultMixIn.fetchone
Fetches a single row from the cursor.
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py
def fetchone(self): """Fetches a single row from the cursor.""" self._check_executed() r = self._fetch_row(1) if not r: self._warning_check() return None self.rownumber = self.rownumber + 1 return r[0]
def fetchone(self): """Fetches a single row from the cursor.""" self._check_executed() r = self._fetch_row(1) if not r: self._warning_check() return None self.rownumber = self.rownumber + 1 return r[0]
[ "Fetches", "a", "single", "row", "from", "the", "cursor", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py#L417-L425
[ "def", "fetchone", "(", "self", ")", ":", "self", ".", "_check_executed", "(", ")", "r", "=", "self", ".", "_fetch_row", "(", "1", ")", "if", "not", "r", ":", "self", ".", "_warning_check", "(", ")", "return", "None", "self", ".", "rownumber", "=", "self", ".", "rownumber", "+", "1", "return", "r", "[", "0", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CursorUseResultMixIn.fetchmany
Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined, cursor.arraysize is used.
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py
def fetchmany(self, size=None): """Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined, cursor.arraysize is used.""" self._check_executed() r = self._fetch_row(size or self.arraysize) self.rownumber = self.rownumber + len(r) if not r: self._warning_check() return r
def fetchmany(self, size=None): """Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined, cursor.arraysize is used.""" self._check_executed() r = self._fetch_row(size or self.arraysize) self.rownumber = self.rownumber + len(r) if not r: self._warning_check() return r
[ "Fetch", "up", "to", "size", "rows", "from", "the", "cursor", ".", "Result", "set", "may", "be", "smaller", "than", "size", ".", "If", "size", "is", "not", "defined", "cursor", ".", "arraysize", "is", "used", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py#L427-L435
[ "def", "fetchmany", "(", "self", ",", "size", "=", "None", ")", ":", "self", ".", "_check_executed", "(", ")", "r", "=", "self", ".", "_fetch_row", "(", "size", "or", "self", ".", "arraysize", ")", "self", ".", "rownumber", "=", "self", ".", "rownumber", "+", "len", "(", "r", ")", "if", "not", "r", ":", "self", ".", "_warning_check", "(", ")", "return", "r" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CursorUseResultMixIn.fetchall
Fetchs all available rows from the cursor.
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py
def fetchall(self): """Fetchs all available rows from the cursor.""" self._check_executed() r = self._fetch_row(0) self.rownumber = self.rownumber + len(r) self._warning_check() return r
def fetchall(self): """Fetchs all available rows from the cursor.""" self._check_executed() r = self._fetch_row(0) self.rownumber = self.rownumber + len(r) self._warning_check() return r
[ "Fetchs", "all", "available", "rows", "from", "the", "cursor", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py#L437-L443
[ "def", "fetchall", "(", "self", ")", ":", "self", ".", "_check_executed", "(", ")", "r", "=", "self", ".", "_fetch_row", "(", "0", ")", "self", ".", "rownumber", "=", "self", ".", "rownumber", "+", "len", "(", "r", ")", "self", ".", "_warning_check", "(", ")", "return", "r" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CursorDictRowsMixIn.fetchmanyDict
Fetch several rows as a list of dictionaries. Deprecated: Use fetchmany() instead. Will be removed in 1.3.
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py
def fetchmanyDict(self, size=None): """Fetch several rows as a list of dictionaries. Deprecated: Use fetchmany() instead. Will be removed in 1.3.""" from warnings import warn warn("fetchmanyDict() is non-standard and will be removed in 1.3", DeprecationWarning, 2) return self.fetchmany(size)
def fetchmanyDict(self, size=None): """Fetch several rows as a list of dictionaries. Deprecated: Use fetchmany() instead. Will be removed in 1.3.""" from warnings import warn warn("fetchmanyDict() is non-standard and will be removed in 1.3", DeprecationWarning, 2) return self.fetchmany(size)
[ "Fetch", "several", "rows", "as", "a", "list", "of", "dictionaries", ".", "Deprecated", ":", "Use", "fetchmany", "()", "instead", ".", "Will", "be", "removed", "in", "1", ".", "3", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py#L478-L484
[ "def", "fetchmanyDict", "(", "self", ",", "size", "=", "None", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "\"fetchmanyDict() is non-standard and will be removed in 1.3\"", ",", "DeprecationWarning", ",", "2", ")", "return", "self", ".", "fetchmany", "(", "size", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
connect
this function will be called on the engines
environment/share/doc/ipython/examples/parallel/interengine/bintree_script.py
def connect(com, peers, tree, pub_url, root_id): """this function will be called on the engines""" com.connect(peers, tree, pub_url, root_id)
def connect(com, peers, tree, pub_url, root_id): """this function will be called on the engines""" com.connect(peers, tree, pub_url, root_id)
[ "this", "function", "will", "be", "called", "on", "the", "engines" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/bintree_script.py#L56-L58
[ "def", "connect", "(", "com", ",", "peers", ",", "tree", ",", "pub_url", ",", "root_id", ")", ":", "com", ".", "connect", "(", "peers", ",", "tree", ",", "pub_url", ",", "root_id", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
parse_json
Parse a string into a (nbformat, dict) tuple.
environment/lib/python2.7/site-packages/IPython/nbformat/current.py
def parse_json(s, **kwargs): """Parse a string into a (nbformat, dict) tuple.""" d = json.loads(s, **kwargs) nbf = d.get('nbformat', 1) nbm = d.get('nbformat_minor', 0) return nbf, nbm, d
def parse_json(s, **kwargs): """Parse a string into a (nbformat, dict) tuple.""" d = json.loads(s, **kwargs) nbf = d.get('nbformat', 1) nbm = d.get('nbformat_minor', 0) return nbf, nbm, d
[ "Parse", "a", "string", "into", "a", "(", "nbformat", "dict", ")", "tuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/current.py#L48-L53
[ "def", "parse_json", "(", "s", ",", "*", "*", "kwargs", ")", ":", "d", "=", "json", ".", "loads", "(", "s", ",", "*", "*", "kwargs", ")", "nbf", "=", "d", ".", "get", "(", "'nbformat'", ",", "1", ")", "nbm", "=", "d", ".", "get", "(", "'nbformat_minor'", ",", "0", ")", "return", "nbf", ",", "nbm", ",", "d" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
parse_py
Parse a string into a (nbformat, string) tuple.
environment/lib/python2.7/site-packages/IPython/nbformat/current.py
def parse_py(s, **kwargs): """Parse a string into a (nbformat, string) tuple.""" nbf = current_nbformat nbm = current_nbformat_minor pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>' m = re.search(pattern,s) if m is not None: digits = m.group('nbformat').split('.') nbf = int(digits[0]) if len(digits) > 1: nbm = int(digits[1]) return nbf, nbm, s
def parse_py(s, **kwargs): """Parse a string into a (nbformat, string) tuple.""" nbf = current_nbformat nbm = current_nbformat_minor pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>' m = re.search(pattern,s) if m is not None: digits = m.group('nbformat').split('.') nbf = int(digits[0]) if len(digits) > 1: nbm = int(digits[1]) return nbf, nbm, s
[ "Parse", "a", "string", "into", "a", "(", "nbformat", "string", ")", "tuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/current.py#L56-L69
[ "def", "parse_py", "(", "s", ",", "*", "*", "kwargs", ")", ":", "nbf", "=", "current_nbformat", "nbm", "=", "current_nbformat_minor", "pattern", "=", "r'# <nbformat>(?P<nbformat>\\d+[\\.\\d+]*)</nbformat>'", "m", "=", "re", ".", "search", "(", "pattern", ",", "s", ")", "if", "m", "is", "not", "None", ":", "digits", "=", "m", ".", "group", "(", "'nbformat'", ")", ".", "split", "(", "'.'", ")", "nbf", "=", "int", "(", "digits", "[", "0", "]", ")", "if", "len", "(", "digits", ")", ">", "1", ":", "nbm", "=", "int", "(", "digits", "[", "1", "]", ")", "return", "nbf", ",", "nbm", ",", "s" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
reads_json
Read a JSON notebook from a string and return the NotebookNode object.
environment/lib/python2.7/site-packages/IPython/nbformat/current.py
def reads_json(s, **kwargs): """Read a JSON notebook from a string and return the NotebookNode object.""" nbf, minor, d = parse_json(s, **kwargs) if nbf == 1: nb = v1.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=1) elif nbf == 2: nb = v2.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=2) elif nbf == 3: nb = v3.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=3, orig_minor=minor) else: raise NBFormatError('Unsupported JSON nbformat version: %i' % nbf) return nb
def reads_json(s, **kwargs): """Read a JSON notebook from a string and return the NotebookNode object.""" nbf, minor, d = parse_json(s, **kwargs) if nbf == 1: nb = v1.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=1) elif nbf == 2: nb = v2.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=2) elif nbf == 3: nb = v3.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=3, orig_minor=minor) else: raise NBFormatError('Unsupported JSON nbformat version: %i' % nbf) return nb
[ "Read", "a", "JSON", "notebook", "from", "a", "string", "and", "return", "the", "NotebookNode", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/current.py#L72-L86
[ "def", "reads_json", "(", "s", ",", "*", "*", "kwargs", ")", ":", "nbf", ",", "minor", ",", "d", "=", "parse_json", "(", "s", ",", "*", "*", "kwargs", ")", "if", "nbf", "==", "1", ":", "nb", "=", "v1", ".", "to_notebook_json", "(", "d", ",", "*", "*", "kwargs", ")", "nb", "=", "v3", ".", "convert_to_this_nbformat", "(", "nb", ",", "orig_version", "=", "1", ")", "elif", "nbf", "==", "2", ":", "nb", "=", "v2", ".", "to_notebook_json", "(", "d", ",", "*", "*", "kwargs", ")", "nb", "=", "v3", ".", "convert_to_this_nbformat", "(", "nb", ",", "orig_version", "=", "2", ")", "elif", "nbf", "==", "3", ":", "nb", "=", "v3", ".", "to_notebook_json", "(", "d", ",", "*", "*", "kwargs", ")", "nb", "=", "v3", ".", "convert_to_this_nbformat", "(", "nb", ",", "orig_version", "=", "3", ",", "orig_minor", "=", "minor", ")", "else", ":", "raise", "NBFormatError", "(", "'Unsupported JSON nbformat version: %i'", "%", "nbf", ")", "return", "nb" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
reads_py
Read a .py notebook from a string and return the NotebookNode object.
environment/lib/python2.7/site-packages/IPython/nbformat/current.py
def reads_py(s, **kwargs): """Read a .py notebook from a string and return the NotebookNode object.""" nbf, nbm, s = parse_py(s, **kwargs) if nbf == 2: nb = v2.to_notebook_py(s, **kwargs) elif nbf == 3: nb = v3.to_notebook_py(s, **kwargs) else: raise NBFormatError('Unsupported PY nbformat version: %i' % nbf) return nb
def reads_py(s, **kwargs): """Read a .py notebook from a string and return the NotebookNode object.""" nbf, nbm, s = parse_py(s, **kwargs) if nbf == 2: nb = v2.to_notebook_py(s, **kwargs) elif nbf == 3: nb = v3.to_notebook_py(s, **kwargs) else: raise NBFormatError('Unsupported PY nbformat version: %i' % nbf) return nb
[ "Read", "a", ".", "py", "notebook", "from", "a", "string", "and", "return", "the", "NotebookNode", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/current.py#L93-L102
[ "def", "reads_py", "(", "s", ",", "*", "*", "kwargs", ")", ":", "nbf", ",", "nbm", ",", "s", "=", "parse_py", "(", "s", ",", "*", "*", "kwargs", ")", "if", "nbf", "==", "2", ":", "nb", "=", "v2", ".", "to_notebook_py", "(", "s", ",", "*", "*", "kwargs", ")", "elif", "nbf", "==", "3", ":", "nb", "=", "v3", ".", "to_notebook_py", "(", "s", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "NBFormatError", "(", "'Unsupported PY nbformat version: %i'", "%", "nbf", ")", "return", "nb" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
reads
Read a notebook from a string and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- s : unicode The raw unicode string to read the notebook from. format : (u'json', u'ipynb', u'py') The format that the string is in. Returns ------- nb : NotebookNode The notebook that was read.
environment/lib/python2.7/site-packages/IPython/nbformat/current.py
def reads(s, format, **kwargs): """Read a notebook from a string and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- s : unicode The raw unicode string to read the notebook from. format : (u'json', u'ipynb', u'py') The format that the string is in. Returns ------- nb : NotebookNode The notebook that was read. """ format = unicode(format) if format == u'json' or format == u'ipynb': return reads_json(s, **kwargs) elif format == u'py': return reads_py(s, **kwargs) else: raise NBFormatError('Unsupported format: %s' % format)
def reads(s, format, **kwargs): """Read a notebook from a string and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- s : unicode The raw unicode string to read the notebook from. format : (u'json', u'ipynb', u'py') The format that the string is in. Returns ------- nb : NotebookNode The notebook that was read. """ format = unicode(format) if format == u'json' or format == u'ipynb': return reads_json(s, **kwargs) elif format == u'py': return reads_py(s, **kwargs) else: raise NBFormatError('Unsupported format: %s' % format)
[ "Read", "a", "notebook", "from", "a", "string", "and", "return", "the", "NotebookNode", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/current.py#L112-L136
[ "def", "reads", "(", "s", ",", "format", ",", "*", "*", "kwargs", ")", ":", "format", "=", "unicode", "(", "format", ")", "if", "format", "==", "u'json'", "or", "format", "==", "u'ipynb'", ":", "return", "reads_json", "(", "s", ",", "*", "*", "kwargs", ")", "elif", "format", "==", "u'py'", ":", "return", "reads_py", "(", "s", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "NBFormatError", "(", "'Unsupported format: %s'", "%", "format", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
writes
Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string.
environment/lib/python2.7/site-packages/IPython/nbformat/current.py
def writes(nb, format, **kwargs): """Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string. """ format = unicode(format) if format == u'json' or format == u'ipynb': return writes_json(nb, **kwargs) elif format == u'py': return writes_py(nb, **kwargs) else: raise NBFormatError('Unsupported format: %s' % format)
def writes(nb, format, **kwargs): """Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string. """ format = unicode(format) if format == u'json' or format == u'ipynb': return writes_json(nb, **kwargs) elif format == u'py': return writes_py(nb, **kwargs) else: raise NBFormatError('Unsupported format: %s' % format)
[ "Write", "a", "notebook", "to", "a", "string", "in", "a", "given", "format", "in", "the", "current", "nbformat", "version", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/current.py#L139-L162
[ "def", "writes", "(", "nb", ",", "format", ",", "*", "*", "kwargs", ")", ":", "format", "=", "unicode", "(", "format", ")", "if", "format", "==", "u'json'", "or", "format", "==", "u'ipynb'", ":", "return", "writes_json", "(", "nb", ",", "*", "*", "kwargs", ")", "elif", "format", "==", "u'py'", ":", "return", "writes_py", "(", "nb", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "NBFormatError", "(", "'Unsupported format: %s'", "%", "format", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
write
Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string.
environment/lib/python2.7/site-packages/IPython/nbformat/current.py
def write(nb, fp, format, **kwargs): """Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string. """ return fp.write(writes(nb, format, **kwargs))
def write(nb, fp, format, **kwargs): """Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string. """ return fp.write(writes(nb, format, **kwargs))
[ "Write", "a", "notebook", "to", "a", "file", "in", "a", "given", "format", "in", "the", "current", "nbformat", "version", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/current.py#L186-L205
[ "def", "write", "(", "nb", ",", "fp", ",", "format", ",", "*", "*", "kwargs", ")", ":", "return", "fp", ".", "write", "(", "writes", "(", "nb", ",", "format", ",", "*", "*", "kwargs", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
_convert_to_metadata
Convert to a notebook having notebook metadata.
environment/lib/python2.7/site-packages/IPython/nbformat/current.py
def _convert_to_metadata(): """Convert to a notebook having notebook metadata.""" import glob for fname in glob.glob('*.ipynb'): print('Converting file:',fname) with open(fname,'r') as f: nb = read(f,u'json') md = new_metadata() if u'name' in nb: md.name = nb.name del nb[u'name'] nb.metadata = md with open(fname,'w') as f: write(nb, f, u'json')
def _convert_to_metadata(): """Convert to a notebook having notebook metadata.""" import glob for fname in glob.glob('*.ipynb'): print('Converting file:',fname) with open(fname,'r') as f: nb = read(f,u'json') md = new_metadata() if u'name' in nb: md.name = nb.name del nb[u'name'] nb.metadata = md with open(fname,'w') as f: write(nb, f, u'json')
[ "Convert", "to", "a", "notebook", "having", "notebook", "metadata", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/current.py#L207-L220
[ "def", "_convert_to_metadata", "(", ")", ":", "import", "glob", "for", "fname", "in", "glob", ".", "glob", "(", "'*.ipynb'", ")", ":", "print", "(", "'Converting file:'", ",", "fname", ")", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "nb", "=", "read", "(", "f", ",", "u'json'", ")", "md", "=", "new_metadata", "(", ")", "if", "u'name'", "in", "nb", ":", "md", ".", "name", "=", "nb", ".", "name", "del", "nb", "[", "u'name'", "]", "nb", ".", "metadata", "=", "md", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "write", "(", "nb", ",", "f", ",", "u'json'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Box.load_from_dict
try load value from dict. if key is not exists, mark as state unset.
jasily/data/box.py
def load_from_dict(self, src: dict, key): ''' try load value from dict. if key is not exists, mark as state unset. ''' if key in src: self.value = src[key] else: self.reset()
def load_from_dict(self, src: dict, key): ''' try load value from dict. if key is not exists, mark as state unset. ''' if key in src: self.value = src[key] else: self.reset()
[ "try", "load", "value", "from", "dict", ".", "if", "key", "is", "not", "exists", "mark", "as", "state", "unset", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/data/box.py#L50-L58
[ "def", "load_from_dict", "(", "self", ",", "src", ":", "dict", ",", "key", ")", ":", "if", "key", "in", "src", ":", "self", ".", "value", "=", "src", "[", "key", "]", "else", ":", "self", ".", "reset", "(", ")" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
inputhook_pyglet
Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance.
environment/lib/python2.7/site-packages/IPython/lib/inputhookpyglet.py
def inputhook_pyglet(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: t = clock() while not stdin_ready(): pyglet.clock.tick() for window in pyglet.app.windows: window.switch_to() window.dispatch_events() window.dispatch_event('on_draw') flip(window) # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 5*60.0: # print 'Sleep for 5 s' # dbg time.sleep(5.0) elif used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
def inputhook_pyglet(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: t = clock() while not stdin_ready(): pyglet.clock.tick() for window in pyglet.app.windows: window.switch_to() window.dispatch_events() window.dispatch_event('on_draw') flip(window) # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 5*60.0: # print 'Sleep for 5 s' # dbg time.sleep(5.0) elif used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
[ "Run", "the", "pyglet", "event", "loop", "by", "processing", "pending", "events", "only", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhookpyglet.py#L69-L115
[ "def", "inputhook_pyglet", "(", ")", ":", "# We need to protect against a user pressing Control-C when IPython is", "# idle and this is running. We trap KeyboardInterrupt and pass.", "try", ":", "t", "=", "clock", "(", ")", "while", "not", "stdin_ready", "(", ")", ":", "pyglet", ".", "clock", ".", "tick", "(", ")", "for", "window", "in", "pyglet", ".", "app", ".", "windows", ":", "window", ".", "switch_to", "(", ")", "window", ".", "dispatch_events", "(", ")", "window", ".", "dispatch_event", "(", "'on_draw'", ")", "flip", "(", "window", ")", "# We need to sleep at this point to keep the idle CPU load", "# low. However, if sleep to long, GUI response is poor. As", "# a compromise, we watch how often GUI events are being processed", "# and switch between a short and long sleep time. Here are some", "# stats useful in helping to tune this.", "# time CPU load", "# 0.001 13%", "# 0.005 3%", "# 0.01 1.5%", "# 0.05 0.5%", "used_time", "=", "clock", "(", ")", "-", "t", "if", "used_time", ">", "5", "*", "60.0", ":", "# print 'Sleep for 5 s' # dbg", "time", ".", "sleep", "(", "5.0", ")", "elif", "used_time", ">", "10.0", ":", "# print 'Sleep for 1 s' # dbg", "time", ".", "sleep", "(", "1.0", ")", "elif", "used_time", ">", "0.1", ":", "# Few GUI events coming in, so we can sleep longer", "# print 'Sleep for 0.05 s' # dbg", "time", ".", "sleep", "(", "0.05", ")", "else", ":", "# Many GUI events coming in, so sleep only very little", "time", ".", "sleep", "(", "0.001", ")", "except", "KeyboardInterrupt", ":", "pass", "return", "0" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Selector.matches
Does the name match my requirements? To match, a name must match config.testMatch OR config.include and it must not match config.exclude
environment/lib/python2.7/site-packages/nose/selector.py
def matches(self, name): """Does the name match my requirements? To match, a name must match config.testMatch OR config.include and it must not match config.exclude """ return ((self.match.search(name) or (self.include and filter(None, [inc.search(name) for inc in self.include]))) and ((not self.exclude) or not filter(None, [exc.search(name) for exc in self.exclude]) ))
def matches(self, name): """Does the name match my requirements? To match, a name must match config.testMatch OR config.include and it must not match config.exclude """ return ((self.match.search(name) or (self.include and filter(None, [inc.search(name) for inc in self.include]))) and ((not self.exclude) or not filter(None, [exc.search(name) for exc in self.exclude]) ))
[ "Does", "the", "name", "match", "my", "requirements?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/selector.py#L47-L60
[ "def", "matches", "(", "self", ",", "name", ")", ":", "return", "(", "(", "self", ".", "match", ".", "search", "(", "name", ")", "or", "(", "self", ".", "include", "and", "filter", "(", "None", ",", "[", "inc", ".", "search", "(", "name", ")", "for", "inc", "in", "self", ".", "include", "]", ")", ")", ")", "and", "(", "(", "not", "self", ".", "exclude", ")", "or", "not", "filter", "(", "None", ",", "[", "exc", ".", "search", "(", "name", ")", "for", "exc", "in", "self", ".", "exclude", "]", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Selector.wantClass
Is the class a wanted test class? A class must be a unittest.TestCase subclass, or match test name requirements. Classes that start with _ are always excluded.
environment/lib/python2.7/site-packages/nose/selector.py
def wantClass(self, cls): """Is the class a wanted test class? A class must be a unittest.TestCase subclass, or match test name requirements. Classes that start with _ are always excluded. """ declared = getattr(cls, '__test__', None) if declared is not None: wanted = declared else: wanted = (not cls.__name__.startswith('_') and (issubclass(cls, unittest.TestCase) or self.matches(cls.__name__))) plug_wants = self.plugins.wantClass(cls) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", cls, plug_wants) wanted = plug_wants log.debug("wantClass %s? %s", cls, wanted) return wanted
def wantClass(self, cls): """Is the class a wanted test class? A class must be a unittest.TestCase subclass, or match test name requirements. Classes that start with _ are always excluded. """ declared = getattr(cls, '__test__', None) if declared is not None: wanted = declared else: wanted = (not cls.__name__.startswith('_') and (issubclass(cls, unittest.TestCase) or self.matches(cls.__name__))) plug_wants = self.plugins.wantClass(cls) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", cls, plug_wants) wanted = plug_wants log.debug("wantClass %s? %s", cls, wanted) return wanted
[ "Is", "the", "class", "a", "wanted", "test", "class?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/selector.py#L62-L81
[ "def", "wantClass", "(", "self", ",", "cls", ")", ":", "declared", "=", "getattr", "(", "cls", ",", "'__test__'", ",", "None", ")", "if", "declared", "is", "not", "None", ":", "wanted", "=", "declared", "else", ":", "wanted", "=", "(", "not", "cls", ".", "__name__", ".", "startswith", "(", "'_'", ")", "and", "(", "issubclass", "(", "cls", ",", "unittest", ".", "TestCase", ")", "or", "self", ".", "matches", "(", "cls", ".", "__name__", ")", ")", ")", "plug_wants", "=", "self", ".", "plugins", ".", "wantClass", "(", "cls", ")", "if", "plug_wants", "is", "not", "None", ":", "log", ".", "debug", "(", "\"Plugin setting selection of %s to %s\"", ",", "cls", ",", "plug_wants", ")", "wanted", "=", "plug_wants", "log", ".", "debug", "(", "\"wantClass %s? %s\"", ",", "cls", ",", "wanted", ")", "return", "wanted" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Selector.wantDirectory
Is the directory a wanted test directory? All package directories match, so long as they do not match exclude. All other directories must match test requirements.
environment/lib/python2.7/site-packages/nose/selector.py
def wantDirectory(self, dirname): """Is the directory a wanted test directory? All package directories match, so long as they do not match exclude. All other directories must match test requirements. """ tail = op_basename(dirname) if ispackage(dirname): wanted = (not self.exclude or not filter(None, [exc.search(tail) for exc in self.exclude] )) else: wanted = (self.matches(tail) or (self.config.srcDirs and tail in self.config.srcDirs)) plug_wants = self.plugins.wantDirectory(dirname) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", dirname, plug_wants) wanted = plug_wants log.debug("wantDirectory %s? %s", dirname, wanted) return wanted
def wantDirectory(self, dirname): """Is the directory a wanted test directory? All package directories match, so long as they do not match exclude. All other directories must match test requirements. """ tail = op_basename(dirname) if ispackage(dirname): wanted = (not self.exclude or not filter(None, [exc.search(tail) for exc in self.exclude] )) else: wanted = (self.matches(tail) or (self.config.srcDirs and tail in self.config.srcDirs)) plug_wants = self.plugins.wantDirectory(dirname) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", dirname, plug_wants) wanted = plug_wants log.debug("wantDirectory %s? %s", dirname, wanted) return wanted
[ "Is", "the", "directory", "a", "wanted", "test", "directory?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/selector.py#L83-L105
[ "def", "wantDirectory", "(", "self", ",", "dirname", ")", ":", "tail", "=", "op_basename", "(", "dirname", ")", "if", "ispackage", "(", "dirname", ")", ":", "wanted", "=", "(", "not", "self", ".", "exclude", "or", "not", "filter", "(", "None", ",", "[", "exc", ".", "search", "(", "tail", ")", "for", "exc", "in", "self", ".", "exclude", "]", ")", ")", "else", ":", "wanted", "=", "(", "self", ".", "matches", "(", "tail", ")", "or", "(", "self", ".", "config", ".", "srcDirs", "and", "tail", "in", "self", ".", "config", ".", "srcDirs", ")", ")", "plug_wants", "=", "self", ".", "plugins", ".", "wantDirectory", "(", "dirname", ")", "if", "plug_wants", "is", "not", "None", ":", "log", ".", "debug", "(", "\"Plugin setting selection of %s to %s\"", ",", "dirname", ",", "plug_wants", ")", "wanted", "=", "plug_wants", "log", ".", "debug", "(", "\"wantDirectory %s? %s\"", ",", "dirname", ",", "wanted", ")", "return", "wanted" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Selector.wantFile
Is the file a wanted test file? The file must be a python source file and match testMatch or include, and not match exclude. Files that match ignore are *never* wanted, regardless of plugin, testMatch, include or exclude settings.
environment/lib/python2.7/site-packages/nose/selector.py
def wantFile(self, file): """Is the file a wanted test file? The file must be a python source file and match testMatch or include, and not match exclude. Files that match ignore are *never* wanted, regardless of plugin, testMatch, include or exclude settings. """ # never, ever load files that match anything in ignore # (.* _* and *setup*.py by default) base = op_basename(file) ignore_matches = [ ignore_this for ignore_this in self.ignoreFiles if ignore_this.search(base) ] if ignore_matches: log.debug('%s matches ignoreFiles pattern; skipped', base) return False if not self.config.includeExe and os.access(file, os.X_OK): log.info('%s is executable; skipped', file) return False dummy, ext = op_splitext(base) pysrc = ext == '.py' wanted = pysrc and self.matches(base) plug_wants = self.plugins.wantFile(file) if plug_wants is not None: log.debug("plugin setting want %s to %s", file, plug_wants) wanted = plug_wants log.debug("wantFile %s? %s", file, wanted) return wanted
def wantFile(self, file): """Is the file a wanted test file? The file must be a python source file and match testMatch or include, and not match exclude. Files that match ignore are *never* wanted, regardless of plugin, testMatch, include or exclude settings. """ # never, ever load files that match anything in ignore # (.* _* and *setup*.py by default) base = op_basename(file) ignore_matches = [ ignore_this for ignore_this in self.ignoreFiles if ignore_this.search(base) ] if ignore_matches: log.debug('%s matches ignoreFiles pattern; skipped', base) return False if not self.config.includeExe and os.access(file, os.X_OK): log.info('%s is executable; skipped', file) return False dummy, ext = op_splitext(base) pysrc = ext == '.py' wanted = pysrc and self.matches(base) plug_wants = self.plugins.wantFile(file) if plug_wants is not None: log.debug("plugin setting want %s to %s", file, plug_wants) wanted = plug_wants log.debug("wantFile %s? %s", file, wanted) return wanted
[ "Is", "the", "file", "a", "wanted", "test", "file?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/selector.py#L107-L135
[ "def", "wantFile", "(", "self", ",", "file", ")", ":", "# never, ever load files that match anything in ignore", "# (.* _* and *setup*.py by default)", "base", "=", "op_basename", "(", "file", ")", "ignore_matches", "=", "[", "ignore_this", "for", "ignore_this", "in", "self", ".", "ignoreFiles", "if", "ignore_this", ".", "search", "(", "base", ")", "]", "if", "ignore_matches", ":", "log", ".", "debug", "(", "'%s matches ignoreFiles pattern; skipped'", ",", "base", ")", "return", "False", "if", "not", "self", ".", "config", ".", "includeExe", "and", "os", ".", "access", "(", "file", ",", "os", ".", "X_OK", ")", ":", "log", ".", "info", "(", "'%s is executable; skipped'", ",", "file", ")", "return", "False", "dummy", ",", "ext", "=", "op_splitext", "(", "base", ")", "pysrc", "=", "ext", "==", "'.py'", "wanted", "=", "pysrc", "and", "self", ".", "matches", "(", "base", ")", "plug_wants", "=", "self", ".", "plugins", ".", "wantFile", "(", "file", ")", "if", "plug_wants", "is", "not", "None", ":", "log", ".", "debug", "(", "\"plugin setting want %s to %s\"", ",", "file", ",", "plug_wants", ")", "wanted", "=", "plug_wants", "log", ".", "debug", "(", "\"wantFile %s? %s\"", ",", "file", ",", "wanted", ")", "return", "wanted" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Selector.wantFunction
Is the function a test function?
environment/lib/python2.7/site-packages/nose/selector.py
def wantFunction(self, function): """Is the function a test function? """ try: if hasattr(function, 'compat_func_name'): funcname = function.compat_func_name else: funcname = function.__name__ except AttributeError: # not a function return False declared = getattr(function, '__test__', None) if declared is not None: wanted = declared else: wanted = not funcname.startswith('_') and self.matches(funcname) plug_wants = self.plugins.wantFunction(function) if plug_wants is not None: wanted = plug_wants log.debug("wantFunction %s? %s", function, wanted) return wanted
def wantFunction(self, function): """Is the function a test function? """ try: if hasattr(function, 'compat_func_name'): funcname = function.compat_func_name else: funcname = function.__name__ except AttributeError: # not a function return False declared = getattr(function, '__test__', None) if declared is not None: wanted = declared else: wanted = not funcname.startswith('_') and self.matches(funcname) plug_wants = self.plugins.wantFunction(function) if plug_wants is not None: wanted = plug_wants log.debug("wantFunction %s? %s", function, wanted) return wanted
[ "Is", "the", "function", "a", "test", "function?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/selector.py#L137-L157
[ "def", "wantFunction", "(", "self", ",", "function", ")", ":", "try", ":", "if", "hasattr", "(", "function", ",", "'compat_func_name'", ")", ":", "funcname", "=", "function", ".", "compat_func_name", "else", ":", "funcname", "=", "function", ".", "__name__", "except", "AttributeError", ":", "# not a function", "return", "False", "declared", "=", "getattr", "(", "function", ",", "'__test__'", ",", "None", ")", "if", "declared", "is", "not", "None", ":", "wanted", "=", "declared", "else", ":", "wanted", "=", "not", "funcname", ".", "startswith", "(", "'_'", ")", "and", "self", ".", "matches", "(", "funcname", ")", "plug_wants", "=", "self", ".", "plugins", ".", "wantFunction", "(", "function", ")", "if", "plug_wants", "is", "not", "None", ":", "wanted", "=", "plug_wants", "log", ".", "debug", "(", "\"wantFunction %s? %s\"", ",", "function", ",", "wanted", ")", "return", "wanted" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Selector.wantMethod
Is the method a test method?
environment/lib/python2.7/site-packages/nose/selector.py
def wantMethod(self, method): """Is the method a test method? """ try: method_name = method.__name__ except AttributeError: # not a method return False if method_name.startswith('_'): # never collect 'private' methods return False declared = getattr(method, '__test__', None) if declared is not None: wanted = declared else: wanted = self.matches(method_name) plug_wants = self.plugins.wantMethod(method) if plug_wants is not None: wanted = plug_wants log.debug("wantMethod %s? %s", method, wanted) return wanted
def wantMethod(self, method): """Is the method a test method? """ try: method_name = method.__name__ except AttributeError: # not a method return False if method_name.startswith('_'): # never collect 'private' methods return False declared = getattr(method, '__test__', None) if declared is not None: wanted = declared else: wanted = self.matches(method_name) plug_wants = self.plugins.wantMethod(method) if plug_wants is not None: wanted = plug_wants log.debug("wantMethod %s? %s", method, wanted) return wanted
[ "Is", "the", "method", "a", "test", "method?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/selector.py#L159-L179
[ "def", "wantMethod", "(", "self", ",", "method", ")", ":", "try", ":", "method_name", "=", "method", ".", "__name__", "except", "AttributeError", ":", "# not a method", "return", "False", "if", "method_name", ".", "startswith", "(", "'_'", ")", ":", "# never collect 'private' methods", "return", "False", "declared", "=", "getattr", "(", "method", ",", "'__test__'", ",", "None", ")", "if", "declared", "is", "not", "None", ":", "wanted", "=", "declared", "else", ":", "wanted", "=", "self", ".", "matches", "(", "method_name", ")", "plug_wants", "=", "self", ".", "plugins", ".", "wantMethod", "(", "method", ")", "if", "plug_wants", "is", "not", "None", ":", "wanted", "=", "plug_wants", "log", ".", "debug", "(", "\"wantMethod %s? %s\"", ",", "method", ",", "wanted", ")", "return", "wanted" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Selector.wantModule
Is the module a test module? The tail of the module name must match test requirements. One exception: we always want __main__.
environment/lib/python2.7/site-packages/nose/selector.py
def wantModule(self, module): """Is the module a test module? The tail of the module name must match test requirements. One exception: we always want __main__. """ declared = getattr(module, '__test__', None) if declared is not None: wanted = declared else: wanted = self.matches(module.__name__.split('.')[-1]) \ or module.__name__ == '__main__' plug_wants = self.plugins.wantModule(module) if plug_wants is not None: wanted = plug_wants log.debug("wantModule %s? %s", module, wanted) return wanted
def wantModule(self, module): """Is the module a test module? The tail of the module name must match test requirements. One exception: we always want __main__. """ declared = getattr(module, '__test__', None) if declared is not None: wanted = declared else: wanted = self.matches(module.__name__.split('.')[-1]) \ or module.__name__ == '__main__' plug_wants = self.plugins.wantModule(module) if plug_wants is not None: wanted = plug_wants log.debug("wantModule %s? %s", module, wanted) return wanted
[ "Is", "the", "module", "a", "test", "module?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/selector.py#L181-L197
[ "def", "wantModule", "(", "self", ",", "module", ")", ":", "declared", "=", "getattr", "(", "module", ",", "'__test__'", ",", "None", ")", "if", "declared", "is", "not", "None", ":", "wanted", "=", "declared", "else", ":", "wanted", "=", "self", ".", "matches", "(", "module", ".", "__name__", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ")", "or", "module", ".", "__name__", "==", "'__main__'", "plug_wants", "=", "self", ".", "plugins", ".", "wantModule", "(", "module", ")", "if", "plug_wants", "is", "not", "None", ":", "wanted", "=", "plug_wants", "log", ".", "debug", "(", "\"wantModule %s? %s\"", ",", "module", ",", "wanted", ")", "return", "wanted" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
decorate_fn_with_doc
Make new_fn have old_fn's doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.
environment/lib/python2.7/site-packages/IPython/core/debugger.py
def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): """Make new_fn have old_fn's doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.""" def wrapper(*args, **kw): return new_fn(*args, **kw) if old_fn.__doc__: wrapper.__doc__ = old_fn.__doc__ + additional_text return wrapper
def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): """Make new_fn have old_fn's doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.""" def wrapper(*args, **kw): return new_fn(*args, **kw) if old_fn.__doc__: wrapper.__doc__ = old_fn.__doc__ + additional_text return wrapper
[ "Make", "new_fn", "have", "old_fn", "s", "doc", "string", ".", "This", "is", "particularly", "useful", "for", "the", "do_", "...", "commands", "that", "hook", "into", "the", "help", "system", ".", "Adapted", "from", "from", "a", "comp", ".", "lang", ".", "python", "posting", "by", "Duncan", "Booth", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/debugger.py#L153-L162
[ "def", "decorate_fn_with_doc", "(", "new_fn", ",", "old_fn", ",", "additional_text", "=", "\"\"", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "new_fn", "(", "*", "args", ",", "*", "*", "kw", ")", "if", "old_fn", ".", "__doc__", ":", "wrapper", ".", "__doc__", "=", "old_fn", ".", "__doc__", "+", "additional_text", "return", "wrapper" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
_file_lines
Return the contents of a named file as a list of lines. This function never raises an IOError exception: if the file can't be read, it simply returns an empty list.
environment/lib/python2.7/site-packages/IPython/core/debugger.py
def _file_lines(fname): """Return the contents of a named file as a list of lines. This function never raises an IOError exception: if the file can't be read, it simply returns an empty list.""" try: outfile = open(fname) except IOError: return [] else: out = outfile.readlines() outfile.close() return out
def _file_lines(fname): """Return the contents of a named file as a list of lines. This function never raises an IOError exception: if the file can't be read, it simply returns an empty list.""" try: outfile = open(fname) except IOError: return [] else: out = outfile.readlines() outfile.close() return out
[ "Return", "the", "contents", "of", "a", "named", "file", "as", "a", "list", "of", "lines", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/debugger.py#L165-L178
[ "def", "_file_lines", "(", "fname", ")", ":", "try", ":", "outfile", "=", "open", "(", "fname", ")", "except", "IOError", ":", "return", "[", "]", "else", ":", "out", "=", "outfile", ".", "readlines", "(", ")", "outfile", ".", "close", "(", ")", "return", "out" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Pdb.list_command_pydb
List command to use if we have a newer pydb installed
environment/lib/python2.7/site-packages/IPython/core/debugger.py
def list_command_pydb(self, arg): """List command to use if we have a newer pydb installed""" filename, first, last = OldPdb.parse_list_cmd(self, arg) if filename is not None: self.print_list_lines(filename, first, last)
def list_command_pydb(self, arg): """List command to use if we have a newer pydb installed""" filename, first, last = OldPdb.parse_list_cmd(self, arg) if filename is not None: self.print_list_lines(filename, first, last)
[ "List", "command", "to", "use", "if", "we", "have", "a", "newer", "pydb", "installed" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/debugger.py#L409-L413
[ "def", "list_command_pydb", "(", "self", ",", "arg", ")", ":", "filename", ",", "first", ",", "last", "=", "OldPdb", ".", "parse_list_cmd", "(", "self", ",", "arg", ")", "if", "filename", "is", "not", "None", ":", "self", ".", "print_list_lines", "(", "filename", ",", "first", ",", "last", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e