def wait(self, readfds, writefds, timeout):

logger.debug("<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>for fd in readfds:<EOL><INDENT>self.rwait[fd].add(self._current)<EOL><DEDENT>for fd in writefds:<EOL><INDENT>self.twait[fd].add(self._current)<EOL><DEDENT>if timeout is not None:<EOL><INDENT>self.timers[self._current] = self.clocks + timeout<EOL><DEDENT>procid = self._current<EOL>next_index = (self.running.index(procid) + <NUM_LIT:1>) % len(self.running)<EOL>self._current = self.running[next_index]<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>self.running.remove(procid)<EOL>if self._current not in self.running:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self._current = None<EOL>self.check_timers()<EOL><DEDENT>

Wait for file descriptors or timeout.
            Adds the current process in the correspondent waiting list and
            yield the cpu to another running process.


logger.debug(f"<STR_LIT>")<EOL>for wait_list in self.rwait:<EOL><INDENT>if procid in wait_list:<EOL><INDENT>wait_list.remove(procid)<EOL><DEDENT><DEDENT>for wait_list in self.twait:<EOL><INDENT>if procid in wait_list:<EOL><INDENT>wait_list.remove(procid)<EOL><DEDENT><DEDENT>self.timers[procid] = None<EOL>self.running.append(procid)<EOL>if self._current is None:<EOL><INDENT>self._current = procid<EOL><DEDENT>

Remove procid from waitlists and reestablish it in the running list


if fd in [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>]:<EOL><INDENT>return None<EOL><DEDENT>if fd % <NUM_LIT:2>:<EOL><INDENT>return fd + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return fd - <NUM_LIT:1><EOL><DEDENT>

File descriptors are connected to each other like pipes, except
        for 0, 1, and 2. If you write to FD(N) for N >=3, then that comes
        out from FD(N+1) and vice-versa


connections = self.connections<EOL>if connections(fd) and self.twait[connections(fd)]:<EOL><INDENT>procid = random.sample(self.twait[connections(fd)], <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>self.awake(procid)<EOL><DEDENT>

Awake one process waiting to receive data on fd


connection = self.connections(fd)<EOL>if connection is None or connection >= len(self.rwait):<EOL><INDENT>return<EOL><DEDENT>procs = self.rwait[connection]<EOL>if procs:<EOL><INDENT>procid = random.sample(procs, <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>self.awake(procid)<EOL><DEDENT>

Awake one process waiting to transmit data on fd


if self._current is None:<EOL><INDENT>advance = min([self.clocks] + [x for x in self.timers if x is not None]) + <NUM_LIT:1><EOL>logger.debug(f"<STR_LIT>")<EOL>self.clocks = advance<EOL><DEDENT>for procid in range(len(self.timers)):<EOL><INDENT>if self.timers[procid] is not None:<EOL><INDENT>if self.clocks > self.timers[procid]:<EOL><INDENT>self.procs[procid].PC += self.procs[procid].instruction.size<EOL>self.awake(procid)<EOL><DEDENT><DEDENT><DEDENT>


try:<EOL><INDENT>self.current.execute()<EOL>self.clocks += <NUM_LIT:1><EOL>if self.clocks % <NUM_LIT> == <NUM_LIT:0>:<EOL><INDENT>self.check_timers()<EOL>self.sched()<EOL><DEDENT><DEDENT>except (Interruption, Syscall) as e:<EOL><INDENT>try:<EOL><INDENT>self.syscall()<EOL>if hasattr(e, '<STR_LIT>'):<EOL><INDENT>e.on_handled()<EOL><DEDENT><DEDENT>except RestartSyscall:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return True<EOL>

Execute one cpu instruction in the current thread (only one supported).
:rtype: bool
:return: C{True}

:todo: This is where we could implement a simple schedule.


try:<EOL><INDENT>stat = self._get_fd(fd).stat()<EOL><DEDENT>except FdError as e:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return -e.err<EOL><DEDENT>def add(width, val):<EOL><INDENT>fformat = {<NUM_LIT:2>: '<STR_LIT:H>', <NUM_LIT:4>: '<STR_LIT:L>', <NUM_LIT:8>: '<STR_LIT>'}[width]<EOL>return struct.pack('<STR_LIT:<>' + fformat, val)<EOL><DEDENT>def to_timespec(width, ts):<EOL><INDENT>'<STR_LIT>'<EOL>return add(width, int(ts)) + add(width, int(ts % <NUM_LIT:1> * <NUM_LIT>))<EOL><DEDENT>nw = self.current.address_bit_size // <NUM_LIT:8><EOL>bufstat = add(nw, stat.st_dev)     <EOL>bufstat += add(nw, stat.st_ino)     <EOL>bufstat += add(nw, stat.st_nlink)   <EOL>bufstat += add(<NUM_LIT:4>, stat.st_mode)     <EOL>bufstat += add(<NUM_LIT:4>, stat.st_uid)      <EOL>bufstat += add(<NUM_LIT:4>, stat.st_gid)      <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)                <EOL>bufstat += add(nw, stat.st_rdev)    <EOL>bufstat += add(nw, stat.st_size)    <EOL>bufstat += add(nw, stat.st_blksize)  <EOL>bufstat += add(nw, stat.st_blocks)  <EOL>bufstat += to_timespec(nw, stat.st_atime)  <EOL>bufstat += to_timespec(nw, stat.st_mtime)  <EOL>bufstat += to_timespec(nw, stat.st_ctime)  <EOL>self.current.write_bytes(buf, bufstat)<EOL>return <NUM_LIT:0><EOL>

Determines information about a file based on its file descriptor.
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success, EBADF when called with bad fd


try:<EOL><INDENT>stat = self._get_fd(fd).stat()<EOL><DEDENT>except FdError as e:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return -e.err<EOL><DEDENT>def add(width, val):<EOL><INDENT>fformat = {<NUM_LIT:2>: '<STR_LIT:H>', <NUM_LIT:4>: '<STR_LIT:L>', <NUM_LIT:8>: '<STR_LIT>'}[width]<EOL>return struct.pack('<STR_LIT:<>' + fformat, val)<EOL><DEDENT>def to_timespec(ts):<EOL><INDENT>return struct.pack('<STR_LIT>', int(ts), int(ts % <NUM_LIT:1> * <NUM_LIT>))<EOL><DEDENT>bufstat = add(<NUM_LIT:8>, stat.st_dev)    <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)              <EOL>bufstat += add(<NUM_LIT:4>, stat.st_ino)    <EOL>bufstat += add(<NUM_LIT:4>, stat.st_mode)   <EOL>bufstat += add(<NUM_LIT:4>, stat.st_nlink)  <EOL>bufstat += add(<NUM_LIT:4>, stat.st_uid)    <EOL>bufstat += add(<NUM_LIT:4>, stat.st_gid)    <EOL>bufstat += add(<NUM_LIT:4>, stat.st_rdev)   <EOL>bufstat += add(<NUM_LIT:4>, stat.st_size)   <EOL>bufstat += add(<NUM_LIT:4>, stat.st_blksize)  <EOL>bufstat += add(<NUM_LIT:4>, stat.st_blocks)  <EOL>bufstat += to_timespec(stat.st_atime)  <EOL>bufstat += to_timespec(stat.st_mtime)  <EOL>bufstat += to_timespec(stat.st_ctime)  <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)              <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)              <EOL>self.current.write_bytes(buf, bufstat)<EOL>return <NUM_LIT:0><EOL>


try:<EOL><INDENT>stat = self._get_fd(fd).stat()<EOL><DEDENT>except FdError as e:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return -e.err<EOL><DEDENT>def add(width, val):<EOL><INDENT>fformat = {<NUM_LIT:2>: '<STR_LIT:H>', <NUM_LIT:4>: '<STR_LIT:L>', <NUM_LIT:8>: '<STR_LIT>'}[width]<EOL>return struct.pack('<STR_LIT:<>' + fformat, val)<EOL><DEDENT>def to_timespec(ts):<EOL><INDENT>return struct.pack('<STR_LIT>', int(ts), int(ts % <NUM_LIT:1> * <NUM_LIT>))<EOL><DEDENT>bufstat = add(<NUM_LIT:8>, stat.st_dev)        <EOL>bufstat += add(<NUM_LIT:8>, stat.st_ino)        <EOL>bufstat += add(<NUM_LIT:4>, stat.st_mode)       <EOL>bufstat += add(<NUM_LIT:4>, stat.st_nlink)      <EOL>bufstat += add(<NUM_LIT:4>, stat.st_uid)        <EOL>bufstat += add(<NUM_LIT:4>, stat.st_gid)        <EOL>bufstat += add(<NUM_LIT:8>, stat.st_rdev)       <EOL>bufstat += add(<NUM_LIT:8>, <NUM_LIT:0>)                  <EOL>bufstat += add(<NUM_LIT:8>, stat.st_size)       <EOL>bufstat += add(<NUM_LIT:4>, stat.st_blksize)    <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)                  <EOL>bufstat += add(<NUM_LIT:8>, stat.st_blocks)     <EOL>bufstat += to_timespec(stat.st_atime)  <EOL>bufstat += to_timespec(stat.st_mtime)  <EOL>bufstat += to_timespec(stat.st_ctime)  <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)                   <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)                   <EOL>self.current.write_bytes(buf, bufstat)<EOL>return <NUM_LIT:0><EOL>

Determines information about a file based on its file descriptor (for Linux 64 bits).
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success, EBADF when called with bad fd
:todo: Fix device number.


return self.sys_stat64(fd, buf)<EOL>


return self._stat(path, buf, True)<EOL>

Determines information about a file based on its filename (for Linux 64 bits).
:rtype: int
:param path: the pathname of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.


load_segs = [x for x in interp.iter_segments() if x.header.p_type == '<STR_LIT>']<EOL>last = load_segs[-<NUM_LIT:1>]<EOL>return last.header.p_vaddr + last.header.p_memsz<EOL>

Compute total load size of interpreter.

:param ELFFile interp: interpreter ELF .so
:return: total load size of interpreter, not aligned
:rtype: int


self.symbolic_files.append(symbolic_file)<EOL>

Add a symbolic file. Each '+' in the file will be considered
as symbolic; other chars are concretized.
Symbolic files must have been defined before the call to `run()`.

:param str symbolic_file: the name of the symbolic file


offset = <NUM_LIT:0><EOL>symbolic_path = issymbolic(self.current.read_int(buf, <NUM_LIT:8>))<EOL>if symbolic_path:<EOL><INDENT>import tempfile<EOL>fd, path = tempfile.mkstemp()<EOL>with open(path, '<STR_LIT>') as f:<EOL><INDENT>f.write('<STR_LIT:+>' * <NUM_LIT:64>)<EOL><DEDENT>self.symbolic_files.append(path)<EOL>buf = self.current.memory.mmap(None, <NUM_LIT>, '<STR_LIT>', data_init=path)<EOL><DEDENT>rv = super().sys_open(buf, flags, mode)<EOL>if symbolic_path:<EOL><INDENT>self.current.memory.munmap(buf, <NUM_LIT>)<EOL><DEDENT>return rv<EOL>

A version of open(2) that includes a special case for a symbolic path.
When given a symbolic path, it will create a temporary file with
64 bytes of symbolic bytes as contents and return that instead.

:param buf: address of zero-terminated pathname
:param flags: file access bits
:param mode: file permission mode


def sys_openat(self, dirfd, buf, flags, mode):

if issymbolic(dirfd):<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self.constraints.add(dirfd >= <NUM_LIT:0>)<EOL>self.constraints.add(dirfd <= len(self.files))<EOL>raise ConcretizeArgument(self, <NUM_LIT:0>)<EOL><DEDENT>if issymbolic(buf):<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>raise ConcretizeArgument(self, <NUM_LIT:1>)<EOL><DEDENT>return super().sys_openat(dirfd, buf, flags, mode)<EOL>

A version of openat that includes a symbolic path and symbolic directory file descriptor

:param dirfd: directory file descriptor
:param buf: address of zero-terminated pathname
:param flags: file access bits
:param mode: file permission mode


def sys_getrandom(self, buf, size, flags):

if issymbolic(buf):<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>raise ConcretizeArgument(self, <NUM_LIT:0>)<EOL><DEDENT>if issymbolic(size):<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>raise ConcretizeArgument(self, <NUM_LIT:1>)<EOL><DEDENT>if issymbolic(flags):<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>raise ConcretizeArgument(self, <NUM_LIT:2>)<EOL><DEDENT>return super().sys_getrandom(buf, size, flags)<EOL>

The getrandom system call fills the buffer with random bytes of buflen.
The source of random (/dev/random or /dev/urandom) is decided based on the flags value.

:param buf: address of buffer to be filled with random bytes
:param size: number of random bytes
:param flags: source of random (/dev/random or /dev/urandom)
:return: number of bytes copied to buf


cpu.decode_instruction(cpu.PC)<EOL>emu = UnicornEmulator(cpu)<EOL>emu.emulate(cpu.instruction)<EOL>return emu<EOL>

Read the next instruction and emulate it with Unicorn


def __init__(self, prg, prompt='<STR_LIT>'):

self.prompt = prompt<EOL>subprocess.Popen.__init__(self, ['<STR_LIT>', prg], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)<EOL>


self.stdin.write(text)<EOL>self.stdin.flush()<EOL>str_buffer = '<STR_LIT>'<EOL>while not str_buffer.endswith(self.prompt):<EOL><INDENT>str_buffer += self.stdout.read(<NUM_LIT:1>)<EOL><DEDENT>return str_buffer<EOL>

Communicate with the child process without closing stdin.


self.prompt = prompt<EOL>subprocess.Popen.__init__(self, ['<STR_LIT>', prg], stdin=subprocess.PIPE, stdout=subprocess.PIPE , stderr=subprocess.STDOUT)<EOL>


equal = copy.copy(constraint)<EOL>assert len(equal.operands) == <NUM_LIT:2><EOL>ite, forcepc = equal.operands<EOL>assert isinstance(ite, BitVecITE) and isinstance(forcepc, BitVecConstant)<EOL>assert len(ite.operands) == <NUM_LIT:3><EOL>cond, iifpc, eelsepc = ite.operands<EOL>assert isinstance(iifpc, BitVecConstant) and isinstance(eelsepc, BitVecConstant)<EOL>equal._operands= (equal.operands[<NUM_LIT:0>], eelsepc if forcepc.value == iifpc.value else iifpc)<EOL>return equal<EOL>

flips a constraint (Equal)

(Equal (BitVecITE Cond IfC ElseC) IfC)
    ->
(Equal (BitVecITE Cond IfC ElseC) ElseC)


for i in range(<NUM_LIT:1>, <NUM_LIT:2>**len(lst)):<EOL><INDENT>yield [func(item) if (<NUM_LIT:1><<j)&i else item for (j, item) in enumerate(lst)]<EOL><DEDENT>

Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly
    possible that returned constraints can be unsat this does it blindly, without any attention to the constraints
    themselves

    Considering lst as a list of constraints, e.g.

      [ C1, C2, C3 ]

    we'd like to consider scenarios of all possible permutations of flipped constraints, excluding the original list.
    So we'd like to generate:

      [ func(C1),      C2 ,       C3 ],
      [      C1 , func(C2),       C3 ],
      [ func(C1), func(C2),       C3 ],
      [      C1 ,      C2 ,  func(C3)],
      .. etc

    This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the
    0th element (unmodified array).

    The code below yields lists of constraints permuted as above by treating list indeces as bitmasks from 1 to
     2**len(lst) and applying func to all the set bit offsets.


def make_chr(c):<EOL><INDENT>try:<EOL><INDENT>return chr(c)<EOL><DEDENT>except Exception:<EOL><INDENT>return c<EOL><DEDENT><DEDENT>newset = constraints_to_constraintset(constupl)<EOL>ret = '<STR_LIT>'<EOL>for data in datas:<EOL><INDENT>for c in data:<EOL><INDENT>ret += make_chr(solver.get_value(newset, c))<EOL><DEDENT><DEDENT>return ret<EOL>


m2 = Manticore.linux(prog, workspace_url='<STR_LIT>')<EOL>f = Follower(trace)<EOL>m2.verbosity(VERBOSITY)<EOL>m2.register_plugin(f)<EOL>def on_term_testcase(mcore, state, stateid, err):<EOL><INDENT>with m2.locked_context() as ctx:<EOL><INDENT>readdata = []<EOL>for name, fd, data in state.platform.syscall_trace:<EOL><INDENT>if name in ('<STR_LIT>', '<STR_LIT>') and fd == <NUM_LIT:0>:<EOL><INDENT>readdata.append(data)<EOL><DEDENT><DEDENT>ctx['<STR_LIT>'] = readdata<EOL>ctx['<STR_LIT>'] = list(state.constraints.constraints)<EOL><DEDENT><DEDENT>m2.subscribe('<STR_LIT>', on_term_testcase)<EOL>m2.run()<EOL>constraints = m2.context['<STR_LIT>']<EOL>datas = m2.context['<STR_LIT>']<EOL>return constraints, datas<EOL>

Execute a symbolic run that follows a concrete run; return constraints generated
and the stdin data produced


return any(eq(new, old) for old in olds)<EOL>

__contains__ operator using the `eq` function


return [new for new in newcons if not contains(new, oldcons)]<EOL>

return all constraints in newcons that aren't in oldcons


return solver.check(constraints_to_constraintset(cons))<EOL>


tv = TraceVisualizer(view, None)<EOL>if tv.workspace is None:<EOL><INDENT>tv.workspace = get_workspace()<EOL><DEDENT>tv.visualize()<EOL>

Given a Manticore trace file, highlight the basic blocks.


tv = TraceVisualizer(view, None, live=True)<EOL>if tv.workspace is None:<EOL><INDENT>tv.workspace = get_workspace()<EOL><DEDENT>tv.live_update = True<EOL>tv.visualize()<EOL>


if os.path.isfile(self.workspace):<EOL><INDENT>t = threading.Thread(target=self.highlight_from_file,<EOL>args=(self.workspace,))<EOL><DEDENT>elif os.path.isdir(self.workspace):<EOL><INDENT>t = threading.Thread(target=self.highlight_from_dir,<EOL>args=(self.workspace,))<EOL><DEDENT>t.start()<EOL>

Given a Manticore workspace, or trace file, highlight the basic blocks.


subproc.stdin.write(text)<EOL>subproc.stdin.flush()<EOL>return drain()<EOL>


differing = False<EOL>gdb_regs = gdb.getCanonicalRegisters()<EOL>for name in sorted(gdb_regs):<EOL><INDENT>vg = gdb_regs[name]<EOL>if name.endswith('<STR_LIT>'):<EOL><INDENT>name = '<STR_LIT>'<EOL><DEDENT>v = cpu.read_register(name.upper())<EOL>if should_print:<EOL><INDENT>logger.debug(f'<STR_LIT>')<EOL><DEDENT>if vg != v:<EOL><INDENT>if should_print:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>differing = True<EOL><DEDENT><DEDENT>if differing:<EOL><INDENT>logger.debug(qemu.correspond(None))<EOL><DEDENT>return differing<EOL>

Compare registers from a remote gdb session to current mcore.

:param manticore.core.cpu Cpu: Current cpu
:param bool should_print: Whether to print values to stdout
:return: Whether or not any differences were detected
:rtype: bool


global in_helper<EOL>if last_instruction.mnemonic.lower() == '<STR_LIT>':<EOL><INDENT>writes = state.cpu.memory.pop_record_writes()<EOL>if writes:<EOL><INDENT>logger.debug("<STR_LIT>", len(writes))<EOL><DEDENT>for addr, val in writes:<EOL><INDENT>gdb.setByte(addr, val[<NUM_LIT:0>])<EOL><DEDENT>gdb_r0 = gdb.getR('<STR_LIT>')<EOL>if gdb_r0 != state.cpu.R0:<EOL><INDENT>logger.debug(f"<STR_LIT>")<EOL><DEDENT>for reg in state.cpu.canonical_registers:<EOL><INDENT>if reg.endswith('<STR_LIT>') or reg in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>val = state.cpu.read_register(reg)<EOL>gdb.setR(reg, val)<EOL><DEDENT><DEDENT>if (state.cpu.PC >> <NUM_LIT:16>) == <NUM_LIT>:<EOL><INDENT>in_helper = True<EOL>return<EOL><DEDENT>if in_helper:<EOL><INDENT>for reg in state.cpu.canonical_registers:<EOL><INDENT>if reg.endswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>if reg == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>gdb.setR(reg, state.cpu.read_register(reg))<EOL><DEDENT>in_helper = False<EOL><DEDENT>if cmp_regs(state.cpu):<EOL><INDENT>cmp_regs(state.cpu, should_print=True)<EOL>state.abandon()<EOL><DEDENT>

Handle syscalls (import memory) and bail if we diverge


syscall = state.cpu.R7 <EOL>name = linux_syscalls.armv7[syscall]<EOL>logger.debug(f"<STR_LIT>")<EOL>try:<EOL><INDENT>if '<STR_LIT>' in name:<EOL><INDENT>returned = gdb.getR('<STR_LIT>')<EOL>logger.debug(f"<STR_LIT>")<EOL>state.cpu.write_register('<STR_LIT>', returned)<EOL><DEDENT>if '<STR_LIT>' in name:<EOL><INDENT>return<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>for reg in state.cpu.canonical_registers:<EOL><INDENT>print(f'<STR_LIT>')<EOL><DEDENT>raise<EOL><DEDENT>

Mirror some service calls in manticore. Happens after qemu executed a SVC
instruction, but before manticore did.


logger.debug(f"<STR_LIT>")<EOL>stack_bottom = min(state.cpu.SP, gdb.getR('<STR_LIT>'))<EOL>for address in range(stack_bottom, stack_top):<EOL><INDENT>b = state.cpu.read_int(address, <NUM_LIT:8>)<EOL>gdb.setByte(address, chr(b))<EOL><DEDENT>logger.debug("<STR_LIT>")<EOL>mcore_stdout = state.platform.files[<NUM_LIT:1>]<EOL>state.platform.files.append(mcore_stdout)<EOL>state.platform.files.append(mcore_stdout)<EOL>for gdb_reg in gdb.getCanonicalRegisters():<EOL><INDENT>if gdb_reg.endswith('<STR_LIT>'):<EOL><INDENT>mcore_reg = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>mcore_reg = gdb_reg.upper()<EOL><DEDENT>value = state.cpu.read_register(mcore_reg)<EOL>gdb.setR(gdb_reg, value)<EOL><DEDENT>

Synchronize the stack and register state (manticore->qemu)


with open(binary, '<STR_LIT:rb>') as f:<EOL><INDENT>elffile = ELFFile(f)<EOL>if elffile['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>

helper method for determining binary architecture

:param binary: str for binary to introspect.
:rtype bool: True for x86_64, False otherwise


def substr_after(string, delim):<EOL><INDENT>return string.partition(delim)[<NUM_LIT:2>]<EOL><DEDENT>with open(binary, '<STR_LIT:rb>') as f:<EOL><INDENT>elffile = ELFFile(f)<EOL>for section in elffile.iter_sections():<EOL><INDENT>if not isinstance(section, SymbolTableSection):<EOL><INDENT>continue<EOL><DEDENT>symbols = [sym.name for sym in section.iter_symbols() if sym]<EOL>return [substr_after(name, PREPEND_SYM) for name in symbols<EOL>if name.startswith(PREPEND_SYM)]<EOL><DEDENT><DEDENT>

helper method for getting all binary symbols with SANDSHREW_ prepended.
We do this in order to provide the symbols Manticore should hook on to
perform main analysis.

:param binary: str for binary to instrospect.
:rtype list: list of symbols from binary


if text:<EOL><INDENT>subproc.stdin.write(text)<EOL><DEDENT>subproc.stdin.flush()<EOL>return get_lines()<EOL>


plat = get_build_platform(); m = macosVersionString.match(plat)<EOL>if m is not None and sys.platform == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>plat = '<STR_LIT>' % ('<STR_LIT:.>'.join(_macosx_vers()[:<NUM_LIT:2>]), m.group(<NUM_LIT:3>))<EOL><DEDENT>except ValueError:<EOL><INDENT>pass    <EOL><DEDENT><DEDENT>return plat<EOL>

Return this platform's maximum compatible version.

    distutils.util.get_platform() normally reports the minimum version
    of Mac OS X that would be required to *use* extensions produced by
    distutils.  But what we want when checking compatibility is to know the
    version of Mac OS X that we are *running*.  To allow usage of packages that
    explicitly require a newer version of Mac OS X, we must also know the
    current version of the OS.

    If this condition occurs for any other platform with a version in its
    platform strings, this function should be extended accordingly.


_provider_factories[loader_type] = provider_factory<EOL>

Register `provider_factory` to make providers for `loader_type`

    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
    and `provider_factory` is a function that, passed a *module* object,
    returns an ``IResourceProvider`` for that module.


if isinstance(moduleOrReq,Requirement):<EOL><INDENT>return working_set.find(moduleOrReq) or require(str(moduleOrReq))[<NUM_LIT:0>]<EOL><DEDENT>try:<EOL><INDENT>module = sys.modules[moduleOrReq]<EOL><DEDENT>except KeyError:<EOL><INDENT>__import__(moduleOrReq)<EOL>module = sys.modules[moduleOrReq]<EOL><DEDENT>loader = getattr(module, '<STR_LIT>', None)<EOL>return _find_adapter(_provider_factories, loader)(module)<EOL>

Return an IResourceProvider for the named module or requirement


from distutils.util import get_platform<EOL>plat = get_platform()<EOL>if sys.platform == "<STR_LIT>" and not plat.startswith('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>version = _macosx_vers()<EOL>machine = os.uname()[<NUM_LIT:4>].replace("<STR_LIT:U+0020>", "<STR_LIT:_>")<EOL>return "<STR_LIT>" % (int(version[<NUM_LIT:0>]), int(version[<NUM_LIT:1>]),<EOL>_macosx_arch(machine))<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return plat<EOL>

Return this platform's string for platform-specific distributions

    XXX Currently this is the same as ``distutils.util.get_platform()``, but it
    needs some hacks for Linux and Mac OS X.


if provided is None or required is None or provided==required:<EOL><INDENT>return True     <EOL><DEDENT>reqMac = macosVersionString.match(required)<EOL>if reqMac:<EOL><INDENT>provMac = macosVersionString.match(provided)<EOL>if not provMac:<EOL><INDENT>provDarwin = darwinVersionString.match(provided)<EOL>if provDarwin:<EOL><INDENT>dversion = int(provDarwin.group(<NUM_LIT:1>))<EOL>macosversion = "<STR_LIT>" % (reqMac.group(<NUM_LIT:1>), reqMac.group(<NUM_LIT:2>))<EOL>if dversion == <NUM_LIT:7> and macosversion >= "<STR_LIT>" ordversion == <NUM_LIT:8> and macosversion >= "<STR_LIT>":<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False    <EOL><DEDENT>if provMac.group(<NUM_LIT:1>) != reqMac.group(<NUM_LIT:1>) orprovMac.group(<NUM_LIT:3>) != reqMac.group(<NUM_LIT:3>):<EOL><INDENT>return False<EOL><DEDENT>if int(provMac.group(<NUM_LIT:2>)) > int(reqMac.group(<NUM_LIT:2>)):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL><DEDENT>return False<EOL>

Can code for the `provided` platform run on the `required` platform?

    Returns true if either platform is ``None``, or the platforms are equal.

    XXX Needs compatibility checks for Linux and other unixy OSes.


ns = sys._getframe(<NUM_LIT:1>).f_globals<EOL>name = ns['<STR_LIT>']<EOL>ns.clear()<EOL>ns['<STR_LIT>'] = name<EOL>require(dist_spec)[<NUM_LIT:0>].run_script(script_name, ns)<EOL>

Locate distribution `dist_spec` and run its `script_name` script


if isinstance(dist,str): dist = Requirement.parse(dist)<EOL>if isinstance(dist,Requirement): dist = get_provider(dist)<EOL>if not isinstance(dist,Distribution):<EOL><INDENT>raise TypeError("<STR_LIT>", dist)<EOL><DEDENT>return dist<EOL>

Return a current distribution object for a Requirement or string


def load_entry_point(dist, group, name):

return get_distribution(dist).load_entry_point(group, name)<EOL>

Return `name` entry point of `group` for `dist` or raise ImportError


return get_distribution(dist).get_entry_map(group)<EOL>

Return the entry point map for `group`, or the full entry map


return get_distribution(dist).get_entry_info(group, name)<EOL>

Return the EntryPoint object for `group`+`name`, or ``None``


try:<EOL><INDENT>return os.environ['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>if os.name!='<STR_LIT>':<EOL><INDENT>return os.path.expanduser('<STR_LIT>')<EOL><DEDENT>app_data = '<STR_LIT>'   <EOL>app_homes = [<EOL>(('<STR_LIT>',), None),       <EOL>(('<STR_LIT>',), app_data),<EOL>(('<STR_LIT>','<STR_LIT>'), app_data),<EOL>(('<STR_LIT>',), app_data),<EOL>(('<STR_LIT>',), None),<EOL>(('<STR_LIT>',), app_data),    <EOL>]<EOL>for keys, subdir in app_homes:<EOL><INDENT>dirname = '<STR_LIT>'<EOL>for key in keys:<EOL><INDENT>if key in os.environ:<EOL><INDENT>dirname = os.path.join(dirname, os.environ[key])<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if subdir:<EOL><INDENT>dirname = os.path.join(dirname,subdir)<EOL><DEDENT>return os.path.join(dirname, '<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>

Determine the default cache location

    This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
    Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
    "Application Data" directory.  On all other systems, it's "~/.python-eggs".


return re.sub('<STR_LIT>', '<STR_LIT:->', name)<EOL>

Convert an arbitrary string to a standard distribution name

    Any runs of non-alphanumeric/. characters are replaced with a single '-'.


version = version.replace('<STR_LIT:U+0020>','<STR_LIT:.>')<EOL>return re.sub('<STR_LIT>', '<STR_LIT:->', version)<EOL>

Convert an arbitrary string to a standard version string

    Spaces become dots, and all other non-alphanumeric characters become
    dashes, with runs of multiple dashes condensed to a single dash.


return re.sub('<STR_LIT>', '<STR_LIT:_>', extra).lower()<EOL>

Convert an arbitrary string to a standard 'extra' name

    Any runs of non-alphanumeric characters are replaced with a single '_',
    and the result is always lowercased.


return name.replace('<STR_LIT:->','<STR_LIT:_>')<EOL>

Convert a project or version name to its filename-escaped form

    Any '-' characters are currently replaced with '_'.


try:<EOL><INDENT>importer = sys.path_importer_cache[path_item]<EOL><DEDENT>except KeyError:<EOL><INDENT>for hook in sys.path_hooks:<EOL><INDENT>try:<EOL><INDENT>importer = hook(path_item)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>importer = None<EOL><DEDENT><DEDENT>sys.path_importer_cache.setdefault(path_item,importer)<EOL>if importer is None:<EOL><INDENT>try:<EOL><INDENT>importer = ImpWrapper(path_item)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return importer<EOL>

Retrieve a PEP 302 "importer" for the given path item

    If there is no importer, this returns a wrapper around the builtin import
    machinery.  The returned importer is only cached if it was created by a
    path hook.


_distribution_finders[importer_type] = distribution_finder<EOL>

Register `distribution_finder` to find distributions in sys.path items

    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
    handler), and `distribution_finder` is a callable that, passed a path
    item and the importer instance, yields ``Distribution`` instances found on
    that path item.  See ``pkg_resources.find_on_path`` for an example.


importer = get_importer(path_item)<EOL>finder = _find_adapter(_distribution_finders, importer)<EOL>return finder(importer, path_item, only)<EOL>

Yield distributions accessible via `path_item`


global StringIO<EOL>try:<EOL><INDENT>from io import StringIO<EOL><DEDENT>except ImportError:<EOL><INDENT>from io import StringIO<EOL><DEDENT>return StringIO(*args,**kw)<EOL>

Thunk to load the real StringIO on demand


def find_on_path(importer, path_item, only=False):

path_item = _normalize_cached(path_item)<EOL>if os.path.isdir(path_item):<EOL><INDENT>if path_item.lower().endswith('<STR_LIT>'):<EOL><INDENT>yield Distribution.from_filename(<EOL>path_item, metadata=PathMetadata(<EOL>path_item, os.path.join(path_item,'<STR_LIT>')<EOL>)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>for entry in os.listdir(path_item):<EOL><INDENT>lower = entry.lower()<EOL>if lower.endswith('<STR_LIT>'):<EOL><INDENT>fullpath = os.path.join(path_item, entry)<EOL>if os.path.isdir(fullpath):<EOL><INDENT>metadata = PathMetadata(path_item, fullpath)<EOL><DEDENT>else:<EOL><INDENT>metadata = FileMetadata(fullpath)<EOL><DEDENT>yield Distribution.from_location(<EOL>path_item,entry,metadata,precedence=DEVELOP_DIST<EOL>)<EOL><DEDENT>elif not only and lower.endswith('<STR_LIT>'):<EOL><INDENT>for dist in find_distributions(os.path.join(path_item, entry)):<EOL><INDENT>yield dist<EOL><DEDENT><DEDENT>elif not only and lower.endswith('<STR_LIT>'):<EOL><INDENT>for line in file(os.path.join(path_item, entry)):<EOL><INDENT>if not line.strip(): continue<EOL>for item in find_distributions(os.path.join(path_item,line.rstrip())):<EOL><INDENT>yield item<EOL><DEDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>

Yield distributions accessible on a sys.path directory


_namespace_handlers[importer_type] = namespace_handler<EOL>

Register `namespace_handler` to declare namespace packages

    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
    handler), and `namespace_handler` is a callable like this::

        def namespace_handler(importer,path_entry,moduleName,module):
            # return a path_entry to use for child packages

    Namespace handlers are only called if the importer object has already
    agreed that it can handle the relevant path item, and they should only
    return a subpath if the module __path__ does not already contain an
    equivalent subpath.  For an example namespace handler, see
    ``pkg_resources.file_ns_handler``.


importer = get_importer(path_item)<EOL>if importer is None:<EOL><INDENT>return None<EOL><DEDENT>loader = importer.find_module(packageName)<EOL>if loader is None:<EOL><INDENT>return None<EOL><DEDENT>module = sys.modules.get(packageName)<EOL>if module is None:<EOL><INDENT>module = sys.modules[packageName] = new.module(packageName)<EOL>module.__path__ = []; _set_parent_ns(packageName)<EOL><DEDENT>elif not hasattr(module,'<STR_LIT>'):<EOL><INDENT>raise TypeError("<STR_LIT>", packageName)<EOL><DEDENT>handler = _find_adapter(_namespace_handlers, importer)<EOL>subpath = handler(importer,path_item,packageName,module)<EOL>if subpath is not None:<EOL><INDENT>path = module.__path__; path.append(subpath)<EOL>loader.load_module(packageName); module.__path__ = path<EOL><DEDENT>return subpath<EOL>

Ensure that named package includes a subpath of path_item (if needed)


imp.acquire_lock()<EOL>try:<EOL><INDENT>if packageName in _namespace_packages:<EOL><INDENT>return<EOL><DEDENT>path, parent = sys.path, None<EOL>if '<STR_LIT:.>' in packageName:<EOL><INDENT>parent = '<STR_LIT:.>'.join(packageName.split('<STR_LIT:.>')[:-<NUM_LIT:1>])<EOL>declare_namespace(parent)<EOL>__import__(parent)<EOL>try:<EOL><INDENT>path = sys.modules[parent].__path__<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise TypeError("<STR_LIT>", parent)<EOL><DEDENT><DEDENT>_namespace_packages.setdefault(parent,[]).append(packageName)<EOL>_namespace_packages.setdefault(packageName,[])<EOL>for path_item in path:<EOL><INDENT>_handle_ns(packageName, path_item)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>imp.release_lock()<EOL><DEDENT>

Declare that package 'packageName' is a namespace package


imp.acquire_lock()<EOL>try:<EOL><INDENT>for package in _namespace_packages.get(parent,()):<EOL><INDENT>subpath = _handle_ns(package, path_item)<EOL>if subpath: fixup_namespace_packages(subpath,package)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>imp.release_lock()<EOL><DEDENT>

Ensure that previously-declared namespace packages include path_item


def file_ns_handler(importer, path_item, packageName, module):

subpath = os.path.join(path_item, packageName.split('<STR_LIT:.>')[-<NUM_LIT:1>])<EOL>normalized = _normalize_cached(subpath)<EOL>for item in module.__path__:<EOL><INDENT>if _normalize_cached(item)==normalized:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return subpath<EOL><DEDENT>

Compute an ns-package subpath for a filesystem or zipfile importer


return os.path.normcase(os.path.realpath(filename))<EOL>

Normalize a file/dir name for comparison purposes


if isinstance(strs,str):<EOL><INDENT>for s in strs.splitlines():<EOL><INDENT>s = s.strip()<EOL>if s and not s.startswith('<STR_LIT:#>'):     <EOL><INDENT>yield s<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for ss in strs:<EOL><INDENT>for s in yield_lines(ss):<EOL><INDENT>yield s<EOL><DEDENT><DEDENT><DEDENT>

Yield non-empty/non-comment lines of a ``basestring`` or sequence


parts = []<EOL>for part in _parse_version_parts(s.lower()):<EOL><INDENT>if part.startswith('<STR_LIT:*>'):<EOL><INDENT>if part<'<STR_LIT>':   <EOL><INDENT>while parts and parts[-<NUM_LIT:1>]=='<STR_LIT>': parts.pop()<EOL><DEDENT>while parts and parts[-<NUM_LIT:1>]=='<STR_LIT>':<EOL><INDENT>parts.pop()<EOL><DEDENT><DEDENT>parts.append(part)<EOL><DEDENT>return tuple(parts)<EOL>

Convert a version string to a chronologically-sortable key

    This is a rough cross between distutils' StrictVersion and LooseVersion;
    if you give it versions that would work with StrictVersion, then it behaves
    the same; otherwise it acts like a slightly-smarter LooseVersion. It is
    *possible* to create pathological version coding schemes that will fool
    this parser, but they should be very rare in practice.

    The returned value will be a tuple of strings.  Numeric portions of the
    version are padded to 8 digits so they will compare numerically, but
    without relying on how numbers compare relative to strings.  Dots are
    dropped, but dashes are retained.  Trailing zeros between alpha segments
    or dashes are suppressed, so that e.g. "2.4.0" is considered the same as
    "2.4". Alphanumeric parts are lower-cased.

    The algorithm assumes that strings like "-" and any alpha string that
    alphabetically follows "final"  represents a "patch level".  So, "2.4-1"
    is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
    considered newer than "2.4-1", whic in turn is newer than "2.4".

    Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
    come before "final" alphabetically) are assumed to be pre-release versions,
    so that the version "2.4" is considered newer than "2.4a1".

    Finally, to handle miscellaneous cases, the strings "pre", "preview", and
    "rc" are treated as if they were "c", i.e. as though they were release
    candidates, and therefore are not as new as a version string that does not
    contain them.


<EOL>lines = iter(yield_lines(strs))<EOL>def scan_list(ITEM,TERMINATOR,line,p,groups,item_name):<EOL><INDENT>items = []<EOL>while not TERMINATOR(line,p):<EOL><INDENT>if CONTINUE(line,p):<EOL><INDENT>try:<EOL><INDENT>line = next(lines); p = <NUM_LIT:0><EOL><DEDENT>except StopIteration:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>match = ITEM(line,p)<EOL>if not match:<EOL><INDENT>raise ValueError("<STR_LIT>"+item_name+"<STR_LIT>",line,"<STR_LIT>",line[p:])<EOL><DEDENT>items.append(match.group(*groups))<EOL>p = match.end()<EOL>match = COMMA(line,p)<EOL>if match:<EOL><INDENT>p = match.end() <EOL><DEDENT>elif not TERMINATOR(line,p):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>",line,"<STR_LIT>",line[p:]<EOL>)<EOL><DEDENT><DEDENT>match = TERMINATOR(line,p)<EOL>if match: p = match.end()   <EOL>return line, p, items<EOL><DEDENT>for line in lines:<EOL><INDENT>match = DISTRO(line)<EOL>if not match:<EOL><INDENT>raise ValueError("<STR_LIT>", line)<EOL><DEDENT>project_name = match.group(<NUM_LIT:1>)<EOL>p = match.end()<EOL>extras = []<EOL>match = OBRACKET(line,p)<EOL>if match:<EOL><INDENT>p = match.end()<EOL>line, p, extras = scan_list(<EOL>DISTRO, CBRACKET, line, p, (<NUM_LIT:1>,), "<STR_LIT>"<EOL>)<EOL><DEDENT>line, p, specs = scan_list(VERSION,LINE_END,line,p,(<NUM_LIT:1>,<NUM_LIT:2>),"<STR_LIT>")<EOL>specs = [(op,safe_version(val)) for op,val in specs]<EOL>yield Requirement(project_name, specs, extras)<EOL><DEDENT>

Yield ``Requirement`` objects for each specification in `strs`

    `strs` must be an instance of ``basestring``, or a (possibly-nested)
    iterable thereof.


if not isinstance(cls,type):<EOL><INDENT>class cls(cls,object): pass<EOL>return cls.__mro__[<NUM_LIT:1>:]<EOL><DEDENT>return cls.__mro__<EOL>


for t in _get_mro(getattr(ob, '<STR_LIT>', type(ob))):<EOL><INDENT>if t in registry:<EOL><INDENT>return registry[t]<EOL><DEDENT><DEDENT>

Return an adapter factory for `ob` from `registry`


dirname = os.path.dirname(path)<EOL>if not os.path.isdir(dirname):<EOL><INDENT>os.makedirs(dirname)<EOL><DEDENT>

Ensure that the parent directory of `path` exists


section = None<EOL>content = []<EOL>for line in yield_lines(s):<EOL><INDENT>if line.startswith("<STR_LIT:[>"):<EOL><INDENT>if line.endswith("<STR_LIT:]>"):<EOL><INDENT>if section or content:<EOL><INDENT>yield section, content<EOL><DEDENT>section = line[<NUM_LIT:1>:-<NUM_LIT:1>].strip()<EOL>content = []<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>", line)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>content.append(line)<EOL><DEDENT><DEDENT>yield section, content<EOL>

Split a string or iterable thereof into (section,content) pairs

    Each ``section`` is a stripped version of the section header ("[section]")
    and each ``content`` is a list of stripped lines excluding blank lines and
    comment-only lines.  If there are any such lines before the first section
    header, they're returned in a first ``section`` of ``None``.


Does the package's distribution contain the named metadata?


Yield named metadata resource as list of non-blank non-comment lines

       Leading and trailing whitespace is stripped from each line, and lines
       with ``#`` as the first non-blank character are omitted.


Is the named metadata a directory?  (like ``os.path.isdir()``)


List of metadata names in the directory (like ``os.listdir()``)


Execute the named script in the supplied namespace dictionary


Return a true filesystem path for `resource_name`

        `manager` must be an ``IResourceManager``


Return a readable file-like object for `resource_name`

        `manager` must be an ``IResourceManager``


Return a string containing the contents of `resource_name`

        `manager` must be an ``IResourceManager``


Does the package contain the named resource?


Is the named resource a directory?  (like ``os.path.isdir()``)


List of resource names in the directory (like ``os.listdir()``)


self.entries = []<EOL>self.entry_keys = {}<EOL>self.by_key = {}<EOL>self.callbacks = []<EOL>if entries is None:<EOL><INDENT>entries = sys.path<EOL><DEDENT>for entry in entries:<EOL><INDENT>self.add_entry(entry)<EOL><DEDENT>

Create working set from list of path entries (default=sys.path)


self.entry_keys.setdefault(entry, [])<EOL>self.entries.append(entry)<EOL>for dist in find_distributions(entry, True):<EOL><INDENT>self.add(dist, entry, False)<EOL><DEDENT>

Add a path item to ``.entries``, finding any distributions on it

        ``find_distributions(entry,False)`` is used to find distributions
        corresponding to the path entry, and they are added.  `entry` is
        always appended to ``.entries``, even if it is already present.
        (This is because ``sys.path`` can contain the same value more than
        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
        equal ``sys.path``.)


return self.by_key.get(dist.key) == dist<EOL>

True if `dist` is the active distribution for its project


dist = self.by_key.get(req.key)<EOL>if dist is not None and dist not in req:<EOL><INDENT>raise VersionConflict(dist,req)     <EOL><DEDENT>else:<EOL><INDENT>return dist<EOL><DEDENT>

Find a distribution matching requirement `req`

        If there is an active distribution for the requested project, this
        returns it as long as it meets the version requirement specified by
        `req`.  But, if there is an active distribution for the project and it
        does *not* meet the `req` requirement, ``VersionConflict`` is raised.
        If there is no active distribution for the requested project, ``None``
        is returned.


def iter_entry_points(self, group, name=None):

for dist in self:<EOL><INDENT>entries = dist.get_entry_map(group)<EOL>if name is None:<EOL><INDENT>for ep in list(entries.values()):<EOL><INDENT>yield ep<EOL><DEDENT><DEDENT>elif name in entries:<EOL><INDENT>yield entries[name]<EOL><DEDENT><DEDENT>

Yield entry point objects from `group` matching `name`

        If `name` is None, yields all entry points in `group` from all
        distributions in the working set, otherwise only ones matching
        both `group` and `name` are yielded (in distribution order).


def run_script(self, requires, script_name):

ns = sys._getframe(<NUM_LIT:1>).f_globals<EOL>name = ns['<STR_LIT>']<EOL>ns.clear()<EOL>ns['<STR_LIT>'] = name<EOL>self.require(requires)[<NUM_LIT:0>].run_script(script_name, ns)<EOL>

Locate distribution for `requires` and run `script_name` script


seen = {}<EOL>for item in self.entries:<EOL><INDENT>for key in self.entry_keys[item]:<EOL><INDENT>if key not in seen:<EOL><INDENT>seen[key]=<NUM_LIT:1><EOL>yield self.by_key[key]<EOL><DEDENT><DEDENT><DEDENT>

Yield distributions for non-duplicate projects in the working set

        The yield order is the order in which the items' path entries were
        added to the working set.


def add(self, dist, entry=None, insert=True):

if insert:<EOL><INDENT>dist.insert_on(self.entries, entry)<EOL><DEDENT>if entry is None:<EOL><INDENT>entry = dist.location<EOL><DEDENT>keys = self.entry_keys.setdefault(entry,[])<EOL>keys2 = self.entry_keys.setdefault(dist.location,[])<EOL>if dist.key in self.by_key:<EOL><INDENT>return      <EOL><DEDENT>self.by_key[dist.key] = dist<EOL>if dist.key not in keys:<EOL><INDENT>keys.append(dist.key)<EOL><DEDENT>if dist.key not in keys2:<EOL><INDENT>keys2.append(dist.key)<EOL><DEDENT>self._added_new(dist)<EOL>

Add `dist` to working set, associated with `entry`

        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
        On exit from this routine, `entry` is added to the end of the working
        set's ``.entries`` (if it wasn't already present).

        `dist` is only added to the working set if it's for a project that
        doesn't already have a distribution in the set.  If it's added, any
        callbacks registered with the ``subscribe()`` method will be called.


def resolve(self, requirements, env=None, installer=None):

requirements = list(requirements)[::-<NUM_LIT:1>]  <EOL>processed = {}  <EOL>best = {}  <EOL>to_activate = []<EOL>while requirements:<EOL><INDENT>req = requirements.pop(<NUM_LIT:0>)   <EOL>if req in processed:<EOL><INDENT>continue<EOL><DEDENT>dist = best.get(req.key)<EOL>if dist is None:<EOL><INDENT>dist = self.by_key.get(req.key)<EOL>if dist is None:<EOL><INDENT>if env is None:<EOL><INDENT>env = Environment(self.entries)<EOL><DEDENT>dist = best[req.key] = env.best_match(req, self, installer)<EOL>if dist is None:<EOL><INDENT>raise DistributionNotFound(req)  <EOL><DEDENT><DEDENT>to_activate.append(dist)<EOL><DEDENT>if dist not in req:<EOL><INDENT>raise VersionConflict(dist,req) <EOL><DEDENT>requirements.extend(dist.requires(req.extras)[::-<NUM_LIT:1>])<EOL>processed[req] = True<EOL><DEDENT>return to_activate<EOL>

List all distributions needed to (recursively) meet `requirements`

        `requirements` must be a sequence of ``Requirement`` objects.  `env`,
        if supplied, should be an ``Environment`` instance.  If
        not supplied, it defaults to all distributions available within any
        entry or distribution in the working set.  `installer`, if supplied,
        will be invoked with each requirement that cannot be met by an
        already-installed distribution; it should return a ``Distribution`` or
        ``None``.


def find_plugins(self,<EOL>plugin_env, full_env=None, installer=None, fallback=True<EOL>):

plugin_projects = list(plugin_env)<EOL>plugin_projects.sort()  <EOL>error_info = {}<EOL>distributions = {}<EOL>if full_env is None:<EOL><INDENT>env = Environment(self.entries)<EOL>env += plugin_env<EOL><DEDENT>else:<EOL><INDENT>env = full_env + plugin_env<EOL><DEDENT>shadow_set = self.__class__([])<EOL>list(map(shadow_set.add, self))   <EOL>for project_name in plugin_projects:<EOL><INDENT>for dist in plugin_env[project_name]:<EOL><INDENT>req = [dist.as_requirement()]<EOL>try:<EOL><INDENT>resolvees = shadow_set.resolve(req, env, installer)<EOL><DEDENT>except ResolutionError as v:<EOL><INDENT>error_info[dist] = v    <EOL>if fallback:<EOL><INDENT>continue    <EOL><DEDENT>else:<EOL><INDENT>break       <EOL><DEDENT><DEDENT>else:<EOL><INDENT>list(map(shadow_set.add, resolvees))<EOL>distributions.update(dict.fromkeys(resolvees))<EOL>break<EOL><DEDENT><DEDENT><DEDENT>distributions = list(distributions)<EOL>distributions.sort()<EOL>return distributions, error_info<EOL>

Find all activatable distributions in `plugin_env`

        Example usage::

            distributions, errors = working_set.find_plugins(
                Environment(plugin_dirlist)
            )
            map(working_set.add, distributions)  # add plugins+libs to sys.path
            print "Couldn't load", errors        # display errors

        The `plugin_env` should be an ``Environment`` instance that contains
        only distributions that are in the project's "plugin directory" or
        directories. The `full_env`, if supplied, should be an ``Environment``
        contains all currently-available distributions.  If `full_env` is not
        supplied, one is created automatically from the ``WorkingSet`` this
        method is called on, which will typically mean that every directory on
        ``sys.path`` will be scanned for distributions.

        `installer` is a standard installer callback as used by the
        ``resolve()`` method. The `fallback` flag indicates whether we should
        attempt to resolve older versions of a plugin if the newest version
        cannot be resolved.

        This method returns a 2-tuple: (`distributions`, `error_info`), where
        `distributions` is a list of the distributions found in `plugin_env`
        that were loadable, along with any other distributions that are needed
        to resolve their dependencies.  `error_info` is a dictionary mapping
        unloadable plugin distributions to an exception instance describing the
        error that occurred. Usually this will be a ``DistributionNotFound`` or
        ``VersionConflict`` instance.


needed = self.resolve(parse_requirements(requirements))<EOL>for dist in needed:<EOL><INDENT>self.add(dist)<EOL><DEDENT>return needed<EOL>

Ensure that distributions matching `requirements` are activated

        `requirements` must be a string or a (possibly-nested) sequence
        thereof, specifying the distributions and versions required.  The
        return value is a sequence of the distributions that needed to be
        activated to fulfill the requirements; all relevant distributions are
        included, even if they were already activated in this working set.


if callback in self.callbacks:<EOL><INDENT>return<EOL><DEDENT>self.callbacks.append(callback)<EOL>for dist in self:<EOL><INDENT>callback(dist)<EOL><DEDENT>

Invoke `callback` for all distributions (including existing ones)


def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):

self._distmap = {}<EOL>self._cache = {}<EOL>self.platform = platform<EOL>self.python = python<EOL>self.scan(search_path)<EOL>

Snapshot distributions available on a search path

        Any distributions found on `search_path` are added to the environment.
        `search_path` should be a sequence of ``sys.path`` items.  If not
        supplied, ``sys.path`` is used.

        `platform` is an optional string specifying the name of the platform
        that platform-specific distributions must be compatible with.  If
        unspecified, it defaults to the current platform.  `python` is an
        optional string naming the desired version of Python (e.g. ``'2.4'``);
        it defaults to the current version.

        You may explicitly set `platform` (and/or `python`) to ``None`` if you
        wish to map *all* distributions, not just those compatible with the
        running platform or Python version.


return (self.python is None or dist.py_version is None<EOL>or dist.py_version==self.python)and compatible_platforms(dist.platform,self.platform)<EOL>

Is distribution `dist` acceptable for this environment?

        The distribution must match the platform and python version
        requirements specified when this environment was created, or False
        is returned.


self._distmap[dist.key].remove(dist)<EOL>


if search_path is None:<EOL><INDENT>search_path = sys.path<EOL><DEDENT>for item in search_path:<EOL><INDENT>for dist in find_distributions(item):<EOL><INDENT>self.add(dist)<EOL><DEDENT><DEDENT>

Scan `search_path` for distributions usable in this environment

        Any distributions found are added to the environment.
        `search_path` should be a sequence of ``sys.path`` items.  If not
        supplied, ``sys.path`` is used.  Only distributions conforming to
        the platform/python version defined at initialization are added.


try:<EOL><INDENT>return self._cache[project_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>project_name = project_name.lower()<EOL>if project_name not in self._distmap:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>if project_name not in self._cache:<EOL><INDENT>dists = self._cache[project_name] = self._distmap[project_name]<EOL>_sort_dists(dists)<EOL><DEDENT>return self._cache[project_name]<EOL>

Return a newest-to-oldest list of distributions for `project_name`


if self.can_add(dist) and dist.has_version():<EOL><INDENT>dists = self._distmap.setdefault(dist.key,[])<EOL>if dist not in dists:<EOL><INDENT>dists.append(dist)<EOL>if dist.key in self._cache:<EOL><INDENT>_sort_dists(self._cache[dist.key])<EOL><DEDENT><DEDENT><DEDENT>

Add `dist` if we ``can_add()`` it and it isn't already added


def best_match(self, req, working_set, installer=None):

dist = working_set.find(req)<EOL>if dist is not None:<EOL><INDENT>return dist<EOL><DEDENT>for dist in self[req.key]:<EOL><INDENT>if dist in req:<EOL><INDENT>return dist<EOL><DEDENT><DEDENT>return self.obtain(req, installer)<EOL>

Find distribution best matching `req` and usable on `working_set`

        This calls the ``find(req)`` method of the `working_set` to see if a
        suitable distribution is already active.  (This may raise
        ``VersionConflict`` if an unsuitable version of the project is already
        active in the specified `working_set`.)  If a suitable distribution
        isn't active, this method returns the newest distribution in the
        environment that meets the ``Requirement`` in `req`.  If no suitable
        distribution is found, and `installer` is supplied, then the result of
        calling the environment's ``obtain(req, installer)`` method will be
        returned.


def obtain(self, requirement, installer=None):

if installer is not None:<EOL><INDENT>return installer(requirement)<EOL><DEDENT>

Obtain a distribution matching `requirement` (e.g. via download)

        Obtain a distro that matches requirement (e.g. via download).  In the
        base ``Environment`` class, this routine just returns
        ``installer(requirement)``, unless `installer` is None, in which case
        None is returned instead.  This method is a hook that allows subclasses
        to attempt other ways of obtaining a distribution before falling back
        to the `installer` argument.


for key in list(self._distmap.keys()):<EOL><INDENT>if self[key]: yield key<EOL><DEDENT>

Yield the unique project names of the available distributions


if isinstance(other,Distribution):<EOL><INDENT>self.add(other)<EOL><DEDENT>elif isinstance(other,Environment):<EOL><INDENT>for project in other:<EOL><INDENT>for dist in other[project]:<EOL><INDENT>self.add(dist)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % (other,))<EOL><DEDENT>return self<EOL>

In-place addition of a distribution or environment


new = self.__class__([], platform=None, python=None)<EOL>for env in self, other:<EOL><INDENT>new += env<EOL><DEDENT>return new<EOL>

Add an environment or distribution to an environment


def resource_exists(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).has_resource(resource_name)<EOL>


def resource_isdir(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).resource_isdir(<EOL>resource_name<EOL>)<EOL>

Is the named resource an existing directory?


def resource_filename(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).get_resource_filename(<EOL>self, resource_name<EOL>)<EOL>

Return a true filesystem path for specified resource


def resource_stream(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).get_resource_stream(<EOL>self, resource_name<EOL>)<EOL>

Return a readable file-like object for specified resource


def resource_string(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).get_resource_string(<EOL>self, resource_name<EOL>)<EOL>


def resource_listdir(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).resource_listdir(<EOL>resource_name<EOL>)<EOL>

List the contents of the named resource directory


old_exc = sys.exc_info()[<NUM_LIT:1>]<EOL>cache_path = self.extraction_path or get_default_cache()<EOL>err = ExtractionError(

Give an error message for problems extracting file(s)


def get_cache_path(self, archive_name, names=()):

extract_path = self.extraction_path or get_default_cache()<EOL>target_path = os.path.join(extract_path, archive_name+'<STR_LIT>', *names)<EOL>try:<EOL><INDENT>ensure_directory(target_path)<EOL><DEDENT>except:<EOL><INDENT>self.extraction_error()<EOL><DEDENT>self.cached_files[target_path] = <NUM_LIT:1><EOL>return target_path<EOL>

Return absolute location in cache for `archive_name` and `names`

        The parent directory of the resulting path will be created if it does
        not already exist.  `archive_name` should be the base filename of the
        enclosing egg (which may not be the name of the enclosing zipfile!),
        including its ".egg" extension.  `names`, if provided, should be a
        sequence of path name parts "under" the egg's extraction location.

        This method should only be called by resource providers that need to
        obtain an extraction location, and only for names they intend to
        extract, as it tracks the generated names for possible cleanup later.


def postprocess(self, tempname, filename):

if os.name == '<STR_LIT>':<EOL><INDENT>mode = ((os.stat(tempname).st_mode) | <NUM_LIT>) & <NUM_LIT><EOL>os.chmod(tempname, mode)<EOL><DEDENT>

Perform any platform-specific postprocessing of `tempname`

        This is where Mac header rewrites should be done; other platforms don't
        have anything special they should do.

        Resource providers should call this method ONLY after successfully
        extracting a compressed resource.  They must NOT call it on resources
        that are already in the filesystem.

        `tempname` is the current (temporary) name of the file, and `filename`
        is the name it will be renamed to by the caller after this routine
        returns.


if self.cached_files:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>self.extraction_path = path<EOL>

Set the base path where resources will be extracted to, if needed.

        If you do not call this routine before any extractions take place, the
        path defaults to the return value of ``get_default_cache()``.  (Which
        is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
        platform-specific fallbacks.  See that routine's documentation for more
        details.)

        Resources are extracted to subdirectories of this path based upon
        information given by the ``IResourceProvider``.  You may set this to a
        temporary directory, but then you must call ``cleanup_resources()`` to
        delete the extracted files when done.  There is no guarantee that
        ``cleanup_resources()`` will be able to remove all extracted files.

        (Note: you may not change the extraction path for a given resource
        manager once resources have been extracted, unless you first call
        ``cleanup_resources()``.)


<EOL>

Delete all extracted resource files and directories, returning a list
of the file and directory names that could not be successfully removed.
This function does not have any concurrency protection, so it should
generally only be called when the extraction path is a temporary
directory exclusive to a single process.  This method is not
automatically called; you must call it explicitly or register it as an
``atexit`` function if you wish to ensure cleanup of a temporary
directory used for extractions.


self.zipinfo = zipimport._zip_directory_cache[importer.archive]<EOL>self.zip_pre = importer.archive+os.sep<EOL>self.loader = importer<EOL>if importer.prefix:<EOL><INDENT>self.module_path = os.path.join(importer.archive, importer.prefix)<EOL><DEDENT>else:<EOL><INDENT>self.module_path = importer.archive<EOL><DEDENT>self._setup_prefix()<EOL>

Create a metadata provider from a zipimporter


try:<EOL><INDENT>attrs = extras = ()<EOL>name,value = src.split('<STR_LIT:=>',<NUM_LIT:1>)<EOL>if '<STR_LIT:[>' in value:<EOL><INDENT>value,extras = value.split('<STR_LIT:[>',<NUM_LIT:1>)<EOL>req = Requirement.parse("<STR_LIT>"+extras)<EOL>if req.specs: raise ValueError<EOL>extras = req.extras<EOL><DEDENT>if '<STR_LIT::>' in value:<EOL><INDENT>value,attrs = value.split('<STR_LIT::>',<NUM_LIT:1>)<EOL>if not MODULE(attrs.rstrip()):<EOL><INDENT>raise ValueError<EOL><DEDENT>attrs = attrs.rstrip().split('<STR_LIT:.>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>",<EOL>src<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return cls(name.strip(), value.strip(), attrs, extras, dist)<EOL><DEDENT>

Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1,extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional


def parse_group(cls, group, lines, dist=None):

if not MODULE(group):<EOL><INDENT>raise ValueError("<STR_LIT>", group)<EOL><DEDENT>this = {}<EOL>for line in yield_lines(lines):<EOL><INDENT>ep = cls.parse(line, dist)<EOL>if ep.name in this:<EOL><INDENT>raise ValueError("<STR_LIT>", group, ep.name)<EOL><DEDENT>this[ep.name]=ep<EOL><DEDENT>return this<EOL>


if isinstance(data,dict):<EOL><INDENT>data = list(data.items())<EOL><DEDENT>else:<EOL><INDENT>data = split_sections(data)<EOL><DEDENT>maps = {}<EOL>for group, lines in data:<EOL><INDENT>if group is None:<EOL><INDENT>if not lines:<EOL><INDENT>continue<EOL><DEDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>group = group.strip()<EOL>if group in maps:<EOL><INDENT>raise ValueError("<STR_LIT>", group)<EOL><DEDENT>maps[group] = cls.parse_group(group, lines, dist)<EOL><DEDENT>return maps<EOL>


dm = self._dep_map<EOL>deps = []<EOL>deps.extend(dm.get(None,()))<EOL>for ext in extras:<EOL><INDENT>try:<EOL><INDENT>deps.extend(dm[safe_extra(ext)])<EOL><DEDENT>except KeyError:<EOL><INDENT>raise UnknownExtra(<EOL>"<STR_LIT>" % (self, ext)<EOL>)<EOL><DEDENT><DEDENT>return deps<EOL>

List of Requirements needed for this distro if `extras` are used


if path is None: path = sys.path<EOL>self.insert_on(path)<EOL>if path is sys.path:<EOL><INDENT>fixup_namespace_packages(self.location)<EOL>list(map(declare_namespace, self._get_metadata('<STR_LIT>')))<EOL><DEDENT>

Ensure distribution is importable on `path` (default=sys.path)


filename = "<STR_LIT>" % (<EOL>to_filename(self.project_name), to_filename(self.version),<EOL>self.py_version or PY_MAJOR<EOL>)<EOL>if self.platform:<EOL><INDENT>filename += '<STR_LIT:->'+self.platform<EOL><DEDENT>return filename<EOL>

Return what this distribution's standard .egg filename should be


if attr.startswith('<STR_LIT:_>'):<EOL><INDENT>raise AttributeError(attr)<EOL><DEDENT>return getattr(self._provider, attr)<EOL>

Delegate all unrecognized public attributes to .metadata provider


return Requirement.parse('<STR_LIT>' % (self.project_name, self.version))<EOL>

Return a ``Requirement`` that matches this distribution exactly


def load_entry_point(self, group, name):

ep = self.get_entry_info(group,name)<EOL>if ep is None:<EOL><INDENT>raise ImportError("<STR_LIT>" % ((group,name),))<EOL><DEDENT>return ep.load()<EOL>

Return the `name` entry point of `group` or raise ImportError


try:<EOL><INDENT>ep_map = self._ep_map<EOL><DEDENT>except AttributeError:<EOL><INDENT>ep_map = self._ep_map = EntryPoint.parse_map(<EOL>self._get_metadata('<STR_LIT>'), self<EOL>)<EOL><DEDENT>if group is not None:<EOL><INDENT>return ep_map.get(group,{})<EOL><DEDENT>return ep_map<EOL>

Return the entry point map for `group`, or the full entry map


return self.get_entry_map(group).get(name)<EOL>

Return the EntryPoint object for `group`+`name`, or ``None``


loc = loc or self.location<EOL>if not loc:<EOL><INDENT>return<EOL><DEDENT>if path is sys.path:<EOL><INDENT>self.check_version_conflict()<EOL><DEDENT>nloc = _normalize_cached(loc)<EOL>bdir = os.path.dirname(nloc)<EOL>npath= list(map(_normalize_cached, path))<EOL>bp = None<EOL>for p, item in enumerate(npath):<EOL><INDENT>if item==nloc:<EOL><INDENT>break<EOL><DEDENT>elif item==bdir and self.precedence==EGG_DIST:<EOL><INDENT>path.insert(p, loc)<EOL>npath.insert(p, nloc)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>path.append(loc)<EOL>return<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>np = npath.index(nloc, p+<NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>del npath[np], path[np]<EOL>p = np  <EOL><DEDENT><DEDENT>return<EOL>

Insert self.location in path before its nearest parent directory


for attr in (<EOL>'<STR_LIT>', '<STR_LIT:version>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:location>',<EOL>'<STR_LIT>'<EOL>):<EOL><INDENT>kw.setdefault(attr, getattr(self,attr,None))<EOL><DEDENT>kw.setdefault('<STR_LIT>', self._provider)<EOL>return self.__class__(**kw)<EOL>

Copy this distribution, substituting in any changed keyword args


def __init__(self, project_name, specs, extras):

self.unsafe_name, project_name = project_name, safe_name(project_name)<EOL>self.project_name, self.key = project_name, project_name.lower()<EOL>index = [(parse_version(v),state_machine[op],op,v) for op,v in specs]<EOL>index.sort()<EOL>self.specs = [(op,ver) for parsed,trans,op,ver in index]<EOL>self.index, self.extras = index, tuple(map(safe_extra,extras))<EOL>self.hashCmp = (<EOL>self.key, tuple([(op,parsed) for parsed,trans,op,ver in index]),<EOL>frozenset(self.extras)<EOL>)<EOL>self.__hash = hash(self.hashCmp)<EOL>

DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!


if resource_stream is not None:<EOL><INDENT>return resource_stream(__name__, '<STR_LIT>' + name)<EOL><DEDENT>else:<EOL><INDENT>name_parts = name.lstrip('<STR_LIT:/>').split('<STR_LIT:/>')<EOL>for part in name_parts:<EOL><INDENT>if part == os.path.pardir or os.path.sep in part:<EOL><INDENT>raise ValueError('<STR_LIT>' % part)<EOL><DEDENT><DEDENT>filename = os.path.join(os.path.dirname(__file__),<EOL>'<STR_LIT>', *name_parts)<EOL>return open(filename, '<STR_LIT:rb>')<EOL><DEDENT>

Open a resource from the zoneinfo subdir for reading.

    Uses the pkg_resources module if available.


if zone.upper() == '<STR_LIT>':<EOL><INDENT>return utc<EOL><DEDENT>try:<EOL><INDENT>zone = zone.encode('<STR_LIT>')<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>raise UnknownTimeZoneError(zone)<EOL><DEDENT>zone = _unmunge_zone(zone)<EOL>if zone not in _tzinfo_cache:<EOL><INDENT>if zone in all_timezones_set:<EOL><INDENT>_tzinfo_cache[zone] = build_tzinfo(zone, open_resource(zone))<EOL><DEDENT>else:<EOL><INDENT>raise UnknownTimeZoneError(zone)<EOL><DEDENT><DEDENT>return _tzinfo_cache[zone]<EOL>

r''' Return a datetime.tzinfo implementation for the given timezone

    >>> from datetime import datetime, timedelta
    >>> utc = timezone('UTC')
    >>> eastern = timezone('US/Eastern')
    >>> eastern.zone
    'US/Eastern'
    >>> timezone(u'US/Eastern') is eastern
    True
    >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
    >>> loc_dt = utc_dt.astimezone(eastern)
    >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
    >>> loc_dt.strftime(fmt)
    '2002-10-27 01:00:00 EST (-0500)'
    >>> (loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 00:50:00 EST (-0500)'
    >>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:50:00 EDT (-0400)'
    >>> (loc_dt + timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:10:00 EST (-0500)'

    Raises UnknownTimeZoneError if passed an unknown zone.

    >>> timezone('Asia/Shangri-La')
    Traceback (most recent call last):
    ...
    UnknownTimeZoneError: 'Asia/Shangri-La'

    >>> timezone(u'\N{TRADE MARK SIGN}')
    Traceback (most recent call last):
    ...
    UnknownTimeZoneError: u'\u2122'


return zone.replace('<STR_LIT>', '<STR_LIT:+>').replace('<STR_LIT>', '<STR_LIT:->')<EOL>

Undo the time zone name munging done by older versions of pytz.


return utc<EOL>

Factory function for utc unpickling.

    Makes sure that unpickling a utc instance always returns the same
    module global.

    These examples belong in the UTC class above, but it is obscured; or in
    the README.txt, but we are not depending on Python 2.4 so integrating
    the README.txt examples with the unit tests is not trivial.

    >>> import datetime, pickle
    >>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
    >>> naive = dt.replace(tzinfo=None)
    >>> p = pickle.dumps(dt, 1)
    >>> naive_p = pickle.dumps(naive, 1)
    >>> len(p), len(naive_p), len(p) - len(naive_p)
    (60, 43, 17)
    >>> new = pickle.loads(p)
    >>> new == dt
    True
    >>> new is dt
    False
    >>> new.tzinfo is dt.tzinfo
    True
    >>> utc is UTC is timezone('UTC')
    True
    >>> utc is timezone('GMT')
    False


return unpickler(*args)<EOL>

Factory function for unpickling pytz tzinfo instances.

    Just a wrapper around tzinfo.unpickler to save a few bytes in each pickle
    by shortening the path.


iso3166_code = iso3166_code.upper()<EOL>if not _country_timezones_cache:<EOL><INDENT>zone_tab = open_resource('<STR_LIT>')<EOL>for line in zone_tab:<EOL><INDENT>if line.startswith('<STR_LIT:#>'):<EOL><INDENT>continue<EOL><DEDENT>code, coordinates, zone = line.split(None, <NUM_LIT:4>)[:<NUM_LIT:3>]<EOL>try:<EOL><INDENT>_country_timezones_cache[code].append(zone)<EOL><DEDENT>except KeyError:<EOL><INDENT>_country_timezones_cache[code] = [zone]<EOL><DEDENT><DEDENT><DEDENT>return _country_timezones_cache[iso3166_code]<EOL>

Return a list of timezones used in a particular country.

    iso3166_code is the two letter code used to identify the country.

    >>> country_timezones('ch')
    ['Europe/Zurich']
    >>> country_timezones('CH')
    ['Europe/Zurich']
    >>> country_timezones(u'ch')
    ['Europe/Zurich']
    >>> country_timezones('XXX')
    Traceback (most recent call last):
    ...
    KeyError: 'XXX'


if offset == <NUM_LIT:0>:<EOL><INDENT>return UTC<EOL><DEDENT>info = _tzinfos.get(offset)<EOL>if info is None:<EOL><INDENT>info = _tzinfos.setdefault(offset, _FixedOffset(offset))<EOL><DEDENT>return info<EOL>

return a fixed-offset timezone based off a number of minutes.

        >>> one = FixedOffset(-330)
        >>> one
        pytz.FixedOffset(-330)
        >>> one.utcoffset(datetime.datetime.now())
        datetime.timedelta(-1, 66600)

        >>> two = FixedOffset(1380)
        >>> two
        pytz.FixedOffset(1380)
        >>> two.utcoffset(datetime.datetime.now())
        datetime.timedelta(0, 82800)

    The datetime.timedelta must be between the range of -1 and 1 day,
    non-inclusive.

        >>> FixedOffset(1440)
        Traceback (most recent call last):
        ...
        ValueError: ('absolute offset is too large', 1440)

        >>> FixedOffset(-1440)
        Traceback (most recent call last):
        ...
        ValueError: ('absolute offset is too large', -1440)

    An offset of 0 is special-cased to return UTC.

        >>> FixedOffset(0) is UTC
        True

    There should always be only one instance of a FixedOffset per timedelta.
    This should be true for multiple creation calls.

        >>> FixedOffset(-330) is one
        True
        >>> FixedOffset(1380) is two
        True

    It should also be true for pickling.

        >>> import pickle
        >>> pickle.loads(pickle.dumps(one)) is one
        True
        >>> pickle.loads(pickle.dumps(two)) is two
        True


if dt.tzinfo is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return dt.replace(tzinfo=self)<EOL>


if dt.tzinfo is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return dt.replace(tzinfo=self)<EOL>

Correct the timezone information on the given datetime


try:<EOL><INDENT>return _timedelta_cache[seconds]<EOL><DEDENT>except KeyError:<EOL><INDENT>delta = timedelta(seconds=seconds)<EOL>_timedelta_cache[seconds] = delta<EOL>return delta<EOL><DEDENT>

Create only one instance of each distinct timedelta


try:<EOL><INDENT>return _datetime_cache[seconds]<EOL><DEDENT>except KeyError:<EOL><INDENT>dt = _epoch + timedelta(seconds=seconds)<EOL>_datetime_cache[seconds] = dt<EOL>return dt<EOL><DEDENT>

Create only one instance of each distinct datetime


try:<EOL><INDENT>return _ttinfo_cache[args]<EOL><DEDENT>except KeyError:<EOL><INDENT>ttinfo = (<EOL>memorized_timedelta(args[<NUM_LIT:0>]),<EOL>memorized_timedelta(args[<NUM_LIT:1>]),<EOL>args[<NUM_LIT:2>]<EOL>)<EOL>_ttinfo_cache[args] = ttinfo<EOL>return ttinfo<EOL><DEDENT>

Create only one instance of each distinct tuple


return td.seconds + td.days * <NUM_LIT> * <NUM_LIT> * <NUM_LIT><EOL>


def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):

<EOL>tz = pytz.timezone(zone)<EOL>if utcoffset is None:<EOL><INDENT>return tz<EOL><DEDENT>utcoffset = memorized_timedelta(utcoffset)<EOL>dstoffset = memorized_timedelta(dstoffset)<EOL>try:<EOL><INDENT>return tz._tzinfos[(utcoffset, dstoffset, tzname)]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>for localized_tz in list(tz._tzinfos.values()):<EOL><INDENT>if (localized_tz._utcoffset == utcoffset<EOL>and localized_tz._dst == dstoffset):<EOL><INDENT>return localized_tz<EOL><DEDENT><DEDENT>inf = (utcoffset, dstoffset, tzname)<EOL>tz._tzinfos[inf] = tz.__class__(inf, tz._tzinfos)<EOL>return tz._tzinfos[inf]<EOL>

Factory function for unpickling pytz tzinfo instances.

    This is shared for both StaticTzInfo and DstTzInfo instances, because
    database changes could cause a zones implementation to switch between
    these two base classes and we can't break pickles on a pytz version
    upgrade.


return (dt + self._utcoffset).replace(tzinfo=self)<EOL>


return self._utcoffset<EOL>


return _notime<EOL>


return self._tzname<EOL>


dt = dt.replace(tzinfo=None)<EOL>idx = max(<NUM_LIT:0>, bisect_right(self._utc_transition_times, dt) - <NUM_LIT:1>)<EOL>inf = self._transition_info[idx]<EOL>return (dt + inf[<NUM_LIT:0>]).replace(tzinfo=self._tzinfos[inf])<EOL>


if dt.tzinfo is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>offset = dt.tzinfo._utcoffset<EOL>dt = dt.replace(tzinfo=None)<EOL>dt = dt - offset<EOL>return self.fromutc(dt)<EOL>

Correct the timezone information on the given datetime

        If date arithmetic crosses DST boundaries, the tzinfo
        is not magically adjusted. This method normalizes the
        tzinfo to the correct one.

        To test, first we need to do some setup

        >>> from pytz import timezone
        >>> utc = timezone('UTC')
        >>> eastern = timezone('US/Eastern')
        >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'

        We next create a datetime right on an end-of-DST transition point,
        the instant when the wallclocks are wound back one hour.

        >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
        >>> loc_dt = utc_dt.astimezone(eastern)
        >>> loc_dt.strftime(fmt)
        '2002-10-27 01:00:00 EST (-0500)'

        Now, if we subtract a few minutes from it, note that the timezone
        information has not changed.

        >>> before = loc_dt - timedelta(minutes=10)
        >>> before.strftime(fmt)
        '2002-10-27 00:50:00 EST (-0500)'

        But we can fix that by calling the normalize method

        >>> before = eastern.normalize(before)
        >>> before.strftime(fmt)
        '2002-10-27 01:50:00 EDT (-0400)'


if dt.tzinfo is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>possible_loc_dt = set()<EOL>for tzinfo in list(self._tzinfos.values()):<EOL><INDENT>loc_dt = tzinfo.normalize(dt.replace(tzinfo=tzinfo))<EOL>if loc_dt.replace(tzinfo=None) == dt:<EOL><INDENT>possible_loc_dt.add(loc_dt)<EOL><DEDENT><DEDENT>if len(possible_loc_dt) == <NUM_LIT:1>:<EOL><INDENT>return possible_loc_dt.pop()<EOL><DEDENT>if is_dst is None:<EOL><INDENT>raise AmbiguousTimeError(dt)<EOL><DEDENT>filtered_possible_loc_dt = [<EOL>p for p in possible_loc_dt<EOL>if bool(p.tzinfo._dst) == is_dst<EOL>]<EOL>if len(filtered_possible_loc_dt) == <NUM_LIT:1>:<EOL><INDENT>return filtered_possible_loc_dt[<NUM_LIT:0>]<EOL><DEDENT>if len(filtered_possible_loc_dt) == <NUM_LIT:0>:<EOL><INDENT>filtered_possible_loc_dt = list(possible_loc_dt)<EOL><DEDENT>def mycmp(a,b):<EOL><INDENT>return cmp(<EOL>a.replace(tzinfo=None) - a.tzinfo._utcoffset,<EOL>b.replace(tzinfo=None) - b.tzinfo._utcoffset,<EOL>)<EOL><DEDENT>filtered_possible_loc_dt.sort(mycmp)<EOL>return filtered_possible_loc_dt[<NUM_LIT:0>]<EOL>

Convert naive time to local time.

        This method should be used to construct localtimes, rather
        than passing a tzinfo argument to a datetime constructor.

        is_dst is used to determine the correct timezone in the ambigous
        period at the end of daylight savings time.

        >>> from pytz import timezone
        >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
        >>> amdam = timezone('Europe/Amsterdam')
        >>> dt  = datetime(2004, 10, 31, 2, 0, 0)
        >>> loc_dt1 = amdam.localize(dt, is_dst=True)
        >>> loc_dt2 = amdam.localize(dt, is_dst=False)
        >>> loc_dt1.strftime(fmt)
        '2004-10-31 02:00:00 CEST (+0200)'
        >>> loc_dt2.strftime(fmt)
        '2004-10-31 02:00:00 CET (+0100)'
        >>> str(loc_dt2 - loc_dt1)
        '1:00:00'

        Use is_dst=None to raise an AmbiguousTimeError for ambiguous
        times at the end of daylight savings

        >>> try:
        ...     loc_dt1 = amdam.localize(dt, is_dst=None)
        ... except AmbiguousTimeError:
        ...     print 'Oops'
        Oops

        >>> loc_dt1 = amdam.localize(dt, is_dst=None)
        Traceback (most recent call last):
            [...]
        AmbiguousTimeError: 2004-10-31 02:00:00

        is_dst defaults to False

        >>> amdam.localize(dt) == amdam.localize(dt, False)
        True


return self._dst<EOL>


<EOL>if True: <EOL><INDENT>trans = self._set_transform()<EOL>ax = self.ax<EOL>sx, sy = trans.inverted().transform_point(<EOL>(ax.bbox.width, ax.bbox.height))<EOL>self.span = sx<EOL>sn = max(<NUM_LIT:8>, min(<NUM_LIT>, math.sqrt(self.N)))<EOL>if self.width is None:<EOL><INDENT>self.width = <NUM_LIT> * self.span / sn<EOL><DEDENT><DEDENT>

initialization delayed until first draw;
        allow time for axes setup.


<EOL>minsh = self.minshaft * self.headlength<EOL>N = len(length)<EOL>length = length.reshape(N, <NUM_LIT:1>)<EOL>x = np.array([<NUM_LIT:0>, -self.headaxislength,<EOL>-self.headlength, <NUM_LIT:0>], np.float64)<EOL>x = x + np.array([<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:1>,<NUM_LIT:1>]) * length<EOL>y = <NUM_LIT:0.5> * np.array([<NUM_LIT:1>, <NUM_LIT:1>, self.headwidth, <NUM_LIT:0>], np.float64)<EOL>y = np.repeat(y[np.newaxis,:], N, axis=<NUM_LIT:0>)<EOL>x0 = np.array([<NUM_LIT:0>, minsh-self.headaxislength,<EOL>minsh-self.headlength, minsh], np.float64)<EOL>y0 = <NUM_LIT:0.5> * np.array([<NUM_LIT:1>, <NUM_LIT:1>, self.headwidth, <NUM_LIT:0>], np.float64)<EOL>ii = [<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:3>,<NUM_LIT:2>,<NUM_LIT:1>,<NUM_LIT:0>]<EOL>X = x.take(ii, <NUM_LIT:1>)<EOL>Y = y.take(ii, <NUM_LIT:1>)<EOL>Y[:, <NUM_LIT:3>:] *= -<NUM_LIT:1><EOL>X0 = x0.take(ii)<EOL>Y0 = y0.take(ii)<EOL>Y0[<NUM_LIT:3>:] *= -<NUM_LIT:1><EOL>shrink = length/minsh<EOL>X0 = shrink * X0[np.newaxis,:]<EOL>Y0 = shrink * Y0[np.newaxis,:]<EOL>short = np.repeat(length < minsh, <NUM_LIT:7>, axis=<NUM_LIT:1>)<EOL>X = ma.where(short, X0, X)<EOL>Y = ma.where(short, Y0, Y)<EOL>if self.pivot[:<NUM_LIT:3>] == '<STR_LIT>':<EOL><INDENT>X -= <NUM_LIT:0.5> * X[:,<NUM_LIT:3>, np.newaxis]<EOL><DEDENT>elif self.pivot[:<NUM_LIT:3>] == '<STR_LIT>':<EOL><INDENT>X = X - X[:,<NUM_LIT:3>, np.newaxis]   <EOL><DEDENT>tooshort = length < self.minlength<EOL>if tooshort.any():<EOL><INDENT>th = np.arange(<NUM_LIT:0>,<NUM_LIT:7>,<NUM_LIT:1>, np.float64) * (np.pi/<NUM_LIT>)<EOL>x1 = np.cos(th) * self.minlength * <NUM_LIT:0.5><EOL>y1 = np.sin(th) * self.minlength * <NUM_LIT:0.5><EOL>X1 = np.repeat(x1[np.newaxis, :], N, axis=<NUM_LIT:0>)<EOL>Y1 = np.repeat(y1[np.newaxis, :], N, axis=<NUM_LIT:0>)<EOL>tooshort = ma.repeat(tooshort, <NUM_LIT:7>, <NUM_LIT:1>)<EOL>X = ma.where(tooshort, X1, X)<EOL>Y = ma.where(tooshort, Y1, Y)<EOL><DEDENT>return X, Y<EOL>


def _find_tails(self, mag, rounding=True, half=<NUM_LIT:5>, full=<NUM_LIT:10>, flag=<NUM_LIT:50>):

<EOL>if rounding:<EOL><INDENT>mag = half * (mag / half + <NUM_LIT:0.5>).astype(np.int)<EOL><DEDENT>num_flags = np.floor(mag / flag).astype(np.int)<EOL>mag = np.mod(mag, flag)<EOL>num_barb = np.floor(mag / full).astype(np.int)<EOL>mag = np.mod(mag, full)<EOL>half_flag = mag >= half<EOL>empty_flag = ~(half_flag | (num_flags > <NUM_LIT:0>) | (num_barb > <NUM_LIT:0>))<EOL>return num_flags, num_barb, half_flag, empty_flag<EOL>

Find how many of each of the tail pieces is necessary.  Flag
specifies the increment for a flag, barb for a full barb, and half for
half a barb. Mag should be the magnitude of a vector (ie. >= 0).

This returns a tuple of:

    (*number of flags*, *number of barbs*, *half_flag*, *empty_flag*)

*half_flag* is a boolean whether half of a barb is needed,
since there should only ever be one half on a given
barb. *empty_flag* flag is an array of flags to easily tell if
a barb is empty (too low to plot any barbs/flags.


def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,<EOL>pivot, sizes, fill_empty, flip):

<EOL>spacing = length * sizes.get('<STR_LIT>', <NUM_LIT>)<EOL>full_height = length * sizes.get('<STR_LIT>', <NUM_LIT>)<EOL>full_width = length * sizes.get('<STR_LIT:width>', <NUM_LIT>)<EOL>empty_rad = length * sizes.get('<STR_LIT>', <NUM_LIT>)<EOL>pivot_points = dict(tip=<NUM_LIT:0.0>, middle=-length/<NUM_LIT>)<EOL>if flip: full_height = -full_height<EOL>endx = <NUM_LIT:0.0><EOL>endy = pivot_points[pivot.lower()]<EOL>angles = -(ma.arctan2(v, u) + np.pi/<NUM_LIT:2>)<EOL>circ = CirclePolygon((<NUM_LIT:0>,<NUM_LIT:0>), radius=empty_rad).get_verts()<EOL>if fill_empty:<EOL><INDENT>empty_barb = circ<EOL><DEDENT>else:<EOL><INDENT>empty_barb = np.concatenate((circ, circ[::-<NUM_LIT:1>]))<EOL><DEDENT>barb_list = []<EOL>for index, angle in np.ndenumerate(angles):<EOL><INDENT>if empty_flag[index]:<EOL><INDENT>barb_list.append(empty_barb)<EOL>continue<EOL><DEDENT>poly_verts = [(endx, endy)]<EOL>offset = length<EOL>for i in range(nflags[index]):<EOL><INDENT>if offset != length: offset += spacing / <NUM_LIT><EOL>poly_verts.extend([[endx, endy + offset],<EOL>[endx + full_height, endy - full_width/<NUM_LIT:2> + offset],<EOL>[endx, endy - full_width + offset]])<EOL>offset -= full_width + spacing<EOL><DEDENT>for i in range(nbarbs[index]):<EOL><INDENT>poly_verts.extend([(endx, endy + offset),<EOL>(endx + full_height, endy + offset + full_width/<NUM_LIT:2>),<EOL>(endx, endy + offset)])<EOL>offset -= spacing<EOL><DEDENT>if half_barb[index]:<EOL><INDENT>if offset == length:<EOL><INDENT>poly_verts.append((endx, endy + offset))<EOL>offset -= <NUM_LIT> * spacing<EOL><DEDENT>poly_verts.extend([(endx, endy + offset),<EOL>(endx + full_height/<NUM_LIT:2>, endy + offset + full_width/<NUM_LIT:4>),<EOL>(endx, endy + offset)])<EOL><DEDENT>poly_verts = transforms.Affine2D().rotate(-angle).transform(<EOL>poly_verts)<EOL>barb_list.append(poly_verts)<EOL><DEDENT>return barb_list<EOL>

This function actually creates the wind barbs.  *u* and *v*
are components of the vector in the *x* and *y* directions,
respectively.

*nflags*, *nbarbs*, and *half_barb*, empty_flag* are,
*respectively, the number of flags, number of barbs, flag for
*half a barb, and flag for empty barb, ostensibly obtained
*from :meth:`_find_tails`.

*length* is the length of the barb staff in points.

*pivot* specifies the point on the barb around which the
entire barb should be rotated.  Right now, valid options are
'head' and 'middle'.

*sizes* is a dictionary of coefficients specifying the ratio
of a given feature to the length of the barb. These features
include:

    - *spacing*: space between features (flags, full/half
       barbs)

    - *height*: distance from shaft of top of a flag or full
       barb

    - *width* - width of a flag, twice the width of a full barb

    - *emptybarb* - radius of the circle used for low
       magnitudes

*fill_empty* specifies whether the circle representing an
empty barb should be filled or not (this changes the drawing
of the polygon).

*flip* is a flag indicating whether the features should be flipped to
the other side of the barb (useful for winds in the southern
hemisphere.

This function returns list of arrays of vertices, defining a polygon for
each of the wind barbs.  These polygons have been rotated to properly
align with the vector direction.


self.x = xy[:,<NUM_LIT:0>]<EOL>self.y = xy[:,<NUM_LIT:1>]<EOL>x,y,u,v = delete_masked_points(self.x.ravel(), self.y.ravel(), self.u,<EOL>self.v)<EOL>xy = np.hstack((x[:,np.newaxis], y[:,np.newaxis]))<EOL>collections.PolyCollection.set_offsets(self, xy)<EOL>

Set the offsets for the barb polygons.  This saves the offets passed in
and actually sets version masked as appropriate for the existing U/V
data. *offsets* should be a sequence.

ACCEPTS: sequence of pairs of floats


backend = rcParams['<STR_LIT>']<EOL>if not rcParams['<STR_LIT>'] orbackend not in _interactive_bk:<EOL><INDENT>return<EOL><DEDENT>is_agg_backend = rcParams['<STR_LIT>'].endswith('<STR_LIT>')<EOL>if '<STR_LIT>' in sys.modules and not backend in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>import wx<EOL>if wx.App.IsMainLoopRunning():<EOL><INDENT>rcParams['<STR_LIT>'] = '<STR_LIT>' + '<STR_LIT>' * is_agg_backend<EOL><DEDENT><DEDENT>elif '<STR_LIT>' in sys.modules and not backend == '<STR_LIT>':<EOL><INDENT>import qt<EOL>if not qt.qApp.startingUp():<EOL><INDENT>rcParams['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT><DEDENT>elif '<STR_LIT>' in sys.modules and not backend == '<STR_LIT>':<EOL><INDENT>import PyQt4.QtGui<EOL>if not PyQt4.QtGui.qApp.startingUp():<EOL><INDENT>rcParams['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT><DEDENT>elif '<STR_LIT>' in sys.modules and not backend in ('<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>'):<EOL><INDENT>import gobject<EOL>if gobject.MainLoop().is_running():<EOL><INDENT>rcParams['<STR_LIT>'] = '<STR_LIT>' + '<STR_LIT>' * is_agg_backend<EOL><DEDENT><DEDENT>elif '<STR_LIT>' in sys.modules and not backend == '<STR_LIT>':<EOL><INDENT>pass<EOL><DEDENT>

If rcParams['backend_fallback'] is true, check to see if the
        current backend is compatible with the current running event
        loop, and if not switches to a compatible one.


close('<STR_LIT:all>')<EOL>global new_figure_manager, draw_if_interactive, show<EOL>matplotlib.use(newbackend, warn=False)<EOL>reload(matplotlib.backends)<EOL>from matplotlib.backends import pylab_setup<EOL>new_figure_manager, draw_if_interactive, show = pylab_setup()<EOL>

Switch the default backend to newbackend.  This feature is
**experimental**, and is only expected to work switching to an
image backend.  Eg, if you have a bunch of PostScript scripts that
you want to run from an interactive ipython session, you may want
to switch to the PS backend before running them to avoid having a
bunch of GUI windows popup.  If you try to interactively switch
from one GUI backend to another, you will explode.

Calling this command will close all open windows.


return matplotlib.is_interactive()<EOL>


matplotlib.interactive(False)<EOL>


matplotlib.interactive(True)<EOL>


return gci._current<EOL>

Get the current :class:`~matplotlib.cm.ScalarMappable` instance
(image or patch collection), or *None* if no images or patch
collections have been defined.  The commands
:func:`~matplotlib.pyplot.imshow` and
:func:`~matplotlib.pyplot.figimage` create
:class:`~matplotlib.image.Image` instances, and the commands
:func:`~matplotlib.pyplot.pcolor` and
:func:`~matplotlib.pyplot.scatter` create
:class:`~matplotlib.collections.Collection` instances.


gci._current = im<EOL>

Set the current image (target of colormap commands like
:func:`~matplotlib.pyplot.jet`, :func:`~matplotlib.pyplot.hot` or
:func:`~matplotlib.pyplot.clim`).


def figure(num=None, <EOL>figsize   = None, <EOL>dpi       = None, <EOL>facecolor = None, <EOL>edgecolor = None, <EOL>frameon = True,<EOL>FigureClass = Figure,<EOL>**kwargs<EOL>):

if figsize is None   : figsize   = rcParams['<STR_LIT>']<EOL>if dpi is None       : dpi       = rcParams['<STR_LIT>']<EOL>if facecolor is None : facecolor = rcParams['<STR_LIT>']<EOL>if edgecolor is None : edgecolor = rcParams['<STR_LIT>']<EOL>if num is None:<EOL><INDENT>allnums = [f.num for f in _pylab_helpers.Gcf.get_all_fig_managers()]<EOL>if allnums:<EOL><INDENT>num = max(allnums) + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>num = <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>num = int(num)  <EOL><DEDENT>figManager = _pylab_helpers.Gcf.get_fig_manager(num)<EOL>if figManager is None:<EOL><INDENT>if get_backend().lower() == '<STR_LIT>':  dpi = <NUM_LIT><EOL>figManager = new_figure_manager(num, figsize=figsize,<EOL>dpi=dpi,<EOL>facecolor=facecolor,<EOL>edgecolor=edgecolor,<EOL>frameon=frameon,<EOL>FigureClass=FigureClass,<EOL>**kwargs)<EOL>def make_active(event):<EOL><INDENT>_pylab_helpers.Gcf.set_active(figManager)<EOL><DEDENT>cid = figManager.canvas.mpl_connect('<STR_LIT>', make_active)<EOL>figManager._cidgcf = cid<EOL>_pylab_helpers.Gcf.set_active(figManager)<EOL>figManager.canvas.figure.number = num<EOL><DEDENT>draw_if_interactive()<EOL>return figManager.canvas.figure<EOL>

call signature::

  figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

Create a new figure and return a :class:`matplotlib.figure.Figure`
instance.  If *num* = *None*, the figure number will be incremented and
a new figure will be created.  The returned figure objects have a
*number* attribute holding this number.

If *num* is an integer, and ``figure(num)`` already exists, make it
active and return the handle to it.  If ``figure(num)`` does not exist
it will be created.  Numbering starts at 1, matlab style::

  figure(1)

If you are creating many figures, make sure you explicitly call "close"
on the figures you are not using, because this will enable pylab
to properly clean up the memory.

Optional keyword arguments:

  =========   =======================================================
  Keyword     Description
  =========   =======================================================
  figsize     width x height in inches; defaults to rc figure.figsize
  dpi         resolution; defaults to rc figure.dpi
  facecolor   the background color; defaults to rc figure.facecolor
  edgecolor   the border color; defaults to rc figure.edgecolor
  =========   =======================================================

rcParams defines the default values, which can be modified in the
matplotlibrc file

*FigureClass* is a :class:`~matplotlib.figure.Figure` or derived
class that will be passed on to :meth:`new_figure_manager` in the
backends which allows you to hook custom Figure classes into the
pylab interface.  Additional kwargs will be passed on to your
figure init function.


figManager = _pylab_helpers.Gcf.get_active()<EOL>if figManager is not None:<EOL><INDENT>return figManager.canvas.figure<EOL><DEDENT>else:<EOL><INDENT>return figure()<EOL><DEDENT>


if len(args)==<NUM_LIT:0>:<EOL><INDENT>figManager = _pylab_helpers.Gcf.get_active()<EOL>if figManager is None: return<EOL>else:<EOL><INDENT>figManager.canvas.mpl_disconnect(figManager._cidgcf)<EOL>_pylab_helpers.Gcf.destroy(figManager.num)<EOL><DEDENT><DEDENT>elif len(args)==<NUM_LIT:1>:<EOL><INDENT>arg = args[<NUM_LIT:0>]<EOL>if arg=='<STR_LIT:all>':<EOL><INDENT>for manager in _pylab_helpers.Gcf.get_all_fig_managers():<EOL><INDENT>manager.canvas.mpl_disconnect(manager._cidgcf)<EOL>_pylab_helpers.Gcf.destroy(manager.num)<EOL><DEDENT><DEDENT>elif isinstance(arg, int):<EOL><INDENT>_pylab_helpers.Gcf.destroy(arg)<EOL><DEDENT>elif isinstance(arg, Figure):<EOL><INDENT>for manager in _pylab_helpers.Gcf.get_all_fig_managers():<EOL><INDENT>if manager.canvas.figure==arg:<EOL><INDENT>manager.canvas.mpl_disconnect(manager._cidgcf)<EOL>_pylab_helpers.Gcf.destroy(manager.num)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'%type(arg))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>

Close a figure window

``close()`` by itself closes the current figure

``close(num)`` closes figure number *num*

``close(h)`` where *h* is a :class:`Figure` instance, closes that figure

``close('all')`` closes all the figure windows


gcf().clf()<EOL>draw_if_interactive()<EOL>


get_current_fig_manager().canvas.draw()<EOL>


return gcf().ginput(*args, **kwargs)<EOL>

Blocking call to interact with the figure.

This will wait for *n* clicks from the user and return a list of the
coordinates of each click.

If *timeout* is negative, does not timeout.


return gcf().waitforbuttonpress(*args, **kwargs)<EOL>

Blocking call to interact with the figure.

This will wait for *n* key or mouse clicks from the user and
return a list containing True's for keyboard clicks and False's
for mouse clicks.

If *timeout* is negative, does not timeout.


def figlegend(handles, labels, loc, **kwargs):

l = gcf().legend(handles, labels, loc, **kwargs)<EOL>draw_if_interactive()<EOL>return l<EOL>

Place a legend in the figure.

*labels*
  a sequence of strings

*handles*
  a sequence of :class:`~matplotlib.lines.Line2D` or
  :class:`~matplotlib.patches.Patch` instances

*loc*
  can be a string or an integer specifying the legend
  location

A :class:`matplotlib.legend.Legend` instance is returned.

Example::

  figlegend( (line1, line2, line3),
             ('label1', 'label2', 'label3'),
             'upper right' )

.. seealso::
   :func:`~matplotlib.pyplot.legend`:
     For information about the location codes


fig = gcf()<EOL>ax = fig.gca()<EOL>fig.hold(b)<EOL>ax.hold(b)<EOL>b = ax.ishold()<EOL>rc('<STR_LIT>', hold=b)<EOL>

Set the hold state.  If *b* is None (default), toggle the
hold state, else set the hold state to boolean value *b*::

  hold()      # toggle hold
  hold(True)  # hold is on
  hold(False) # hold is off

When *hold* is *True*, subsequent plot commands will be added to
the current axes.  When *hold* is *False*, the current axes and
figure will be cleared on the next plot command.


return gca().ishold()<EOL>

Return the hold status of the current axes


h = ishold()<EOL>hold(True)<EOL>func(*args, **kwargs)<EOL>hold(h)<EOL>

over calls::

  func(*args, **kwargs)

with ``hold(True)`` and then restores the hold state.


nargs = len(args)<EOL>if len(args)==<NUM_LIT:0>: return subplot(<NUM_LIT>, **kwargs)<EOL>if nargs><NUM_LIT:1>:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>arg = args[<NUM_LIT:0>]<EOL>if isinstance(arg, Axes):<EOL><INDENT>a = gcf().sca(arg)<EOL><DEDENT>else:<EOL><INDENT>rect = arg<EOL>a = gcf().add_axes(rect, **kwargs)<EOL><DEDENT>draw_if_interactive()<EOL>return a<EOL>

Add an axes at position rect specified by:

- ``axes()`` by itself creates a default full ``subplot(111)`` window axis.

- ``axes(rect, axisbg='w')`` where *rect* = [left, bottom, width,
  height] in normalized (0, 1) units.  *axisbg* is the background
  color for the axis, default white.

- ``axes(h)`` where *h* is an axes instance makes *h* the current
  axis.  An :class:`~matplotlib.axes.Axes` instance is returned.

=======   ============   ================================================
kwarg     Accepts        Desctiption
=======   ============   ================================================
axisbg    color          the axes background color
frameon   [True|False]   display the frame?
sharex    otherax        current axes shares xaxis attribute with otherax
sharey    otherax        current axes shares yaxis attribute with otherax
polar     [True|False]   use a polar axes?
=======   ============   ================================================

Examples:

* :file:`examples/pylab_examples/axes_demo.py` places custom axes.
* :file:`examples/pylab_examples/shared_axis_demo.py` uses
  *sharex* and *sharey*.


if not len(args):<EOL><INDENT>ax = gca()<EOL><DEDENT>else:<EOL><INDENT>ax = args[<NUM_LIT:0>]<EOL><DEDENT>ret = gcf().delaxes(ax)<EOL>draw_if_interactive()<EOL>return ret<EOL>

``delaxes(ax)``: remove *ax* from the current figure.  If *ax*
doesn't exist, an error will be raised.

``delaxes()``: delete the current axes


ax =  gcf().gca(**kwargs)<EOL>return ax<EOL>

Return the current axis instance.  This can be used to control
axis properties either using set or the
:class:`~matplotlib.axes.Axes` methods, for example, setting the
xaxis range::

  plot(t,s)
  set(gca(), 'xlim', [0,10])

or::

  plot(t,s)
  a = gca()
  a.set_xlim([0,10])


fig = gcf()<EOL>a = fig.add_subplot(*args, **kwargs)<EOL>bbox = a.bbox<EOL>byebye = []<EOL>for other in fig.axes:<EOL><INDENT>if other==a: continue<EOL>if bbox.fully_overlaps(other.bbox):<EOL><INDENT>byebye.append(other)<EOL><DEDENT><DEDENT>for ax in byebye: delaxes(ax)<EOL>draw_if_interactive()<EOL>return a<EOL>

Create a subplot command, creating axes with::

  subplot(numRows, numCols, plotNum)

where *plotNum* = 1 is the first plot number and increasing *plotNums*
fill rows first.  max(*plotNum*) == *numRows* * *numCols*

You can leave out the commas if *numRows* <= *numCols* <=
*plotNum* < 10, as in::

  subplot(211)    # 2 rows, 1 column, first (upper) plot

``subplot(111)`` is the default axis.

New subplots that overlap old will delete the old axes.  If you do
not want this behavior, use
:meth:`matplotlib.figure.Figure.add_subplot` or the
:func:`~matplotlib.pyplot.axes` command.  Eg.::

  from pylab import *
  plot([1,2,3])  # implicitly creates subplot(111)
  subplot(211)   # overlaps, subplot(111) is killed
  plot(rand(12), rand(12))
  subplot(212, axisbg='y') # creates 2nd subplot with yellow background

Keyword arguments:

  *axisbg*:
    The background color of the subplot, which can be any valid
    color specifier.  See :mod:`matplotlib.colors` for more
    information.

  *polar*:
    A boolean flag indicating whether the subplot plot should be
    a polar projection.  Defaults to False.

  *projection*:
    A string giving the name of a custom projection to be used
    for the subplot. This projection must have been previously
    registered. See :func:`matplotlib.projections.register_projection`

.. seealso::
    :func:`~matplotlib.pyplot.axes`:
        For additional information on :func:`axes` and
        :func:`subplot` keyword arguments.

    :file:`examples/pylab_examples/polar_scatter.py`

**Example:**

.. plot:: mpl_examples/pylab_examples/subplot_demo.py


if ax is None:<EOL><INDENT>ax=gca()<EOL><DEDENT>ax1 = ax.twinx()<EOL>draw_if_interactive()<EOL>return ax1<EOL>

Make a second axes overlay *ax* (or the current axes if *ax* is
*None*) sharing the xaxis.  The ticks for *ax2* will be placed on
the right, and the *ax2* instance is returned.

.. seealso::
   :file:`examples/api_examples/two_scales.py`


if ax is None:<EOL><INDENT>ax=gca()<EOL><DEDENT>ax1 = ax.twiny()<EOL>draw_if_interactive()<EOL>return ax1<EOL>

Make a second axes overlay *ax* (or the current axes if *ax* is
*None*) sharing the yaxis.  The ticks for *ax2* will be placed on
the top, and the *ax2* instance is returned.


fig = gcf()<EOL>fig.subplots_adjust(*args, **kwargs)<EOL>draw_if_interactive()<EOL>

call signature::

  subplots_adjust(left=None, bottom=None, right=None, top=None,
                  wspace=None, hspace=None)

Tune the subplot layout via the
:class:`matplotlib.figure.SubplotParams` mechanism.  The parameter
meanings (and suggested defaults) are::

  left  = 0.125  # the left side of the subplots of the figure
  right = 0.9    # the right side of the subplots of the figure
  bottom = 0.1   # the bottom of the subplots of the figure
  top = 0.9      # the top of the subplots of the figure
  wspace = 0.2   # the amount of width reserved for blank space between subplots
  hspace = 0.2   # the amount of height reserved for white space between subplots

The actual defaults are controlled by the rc file