code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example:: retcode = call(["ls", "-l"]) """ timeout = kwargs.pop('timeout', None) with Popen(*popenargs, **kwargs) as p: try: return p.wait(timeout=timeout) except: p.kill() p.wait() raise
Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example:: retcode = call(["ls", "-l"])
call
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise :exc:`CalledProcessError`. The ``CalledProcessError`` object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example:: retcode = check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return 0
Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise :exc:`CalledProcessError`. The ``CalledProcessError`` object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example:: retcode = check_call(["ls", "-l"])
check_call
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output. If the exit code was non-zero it raises a :exc:`CalledProcessError`. The ``CalledProcessError`` object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example:: >>> check_output(["ls", "-1", "/dev/null"]) b'/dev/null\n' The ``stdout`` argument is not allowed as it is used internally. To capture standard error in the result, use ``stderr=STDOUT``:: >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) b'ls: non_existent_file: No such file or directory\n' There is an additional optional argument, "input", allowing you to pass a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it too will be used internally. Example:: >>> check_output(["sed", "-e", "s/foo/bar/"], ... input=b"when in the course of fooman events\n") b'when in the course of barman events\n' If ``universal_newlines=True`` is passed, the return value will be a string rather than bytes. """ timeout = kwargs.pop('timeout', None) if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') if 'input' in kwargs: if 'stdin' in kwargs: raise ValueError('stdin and input arguments may not both be used.') inputdata = kwargs['input'] del kwargs['input'] kwargs['stdin'] = PIPE else: inputdata = None with Popen(*popenargs, stdout=PIPE, **kwargs) as process: try: output, unused_err = process.communicate(inputdata, timeout=timeout) except TimeoutExpired: process.kill() output, unused_err = process.communicate() raise TimeoutExpired(process.args, timeout, output=output) except: process.kill() process.wait() raise retcode = process.poll() if retcode: raise CalledProcessError(retcode, process.args, output=output) return output
Run command with arguments and return its output. If the exit code was non-zero it raises a :exc:`CalledProcessError`. The ``CalledProcessError`` object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example:: >>> check_output(["ls", "-1", "/dev/null"]) b'/dev/null\n' The ``stdout`` argument is not allowed as it is used internally. To capture standard error in the result, use ``stderr=STDOUT``:: >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) b'ls: non_existent_file: No such file or directory\n' There is an additional optional argument, "input", allowing you to pass a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it too will be used internally. Example:: >>> check_output(["sed", "-e", "s/foo/bar/"], ... input=b"when in the course of fooman events\n") b'when in the course of barman events\n' If ``universal_newlines=True`` is passed, the return value will be a string rather than bytes.
check_output
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> print(check_output(["ls", "-1", "/dev/null"]).decode('ascii')) /dev/null <BLANKLINE> The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> print(check_output(["/bin/sh", "-c", "echo hello world"], stderr=STDOUT).decode('ascii')) hello world <BLANKLINE> """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output = process.communicate()[0] retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] ex = CalledProcessError(retcode, cmd) # on Python 2.6 and older CalledProcessError does not accept 'output' argument ex.output = output raise ex return output
Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> print(check_output(["ls", "-1", "/dev/null"]).decode('ascii')) /dev/null <BLANKLINE> The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> print(check_output(["/bin/sh", "-c", "echo hello world"], stderr=STDOUT).decode('ascii')) hello world <BLANKLINE>
check_output
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def __init__(self, args, bufsize=None, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, threadpool=None, **kwargs): """Create new Popen instance. :param kwargs: *Only* allowed under Python 3; under Python 2, any unrecognized keyword arguments will result in a :exc:`TypeError`. Under Python 3, keyword arguments can include ``pass_fds``, ``start_new_session``, and ``restore_signals``. """ if not PY3 and kwargs: raise TypeError("Got unexpected keyword arguments", kwargs) pass_fds = kwargs.pop('pass_fds', ()) start_new_session = kwargs.pop('start_new_session', False) restore_signals = kwargs.pop('restore_signals', True) hub = get_hub() if bufsize is None: # bufsize has different defaults on Py3 and Py2 if PY3: bufsize = -1 else: bufsize = 0 if not isinstance(bufsize, integer_types): raise TypeError("bufsize must be an integer") if mswindows: if preexec_fn is not None: raise ValueError("preexec_fn is not supported on Windows " "platforms") any_stdio_set = (stdin is not None or stdout is not None or stderr is not None) if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: if any_stdio_set: close_fds = False else: close_fds = True elif close_fds and any_stdio_set: raise ValueError("close_fds is not supported on Windows " "platforms if you redirect stdin/stdout/stderr") if threadpool is None: threadpool = hub.threadpool self.threadpool = threadpool self._waiting = False else: # POSIX if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: # close_fds has different defaults on Py3/Py2 if PY3: close_fds = True else: close_fds = False if pass_fds and not close_fds: import warnings warnings.warn("pass_fds overriding close_fds.", RuntimeWarning) close_fds = True if startupinfo is not None: raise ValueError("startupinfo is only supported on Windows " "platforms") if creationflags != 0: raise ValueError("creationflags is only supported on Windows " "platforms") assert threadpool is None self._loop = hub.loop if PY3: self.args = args self.stdin = None self.stdout = None self.stderr = None self.pid = None self.returncode = None self.universal_newlines = universal_newlines self.result = AsyncResult() # Input and output objects. The general principle is like # this: # # Parent Child # ------ ----- # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite # # On POSIX, the child objects are file descriptors. On # Windows, these are Windows file handles. The parent objects # are file descriptors on both platforms. The parent objects # are None when not using PIPEs. The child objects are None # when not redirecting. (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) # We wrap OS handles *before* launching the child, otherwise a # quickly terminating child could make our fds unwrappable # (see #8458). if mswindows: if p2cwrite is not None: p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0) if c2pread is not None: c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0) if errread is not None: errread = msvcrt.open_osfhandle(errread.Detach(), 0) if p2cwrite is not None: if PY3 and universal_newlines: # Under Python 3, if we left on the 'b' we'd get different results # depending on whether we used FileObjectPosix or FileObjectThread self.stdin = FileObject(p2cwrite, 'wb', bufsize) self.stdin._translate = True self.stdin.io = io.TextIOWrapper(self.stdin.io, write_through=True, line_buffering=(bufsize == 1)) else: self.stdin = FileObject(p2cwrite, 'wb', bufsize) if c2pread is not None: if universal_newlines: if PY3: # FileObjectThread doesn't support the 'U' qualifier # with a bufsize of 0 self.stdout = FileObject(c2pread, 'rb', bufsize) # NOTE: Universal Newlines are broken on Windows/Py3, at least # in some cases. This is true in the stdlib subprocess module # as well; the following line would fix the test cases in # test__subprocess.py that depend on python_universal_newlines, # but would be inconsistent with the stdlib: #msvcrt.setmode(self.stdout.fileno(), os.O_TEXT) self.stdout.io = io.TextIOWrapper(self.stdout.io) self.stdout.io.mode = 'r' self.stdout._translate = True else: self.stdout = FileObject(c2pread, 'rU', bufsize) else: self.stdout = FileObject(c2pread, 'rb', bufsize) if errread is not None: if universal_newlines: if PY3: self.stderr = FileObject(errread, 'rb', bufsize) self.stderr.io = io.TextIOWrapper(self.stderr.io) self.stderr._translate = True else: self.stderr = FileObject(errread, 'rU', bufsize) else: self.stderr = FileObject(errread, 'rb', bufsize) self._closed_child_pipe_fds = False try: self._execute_child(args, executable, preexec_fn, close_fds, pass_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session) except: # Cleanup if the child failed starting. # (gevent: New in python3, but reported as gevent bug in #347. # Note that under Py2, any error raised below will replace the # original error so we have to use reraise) if not PY3: exc_info = sys.exc_info() for f in filter(None, (self.stdin, self.stdout, self.stderr)): try: f.close() except (OSError, IOError): pass # Ignore EBADF or other errors. if not self._closed_child_pipe_fds: to_close = [] if stdin == PIPE: to_close.append(p2cread) if stdout == PIPE: to_close.append(c2pwrite) if stderr == PIPE: to_close.append(errwrite) if hasattr(self, '_devnull'): to_close.append(self._devnull) for fd in to_close: try: os.close(fd) except (OSError, IOError): pass if not PY3: try: reraise(*exc_info) finally: del exc_info raise
Create new Popen instance. :param kwargs: *Only* allowed under Python 3; under Python 2, any unrecognized keyword arguments will result in a :exc:`TypeError`. Under Python 3, keyword arguments can include ``pass_fds``, ``start_new_session``, and ``restore_signals``.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def communicate(self, input=None, timeout=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). :keyword timeout: Under Python 2, this is a gevent extension; if given and it expires, we will raise :class:`gevent.timeout.Timeout`. Under Python 3, this raises the standard :exc:`TimeoutExpired` exception. .. versionchanged:: 1.1a2 Under Python 2, if the *timeout* elapses, raise the :exc:`gevent.timeout.Timeout` exception. Previously, we silently returned. .. versionchanged:: 1.1b5 Honor a *timeout* even if there's no way to communicate with the child (stdin, stdout, and stderr are not pipes). """ greenlets = [] if self.stdin: greenlets.append(spawn(write_and_close, self.stdin, input)) # If the timeout parameter is used, and the caller calls back after # getting a TimeoutExpired exception, we can wind up with multiple # greenlets trying to run and read from and close stdout/stderr. # That's bad because it can lead to 'RuntimeError: reentrant call in io.BufferedReader'. # We can't just kill the previous greenlets when a timeout happens, # though, because we risk losing the output collected by that greenlet # (and Python 3, where timeout is an official parameter, explicitly says # that no output should be lost in the event of a timeout.) Instead, we're # watching for the exception and ignoring it. It's not elegant, # but it works if self.stdout: def _read_out(): try: data = self.stdout.read() except RuntimeError: return if self._stdout_buffer is not None: self._stdout_buffer += data else: self._stdout_buffer = data stdout = spawn(_read_out) greenlets.append(stdout) else: stdout = None if self.stderr: def _read_err(): try: data = self.stderr.read() except RuntimeError: return if self._stderr_buffer is not None: self._stderr_buffer += data else: self._stderr_buffer = data stderr = spawn(_read_err) greenlets.append(stderr) else: stderr = None # If we were given stdin=stdout=stderr=None, we have no way to # communicate with the child, and thus no greenlets to wait # on. This is a nonsense case, but it comes up in the test # case for Python 3.5 (test_subprocess.py # RunFuncTestCase.test_timeout). Instead, we go directly to # self.wait if not greenlets and timeout is not None: result = self.wait(timeout=timeout) # Python 3 would have already raised, but Python 2 would not # so we need to do that manually if result is None: from gevent.timeout import Timeout raise Timeout(timeout) done = joinall(greenlets, timeout=timeout) if timeout is not None and len(done) != len(greenlets): if PY3: raise TimeoutExpired(self.args, timeout) from gevent.timeout import Timeout raise Timeout(timeout) if self.stdout: try: self.stdout.close() except RuntimeError: pass if self.stderr: try: self.stderr.close() except RuntimeError: pass self.wait() stdout_value = self._stdout_buffer self._stdout_buffer = None stderr_value = self._stderr_buffer self._stderr_buffer = None # XXX: Under python 3 in universal newlines mode we should be # returning str, not bytes return (None if stdout is None else stdout_value or b'', None if stderr is None else stderr_value or b'')
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). :keyword timeout: Under Python 2, this is a gevent extension; if given and it expires, we will raise :class:`gevent.timeout.Timeout`. Under Python 3, this raises the standard :exc:`TimeoutExpired` exception. .. versionchanged:: 1.1a2 Under Python 2, if the *timeout* elapses, raise the :exc:`gevent.timeout.Timeout` exception. Previously, we silently returned. .. versionchanged:: 1.1b5 Honor a *timeout* even if there's no way to communicate with the child (stdin, stdout, and stderr are not pipes).
communicate
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin is None and stdout is None and stderr is None: return (None, None, None, None, None, None) p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None try: DEVNULL except NameError: _devnull = object() else: _devnull = DEVNULL if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) if p2cread is None: p2cread, _ = CreatePipe(None, 0) if PY3: p2cread = Handle(p2cread) _winapi.CloseHandle(_) elif stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) if PY3: p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite) elif stdin == _devnull: p2cread = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stdin, int): p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object p2cread = msvcrt.get_osfhandle(stdin.fileno()) p2cread = self._make_inheritable(p2cread) if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) if c2pwrite is None: _, c2pwrite = CreatePipe(None, 0) if PY3: c2pwrite = Handle(c2pwrite) _winapi.CloseHandle(_) elif stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) if PY3: c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite) elif stdout == _devnull: c2pwrite = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stdout, int): c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) c2pwrite = self._make_inheritable(c2pwrite) if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) if errwrite is None: _, errwrite = CreatePipe(None, 0) if PY3: errwrite = Handle(errwrite) _winapi.CloseHandle(_) elif stderr == PIPE: errread, errwrite = CreatePipe(None, 0) if PY3: errread, errwrite = Handle(errread), Handle(errwrite) elif stderr == STDOUT: errwrite = c2pwrite elif stderr == _devnull: errwrite = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stderr, int): errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object errwrite = msvcrt.get_osfhandle(stderr.fileno()) errwrite = self._make_inheritable(errwrite) return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
_get_handles
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS)
Return a duplicate of handle, which is inheritable
_make_inheritable
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def _find_w9xpopen(self): """Find and return absolute path to w9xpopen.exe""" w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen
Find and return absolute path to w9xpopen.exe
_find_w9xpopen
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def _internal_poll(self): """Check if child process has terminated. Returns returncode attribute. """ if self.returncode is None: if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: self.returncode = GetExitCodeProcess(self._handle) self.result.set(self.returncode) return self.returncode
Check if child process has terminated. Returns returncode attribute.
_internal_poll
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def wait(self, timeout=None): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: if not self._waiting: self._waiting = True self._wait() result = self.result.wait(timeout=timeout) if PY3 and timeout is not None and not self.result.ready(): raise TimeoutExpired(self.args, timeout) return result
Wait for child process to terminate. Returns returncode attribute.
wait
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None try: DEVNULL except NameError: _devnull = object() else: _devnull = DEVNULL if stdin is None: pass elif stdin == PIPE: p2cread, p2cwrite = self.pipe_cloexec() elif stdin == _devnull: p2cread = self._get_devnull() elif isinstance(stdin, int): p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout is None: pass elif stdout == PIPE: c2pread, c2pwrite = self.pipe_cloexec() elif stdout == _devnull: c2pwrite = self._get_devnull() elif isinstance(stdout, int): c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr is None: pass elif stderr == PIPE: errread, errwrite = self.pipe_cloexec() elif stderr == STDOUT: errwrite = c2pwrite elif stderr == _devnull: errwrite = self._get_devnull() elif isinstance(stderr, int): errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
_get_handles
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def pipe_cloexec(self): """Create a pipe with FDs set CLOEXEC.""" # Pipes' FDs are set CLOEXEC by default because we don't want them # to be inherited by other subprocesses: the CLOEXEC flag is removed # from the child's FDs by _dup2(), between fork() and exec(). # This is not atomic: we would need the pipe2() syscall for that. r, w = os.pipe() self._set_cloexec_flag(r) self._set_cloexec_flag(w) return r, w
Create a pipe with FDs set CLOEXEC.
pipe_cloexec
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def _internal_poll(self): """Check if child process has terminated. Returns returncode attribute. """ if self.returncode is None: if get_hub() is not getcurrent(): sig_pending = getattr(self._loop, 'sig_pending', True) if sig_pending: sleep(0.00001) return self.returncode
Check if child process has terminated. Returns returncode attribute.
_internal_poll
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def wait(self, timeout=None): """Wait for child process to terminate. Returns :attr:`returncode` attribute. :keyword timeout: The floating point number of seconds to wait. Under Python 2, this is a gevent extension, and we simply return if it expires. Under Python 3, if this time elapses without finishing the process, :exc:`TimeoutExpired` is raised.""" result = self.result.wait(timeout=timeout) if PY3 and timeout is not None and not self.result.ready(): raise TimeoutExpired(self.args, timeout) return result
Wait for child process to terminate. Returns :attr:`returncode` attribute. :keyword timeout: The floating point number of seconds to wait. Under Python 2, this is a gevent extension, and we simply return if it expires. Under Python 3, if this time elapses without finishing the process, :exc:`TimeoutExpired` is raised.
wait
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/subprocess.py
MIT
def join(self): """Waits until all outstanding tasks have been completed.""" delay = 0.0005 while self.task_queue.unfinished_tasks > 0: sleep(delay) delay = min(delay * 2, .05)
Waits until all outstanding tasks have been completed.
join
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/threadpool.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/threadpool.py
MIT
def spawn(self, func, *args, **kwargs): """ Add a new task to the threadpool that will run ``func(*args, **kwargs)``. Waits until a slot is available. Creates a new thread if necessary. :return: A :class:`gevent.event.AsyncResult`. """ while True: semaphore = self._semaphore semaphore.acquire() if semaphore is self._semaphore: break thread_result = None try: task_queue = self.task_queue result = AsyncResult() # XXX We're calling the semaphore release function in the hub, otherwise # we get LoopExit (why?). Previously it was done with a rawlink on the # AsyncResult and the comment that it is "competing for order with get(); this is not # good, just make ThreadResult release the semaphore before doing anything else" thread_result = ThreadResult(result, hub=self.hub, call_when_ready=semaphore.release) task_queue.put((func, args, kwargs, thread_result)) self.adjust() except: if thread_result is not None: thread_result.destroy() semaphore.release() raise return result
Add a new task to the threadpool that will run ``func(*args, **kwargs)``. Waits until a slot is available. Creates a new thread if necessary. :return: A :class:`gevent.event.AsyncResult`.
spawn
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/threadpool.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/threadpool.py
MIT
def apply_e(self, expected_errors, function, args=None, kwargs=None): """ .. deprecated:: 1.1a2 Identical to :meth:`apply`; the ``expected_errors`` argument is ignored. """ # Deprecated but never documented. In the past, before # self.apply() allowed all errors to be raised to the caller, # expected_errors allowed a caller to specify a set of errors # they wanted to be raised, through the wrap_errors function. # In practice, it always took the value Exception or # BaseException. return self.apply(function, args, kwargs)
.. deprecated:: 1.1a2 Identical to :meth:`apply`; the ``expected_errors`` argument is ignored.
apply_e
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/threadpool.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/threadpool.py
MIT
def start_new(cls, timeout=None, exception=None, ref=True): """Create a started :class:`Timeout`. This is a shortcut, the exact action depends on *timeout*'s type: * If *timeout* is a :class:`Timeout`, then call its :meth:`start` method if it's not already begun. * Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as arguments, then call its :meth:`start` method. Returns the :class:`Timeout` instance. """ if isinstance(timeout, Timeout): if not timeout.pending: timeout.start() return timeout timeout = cls(timeout, exception, ref=ref) timeout.start() return timeout
Create a started :class:`Timeout`. This is a shortcut, the exact action depends on *timeout*'s type: * If *timeout* is a :class:`Timeout`, then call its :meth:`start` method if it's not already begun. * Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as arguments, then call its :meth:`start` method. Returns the :class:`Timeout` instance.
start_new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/timeout.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/timeout.py
MIT
def __str__(self): """ >>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... Timeout """ if self.seconds is None: return '' suffix = '' if self.seconds == 1 else 's' if self.exception is None: return '%s second%s' % (self.seconds, suffix) if self.exception is False: return '%s second%s (silent)' % (self.seconds, suffix) return '%s second%s: %s' % (self.seconds, suffix, self.exception)
>>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... Timeout
__str__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/timeout.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/timeout.py
MIT
def with_timeout(seconds, function, *args, **kwds): """Wrap a call to *function* with a timeout; if the called function fails to return before the timeout, cancel it and return a flag value, provided by *timeout_value* keyword argument. If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`. Keyword argument *timeout_value* is not passed to *function*. """ timeout_value = kwds.pop("timeout_value", _NONE) timeout = Timeout.start_new(seconds) try: try: return function(*args, **kwds) except Timeout as ex: if ex is timeout and timeout_value is not _NONE: return timeout_value raise finally: timeout.cancel()
Wrap a call to *function* with a timeout; if the called function fails to return before the timeout, cancel it and return a flag value, provided by *timeout_value* keyword argument. If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`. Keyword argument *timeout_value* is not passed to *function*.
with_timeout
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/timeout.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/timeout.py
MIT
def __init__(self, errors, func): """ Calling this makes a new function from *func*, such that it catches *errors* (an :exc:`BaseException` subclass, or a tuple of :exc:`BaseException` subclasses) and return it as a value. """ self.__errors = errors self.__func = func # Set __doc__, __wrapped__, etc, especially useful on Python 3. functools.update_wrapper(self, func)
Calling this makes a new function from *func*, such that it catches *errors* (an :exc:`BaseException` subclass, or a tuple of :exc:`BaseException` subclasses) and return it as a value.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/util.py
MIT
def fromEnvironment(cls): """ Get as many of the platform-specific error translation objects as possible and return an instance of C{cls} created with them. """ try: from ctypes import WinError except ImportError: WinError = None try: from win32api import FormatMessage except ImportError: FormatMessage = None try: from socket import errorTab except ImportError: errorTab = None return cls(WinError, FormatMessage, errorTab)
Get as many of the platform-specific error translation objects as possible and return an instance of C{cls} created with them.
fromEnvironment
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/win32util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/win32util.py
MIT
def formatError(self, errorcode): """ Returns the string associated with a Windows error message, such as the ones found in socket.error. Attempts direct lookup against the win32 API via ctypes and then pywin32 if available), then in the error table in the socket module, then finally defaulting to C{os.strerror}. @param errorcode: the Windows error code @type errorcode: C{int} @return: The error message string @rtype: C{str} """ if self.winError is not None: return str(self.winError(errorcode)) if self.formatMessage is not None: return self.formatMessage(errorcode) if self.errorTab is not None: result = self.errorTab.get(errorcode) if result is not None: return result return os.strerror(errorcode)
Returns the string associated with a Windows error message, such as the ones found in socket.error. Attempts direct lookup against the win32 API via ctypes and then pywin32 if available), then in the error table in the socket module, then finally defaulting to C{os.strerror}. @param errorcode: the Windows error code @type errorcode: C{int} @return: The error message string @rtype: C{str}
formatError
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/win32util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/win32util.py
MIT
def release(self): """ Release the semaphore, notifying any waiters if needed. """ self.counter += 1 self._start_notify() return self.counter
Release the semaphore, notifying any waiters if needed.
release
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_semaphore.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_semaphore.py
MIT
def rawlink(self, callback): """ rawlink(callback) -> None Register a callback to call when a counter is more than zero. *callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API. *callback* will be passed one argument: this instance. This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most code will not need to use it. """ if not callable(callback): raise TypeError('Expected callable:', callback) if self._links is None: self._links = [callback] else: self._links.append(callback) self._dirty = True
rawlink(callback) -> None Register a callback to call when a counter is more than zero. *callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API. *callback* will be passed one argument: this instance. This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most code will not need to use it.
rawlink
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_semaphore.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_semaphore.py
MIT
def unlink(self, callback): """ unlink(callback) -> None Remove the callback set by :meth:`rawlink`. This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most code will not need to use it. """ try: self._links.remove(callback) self._dirty = True except (ValueError, AttributeError): pass if not self._links: self._links = None # TODO: Cancel a notifier if there are no links?
unlink(callback) -> None Remove the callback set by :meth:`rawlink`. This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most code will not need to use it.
unlink
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_semaphore.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_semaphore.py
MIT
def _do_wait(self, timeout): """ Wait for up to *timeout* seconds to expire. If timeout elapses, return the exception. Otherwise, return None. Raises timeout if a different timer expires. """ switch = getcurrent().switch self.rawlink(switch) try: timer = Timeout._start_new_or_dummy(timeout) try: try: result = get_hub().switch() assert result is self, 'Invalid switch into Semaphore.wait/acquire(): %r' % (result, ) except Timeout as ex: if ex is not timer: raise return ex finally: timer.cancel() finally: self.unlink(switch)
Wait for up to *timeout* seconds to expire. If timeout elapses, return the exception. Otherwise, return None. Raises timeout if a different timer expires.
_do_wait
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_semaphore.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_semaphore.py
MIT
def wait(self, timeout=None): """ wait(timeout=None) -> int Wait until it is possible to acquire this semaphore, or until the optional *timeout* elapses. .. caution:: If this semaphore was initialized with a size of 0, this method will block forever if no timeout is given. :keyword float timeout: If given, specifies the maximum amount of seconds this method will block. :return: A number indicating how many times the semaphore can be acquired before blocking. """ if self.counter > 0: return self.counter self._do_wait(timeout) # return value irrelevant, whether we got it or got a timeout return self.counter
wait(timeout=None) -> int Wait until it is possible to acquire this semaphore, or until the optional *timeout* elapses. .. caution:: If this semaphore was initialized with a size of 0, this method will block forever if no timeout is given. :keyword float timeout: If given, specifies the maximum amount of seconds this method will block. :return: A number indicating how many times the semaphore can be acquired before blocking.
wait
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_semaphore.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_semaphore.py
MIT
def acquire(self, blocking=True, timeout=None): """ acquire(blocking=True, timeout=None) -> bool Acquire the semaphore. .. caution:: If this semaphore was initialized with a size of 0, this method will block forever (unless a timeout is given or blocking is set to false). :keyword bool blocking: If True (the default), this function will block until the semaphore is acquired. :keyword float timeout: If given, specifies the maximum amount of seconds this method will block. :return: A boolean indicating whether the semaphore was acquired. If ``blocking`` is True and ``timeout`` is None (the default), then (so long as this semaphore was initialized with a size greater than 0) this will always return True. If a timeout was given, and it expired before the semaphore was acquired, False will be returned. (Note that this can still raise a ``Timeout`` exception, if some other caller had already started a timer.) """ if self.counter > 0: self.counter -= 1 return True if not blocking: return False timeout = self._do_wait(timeout) if timeout is not None: # Our timer expired. return False # Neither our timer no another one expired, so we blocked until # awoke. Therefore, the counter is ours self.counter -= 1 assert self.counter >= 0 return True
acquire(blocking=True, timeout=None) -> bool Acquire the semaphore. .. caution:: If this semaphore was initialized with a size of 0, this method will block forever (unless a timeout is given or blocking is set to false). :keyword bool blocking: If True (the default), this function will block until the semaphore is acquired. :keyword float timeout: If given, specifies the maximum amount of seconds this method will block. :return: A boolean indicating whether the semaphore was acquired. If ``blocking`` is True and ``timeout`` is None (the default), then (so long as this semaphore was initialized with a size greater than 0) this will always return True. If a timeout was given, and it expired before the semaphore was acquired, False will be returned. (Note that this can still raise a ``Timeout`` exception, if some other caller had already started a timer.)
acquire
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_semaphore.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_semaphore.py
MIT
def _wait(self, watcher, timeout_exc=timeout('timed out')): """Block the current greenlet until *watcher* has pending events. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``. """ if watcher.callback is not None: raise _socketcommon.ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (watcher.callback, )) if self.timeout is not None: timeout = Timeout.start_new(self.timeout, timeout_exc, ref=False) else: timeout = None try: self.hub.wait(watcher) finally: if timeout is not None: timeout.cancel()
Block the current greenlet until *watcher* has pending events. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
_wait
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket2.py
MIT
def __send_chunk(self, data_memory, flags, timeleft, end): """ Send the complete contents of ``data_memory`` before returning. This is the core loop around :meth:`send`. :param timeleft: Either ``None`` if there is no timeout involved, or a float indicating the timeout to use. :param end: Either ``None`` if there is no timeout involved, or a float giving the absolute end time. :return: An updated value for ``timeleft`` (or None) :raises timeout: If ``timeleft`` was given and elapsed while sending this chunk. """ data_sent = 0 len_data_memory = len(data_memory) started_timer = 0 while data_sent < len_data_memory: chunk = data_memory[data_sent:] if timeleft is None: data_sent += self.send(chunk, flags) elif started_timer and timeleft <= 0: # Check before sending to guarantee a check # happens even if each chunk successfully sends its data # (especially important for SSL sockets since they have large # buffers) raise timeout('timed out') else: started_timer = 1 data_sent += self.send(chunk, flags, timeout=timeleft) timeleft = end - time.time() return timeleft
Send the complete contents of ``data_memory`` before returning. This is the core loop around :meth:`send`. :param timeleft: Either ``None`` if there is no timeout involved, or a float indicating the timeout to use. :param end: Either ``None`` if there is no timeout involved, or a float giving the absolute end time. :return: An updated value for ``timeleft`` (or None) :raises timeout: If ``timeleft`` was given and elapsed while sending this chunk.
__send_chunk
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket2.py
MIT
def __repr__(self): """Wrap __repr__() to reveal the real class name.""" try: s = _socket.socket.__repr__(self._sock) except Exception as ex: # Observed on Windows Py3.3, printing the repr of a socket # that just sufferred a ConnectionResetError [WinError 10054]: # "OverflowError: no printf formatter to display the socket descriptor in decimal" # Not sure what the actual cause is or if there's a better way to handle this s = '<socket [%r]>' % ex if s.startswith("<socket object"): s = "<%s.%s%s%s" % (self.__class__.__module__, self.__class__.__name__, getattr(self, '_closed', False) and " [closed] " or "", s[7:]) return s
Wrap __repr__() to reveal the real class name.
__repr__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket3.py
MIT
def _wait(self, watcher, timeout_exc=timeout('timed out')): """Block the current greenlet until *watcher* has pending events. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``. """ if watcher.callback is not None: raise _socketcommon.ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (watcher.callback, )) if self.timeout is not None: timeout = Timeout.start_new(self.timeout, timeout_exc, ref=False) else: timeout = None try: self.hub.wait(watcher) finally: if timeout is not None: timeout.cancel()
Block the current greenlet until *watcher* has pending events. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
_wait
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket3.py
MIT
def dup(self): """dup() -> socket object Return a new socket object connected to the same system resource. """ fd = dup(self.fileno()) sock = self.__class__(self.family, self.type, self.proto, fileno=fd) sock.settimeout(self.gettimeout()) return sock
dup() -> socket object Return a new socket object connected to the same system resource.
dup
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket3.py
MIT
def accept(self): """accept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. For IP sockets, the address info is a pair (hostaddr, port). """ while True: try: fd, addr = self._accept() break except BlockingIOError: if self.timeout == 0.0: raise self._wait(self._read_event) sock = socket(self.family, self.type, self.proto, fileno=fd) # Python Issue #7995: if no default timeout is set and the listening # socket had a (non-zero) timeout, force the new socket in blocking # mode to override platform-specific socket flags inheritance. # XXX do we need to do this? if getdefaulttimeout() is None and self.gettimeout(): sock.setblocking(True) return sock, addr
accept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. For IP sockets, the address info is a pair (hostaddr, port).
accept
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket3.py
MIT
def makefile(self, mode="r", buffering=None, *, encoding=None, errors=None, newline=None): """Return an I/O stream connected to the socket The arguments are as for io.open() after the filename, except the only mode characters supported are 'r', 'w' and 'b'. The semantics are similar too. """ # (XXX refactor to share code?) for c in mode: if c not in {"r", "w", "b"}: raise ValueError("invalid mode %r (only r, w, b allowed)") writing = "w" in mode reading = "r" in mode or not writing assert reading or writing binary = "b" in mode rawmode = "" if reading: rawmode += "r" if writing: rawmode += "w" raw = SocketIO(self, rawmode) self._io_refs += 1 if buffering is None: buffering = -1 if buffering < 0: buffering = io.DEFAULT_BUFFER_SIZE if buffering == 0: if not binary: raise ValueError("unbuffered streams must be binary") return raw if reading and writing: buffer = io.BufferedRWPair(raw, raw, buffering) elif reading: buffer = io.BufferedReader(raw, buffering) else: assert writing buffer = io.BufferedWriter(raw, buffering) if binary: return buffer text = io.TextIOWrapper(buffer, encoding, errors, newline) text.mode = mode return text
Return an I/O stream connected to the socket The arguments are as for io.open() after the filename, except the only mode characters supported are 'r', 'w' and 'b'. The semantics are similar too.
makefile
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket3.py
MIT
def fromfd(fd, family, type, proto=0): """ fromfd(fd, family, type[, proto]) -> socket object Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket(). """ nfd = dup(fd) return socket(family, type, proto, nfd)
fromfd(fd, family, type[, proto]) -> socket object Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket().
fromfd
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket3.py
MIT
def socketpair(family=None, type=SOCK_STREAM, proto=0): """socketpair([family[, type[, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET. """ if family is None: try: family = AF_UNIX except NameError: family = AF_INET a, b = _socket.socketpair(family, type, proto) a = socket(family, type, proto, a.detach()) b = socket(family, type, proto, b.detach()) return a, b
socketpair([family[, type[, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
socketpair
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socket3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socket3.py
MIT
def wait(io, timeout=None, timeout_exc=_NONE): """ Block the current greenlet until *io* is ready. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called on *io* by another greenlet, raise an exception in this blocking greenlet (``socket.error(EBADF, 'File descriptor was closed in another greenlet')`` by default). :param io: A libev watcher, most commonly an IO watcher obtained from :meth:`gevent.core.loop.io` :keyword timeout_exc: The exception to raise if the timeout expires. By default, a :class:`socket.timeout` exception is raised. If you pass a value for this keyword, it is interpreted as for :class:`gevent.timeout.Timeout`. """ if io.callback is not None: raise ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (io.callback, )) if timeout is not None: timeout_exc = timeout_exc if timeout_exc is not _NONE else _timeout_error('timed out') timeout = Timeout.start_new(timeout, timeout_exc) try: return get_hub().wait(io) finally: if timeout is not None: timeout.cancel() # rename "io" to "watcher" because wait() works with any watcher
Block the current greenlet until *io* is ready. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called on *io* by another greenlet, raise an exception in this blocking greenlet (``socket.error(EBADF, 'File descriptor was closed in another greenlet')`` by default). :param io: A libev watcher, most commonly an IO watcher obtained from :meth:`gevent.core.loop.io` :keyword timeout_exc: The exception to raise if the timeout expires. By default, a :class:`socket.timeout` exception is raised. If you pass a value for this keyword, it is interpreted as for :class:`gevent.timeout.Timeout`.
wait
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socketcommon.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socketcommon.py
MIT
def wait_read(fileno, timeout=None, timeout_exc=_NONE): """ Block the current greenlet until *fileno* is ready to read. For the meaning of the other parameters and possible exceptions, see :func:`wait`. .. seealso:: :func:`cancel_wait` """ io = get_hub().loop.io(fileno, 1) return wait(io, timeout, timeout_exc)
Block the current greenlet until *fileno* is ready to read. For the meaning of the other parameters and possible exceptions, see :func:`wait`. .. seealso:: :func:`cancel_wait`
wait_read
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socketcommon.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socketcommon.py
MIT
def wait_write(fileno, timeout=None, timeout_exc=_NONE, event=_NONE): """ Block the current greenlet until *fileno* is ready to write. For the meaning of the other parameters and possible exceptions, see :func:`wait`. :keyword event: Ignored. Applications should not pass this parameter. In the future, it may become an error. .. seealso:: :func:`cancel_wait` """ io = get_hub().loop.io(fileno, 2) return wait(io, timeout, timeout_exc)
Block the current greenlet until *fileno* is ready to write. For the meaning of the other parameters and possible exceptions, see :func:`wait`. :keyword event: Ignored. Applications should not pass this parameter. In the future, it may become an error. .. seealso:: :func:`cancel_wait`
wait_write
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socketcommon.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socketcommon.py
MIT
def wait_readwrite(fileno, timeout=None, timeout_exc=_NONE, event=_NONE): """ Block the current greenlet until *fileno* is ready to read or write. For the meaning of the other parameters and possible exceptions, see :func:`wait`. :keyword event: Ignored. Applications should not pass this parameter. In the future, it may become an error. .. seealso:: :func:`cancel_wait` """ io = get_hub().loop.io(fileno, 3) return wait(io, timeout, timeout_exc)
Block the current greenlet until *fileno* is ready to read or write. For the meaning of the other parameters and possible exceptions, see :func:`wait`. :keyword event: Ignored. Applications should not pass this parameter. In the future, it may become an error. .. seealso:: :func:`cancel_wait`
wait_readwrite
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socketcommon.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socketcommon.py
MIT
def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned. """ name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if isinstance(name, bytes): if b'.' in name: break elif '.' in name: break else: name = hostname return name
Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned.
getfqdn
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_socketcommon.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_socketcommon.py
MIT
def read(self, len=1024): """Read up to LEN bytes and return them. Return zero-length string on EOF.""" while True: try: return self._sslobj.read(len) except SSLError as ex: if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: return '' elif ex.args[0] == SSL_ERROR_WANT_READ: if self.timeout == 0.0: raise sys.exc_clear() self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout) elif ex.args[0] == SSL_ERROR_WANT_WRITE: if self.timeout == 0.0: raise sys.exc_clear() # note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout) else: raise
Read up to LEN bytes and return them. Return zero-length string on EOF.
read
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl2.py
MIT
def connect(self, addr): """Connects to remote ADDR, and then wraps the connection in an SSL channel.""" # Here we assume that the socket is client-side, and not # connected at the time of the call. We connect it, then wrap it. if self._sslobj: raise ValueError("attempt to connect already-connected SSLSocket!") socket.connect(self, addr) if self.ciphers is None: self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile, self.cert_reqs, self.ssl_version, self.ca_certs) else: self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile, self.cert_reqs, self.ssl_version, self.ca_certs, self.ciphers) if self.do_handshake_on_connect: self.do_handshake()
Connects to remote ADDR, and then wraps the connection in an SSL channel.
connect
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl2.py
MIT
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" sock = self._sock while True: try: client_socket, address = sock.accept() break except socket_error as ex: if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0: raise sys.exc_clear() self._wait(self._read_event) sslobj = SSLSocket(client_socket, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, ciphers=self.ciphers) return sslobj, address
Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.
accept
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl2.py
MIT
def makefile(self, mode='r', bufsize=-1): """Make and return a file-like object that works with the SSL connection. Just use the code from the socket module.""" if not PYPY: self._makefile_refs += 1 # close=True so as to decrement the reference count when done with # the file-like object. return _fileobject(self, mode, bufsize, close=True)
Make and return a file-like object that works with the SSL connection. Just use the code from the socket module.
makefile
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl2.py
MIT
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.""" host, port = addr if (ca_certs is not None): cert_reqs = CERT_REQUIRED else: cert_reqs = CERT_NONE s = wrap_socket(socket(), ssl_version=ssl_version, cert_reqs=cert_reqs, ca_certs=ca_certs) s.connect(addr) dercert = s.getpeercert(True) s.close() return DER_cert_to_PEM_cert(dercert)
Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.
get_server_certificate
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl2.py
MIT
def read(self, len=1024, buffer=None): """Read up to LEN bytes and return them. Return zero-length string on EOF.""" self._checkClosed() if not self._sslobj: raise ValueError("Read on closed or unwrapped SSL socket.") while True: try: if buffer is not None: return self._sslobj.read(len, buffer) else: return self._sslobj.read(len or 1024) except SSLWantReadError: if self.timeout == 0.0: raise self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout) except SSLWantWriteError: if self.timeout == 0.0: raise # note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout) except SSLError as ex: if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: if buffer is None: return b'' else: return 0 else: raise
Read up to LEN bytes and return them. Return zero-length string on EOF.
read
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl3.py
MIT
def getpeercert(self, binary_form=False): """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.""" self._checkClosed() self._check_connected() return self._sslobj.peer_certificate(binary_form)
Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.
getpeercert
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl3.py
MIT
def version(self): """Return a string identifying the protocol version used by the current SSL channel. """ if not self._sslobj: return None return self._sslobj.version()
Return a string identifying the protocol version used by the current SSL channel.
version
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl3.py
MIT
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) newsock = self.context.wrap_socket(newsock, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, server_side=True) return newsock, addr
Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.
accept
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl3.py
MIT
def get_channel_binding(self, cb_type="tls-unique"): """Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake). """ if cb_type not in CHANNEL_BINDING_TYPES: raise ValueError("Unsupported channel binding type") if cb_type != "tls-unique": raise NotImplementedError("{0} channel binding type not implemented".format(cb_type)) if self._sslobj is None: return None return self._sslobj.tls_unique_cb()
Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).
get_channel_binding
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl3.py
MIT
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.""" host, port = addr if (ca_certs is not None): cert_reqs = CERT_REQUIRED else: cert_reqs = CERT_NONE s = create_connection(addr) s = wrap_socket(s, ssl_version=ssl_version, cert_reqs=cert_reqs, ca_certs=ca_certs) dercert = s.getpeercert(True) s.close() return DER_cert_to_PEM_cert(dercert)
Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.
get_server_certificate
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_ssl3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_ssl3.py
MIT
def create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None): """Create a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum compatibility and security. """ if not isinstance(purpose, _ASN1Object): raise TypeError(purpose) context = SSLContext(PROTOCOL_SSLv23) # SSLv2 considered harmful. context.options |= OP_NO_SSLv2 # SSLv3 has problematic security and is only required for really old # clients such as IE6 on Windows XP context.options |= OP_NO_SSLv3 # disable compression to prevent CRIME attacks (OpenSSL 1.0+) context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0) if purpose == Purpose.SERVER_AUTH: # verify certs and host name in client mode context.verify_mode = CERT_REQUIRED context.check_hostname = True elif purpose == Purpose.CLIENT_AUTH: # Prefer the server's ciphers by default so that we get stronger # encryption context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0) # Use single use keys in order to improve forward secrecy context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0) context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0) # disallow ciphers with known vulnerabilities context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) if cafile or capath or cadata: context.load_verify_locations(cafile, capath, cadata) elif context.verify_mode != CERT_NONE: # no explicit cafile, capath or cadata but the verify mode is # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system # root CA certificates for the given purpose. This may fail silently. context.load_default_certs(purpose) return context
Create a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum compatibility and security.
create_default_context
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def _create_unverified_context(protocol=PROTOCOL_SSLv23, cert_reqs=None, check_hostname=False, purpose=Purpose.SERVER_AUTH, certfile=None, keyfile=None, cafile=None, capath=None, cadata=None): """Create a SSLContext object for Python stdlib modules All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration is less restrict than create_default_context()'s to increase backward compatibility. """ if not isinstance(purpose, _ASN1Object): raise TypeError(purpose) context = SSLContext(protocol) # SSLv2 considered harmful. context.options |= OP_NO_SSLv2 # SSLv3 has problematic security and is only required for really old # clients such as IE6 on Windows XP context.options |= OP_NO_SSLv3 if cert_reqs is not None: context.verify_mode = cert_reqs context.check_hostname = check_hostname if keyfile and not certfile: raise ValueError("certfile must be specified") if certfile or keyfile: context.load_cert_chain(certfile, keyfile) # load CA root certs if cafile or capath or cadata: context.load_verify_locations(cafile, capath, cadata) elif context.verify_mode != CERT_NONE: # no explicit cafile, capath or cadata but the verify mode is # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system # root CA certificates for the given purpose. This may fail silently. context.load_default_certs(purpose) return context
Create a SSLContext object for Python stdlib modules All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration is less restrict than create_default_context()'s to increase backward compatibility.
_create_unverified_context
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def read(self, len=0, buffer=None): """Read up to LEN bytes and return them. Return zero-length string on EOF.""" self._checkClosed() if not self._sslobj: raise ValueError("Read on closed or unwrapped SSL socket.") while True: try: if buffer is not None: return self._sslobj.read(len, buffer) else: return self._sslobj.read(len or 1024) except SSLWantReadError: if self.timeout == 0.0: raise self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout) except SSLWantWriteError: if self.timeout == 0.0: raise # note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout) except SSLError as ex: if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: if buffer is not None: return 0 else: return b'' else: raise
Read up to LEN bytes and return them. Return zero-length string on EOF.
read
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def getpeercert(self, binary_form=False): """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.""" self._checkClosed() self._check_connected() return self._sslobj.peer_certificate(binary_form)
Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.
getpeercert
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) newsock = self.context.wrap_socket(newsock, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, server_side=True) return newsock, addr
Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.
accept
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def makefile(self, mode='r', bufsize=-1): """Make and return a file-like object that works with the SSL connection. Just use the code from the socket module.""" if not PYPY: self._makefile_refs += 1 # close=True so as to decrement the reference count when done with # the file-like object. return _fileobject(self, mode, bufsize, close=True)
Make and return a file-like object that works with the SSL connection. Just use the code from the socket module.
makefile
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def get_channel_binding(self, cb_type="tls-unique"): """Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake). """ if cb_type not in CHANNEL_BINDING_TYPES: raise ValueError("Unsupported channel binding type") if cb_type != "tls-unique": raise NotImplementedError( "{0} channel binding type not implemented" .format(cb_type)) if self._sslobj is None: return None return self._sslobj.tls_unique_cb()
Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).
get_channel_binding
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def version(self): """ Return a string identifying the protocol version used by the current SSL channel, or None if there is no established channel. """ if self._sslobj is None: return None return self._sslobj.version()
Return a string identifying the protocol version used by the current SSL channel, or None if there is no established channel.
version
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.""" host, port = addr if ca_certs is not None: cert_reqs = CERT_REQUIRED else: cert_reqs = CERT_NONE context = _create_stdlib_context(ssl_version, cert_reqs=cert_reqs, cafile=ca_certs) with closing(create_connection(addr)) as sock: with closing(context.wrap_socket(sock)) as sslsock: dercert = sslsock.getpeercert(True) return DER_cert_to_PEM_cert(dercert)
Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.
get_server_certificate
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_sslgte279.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_sslgte279.py
MIT
def _init_ugly_crap(): """This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. Do not attempt to use this on non cpython interpreters """ import ctypes from types import TracebackType # figure out side of _Py_ssize_t if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'): _Py_ssize_t = ctypes.c_int64 else: _Py_ssize_t = ctypes.c_int # regular python class _PyObject(ctypes.Structure): pass _PyObject._fields_ = [ ('ob_refcnt', _Py_ssize_t), ('ob_type', ctypes.POINTER(_PyObject)) ] # python with trace if hasattr(sys, 'getobjects'): class _PyObject(ctypes.Structure): pass _PyObject._fields_ = [ ('_ob_next', ctypes.POINTER(_PyObject)), ('_ob_prev', ctypes.POINTER(_PyObject)), ('ob_refcnt', _Py_ssize_t), ('ob_type', ctypes.POINTER(_PyObject)) ] class _Traceback(_PyObject): pass _Traceback._fields_ = [ ('tb_next', ctypes.POINTER(_Traceback)), ('tb_frame', ctypes.POINTER(_PyObject)), ('tb_lasti', ctypes.c_int), ('tb_lineno', ctypes.c_int) ] def tb_set_next(tb, next): """Set the tb_next attribute of a traceback object.""" if not (isinstance(tb, TracebackType) and (next is None or isinstance(next, TracebackType))): raise TypeError('tb_set_next arguments must be traceback objects') obj = _Traceback.from_address(id(tb)) if tb.tb_next is not None: old = _Traceback.from_address(id(tb.tb_next)) old.ob_refcnt -= 1 if next is None: obj.tb_next = ctypes.POINTER(_Traceback)() else: next = _Traceback.from_address(id(next)) next.ob_refcnt += 1 obj.tb_next = ctypes.pointer(next) return tb_set_next
This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. Do not attempt to use this on non cpython interpreters
_init_ugly_crap
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_tblib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_tblib.py
MIT
def tb_set_next(tb, next): """Set the tb_next attribute of a traceback object.""" if not (isinstance(tb, TracebackType) and (next is None or isinstance(next, TracebackType))): raise TypeError('tb_set_next arguments must be traceback objects') obj = _Traceback.from_address(id(tb)) if tb.tb_next is not None: old = _Traceback.from_address(id(tb.tb_next)) old.ob_refcnt -= 1 if next is None: obj.tb_next = ctypes.POINTER(_Traceback)() else: next = _Traceback.from_address(id(next)) next.ob_refcnt += 1 obj.tb_next = ctypes.pointer(next)
Set the tb_next attribute of a traceback object.
tb_set_next
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_tblib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_tblib.py
MIT
def task_done(self): """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. """ self.all_tasks_done.acquire() try: unfinished = self.unfinished_tasks - 1 if unfinished <= 0: if unfinished < 0: raise ValueError('task_done() called too many times') self.all_tasks_done.notify_all() self.unfinished_tasks = unfinished finally: self.all_tasks_done.release()
Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue.
task_done
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_threading.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_threading.py
MIT
def join(self): """Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. """ self.all_tasks_done.acquire() try: while self.unfinished_tasks: self.all_tasks_done.wait() finally: self.all_tasks_done.release()
Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.
join
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_threading.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_threading.py
MIT
def qsize(self): """Return the approximate size of the queue (not reliable!).""" self.mutex.acquire() try: return self._qsize() finally: self.mutex.release()
Return the approximate size of the queue (not reliable!).
qsize
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_threading.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_threading.py
MIT
def empty(self): """Return True if the queue is empty, False otherwise (not reliable!).""" self.mutex.acquire() try: return not self._qsize() finally: self.mutex.release()
Return True if the queue is empty, False otherwise (not reliable!).
empty
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_threading.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_threading.py
MIT
def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() try: if self.maxsize <= 0: return False if self.maxsize >= self._qsize(): return True finally: self.mutex.release()
Return True if the queue is full, False otherwise (not reliable!).
full
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_threading.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_threading.py
MIT
def put(self, item, block=True, timeout=None): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case). """ self.not_full.acquire() try: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a positive number") else: endtime = _time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - _time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 self.not_empty.notify() finally: self.not_full.release()
Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case).
put
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_threading.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_threading.py
MIT
def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). """ self.not_empty.acquire() try: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a positive number") else: endtime = _time() + timeout while not self._qsize(): remaining = endtime - _time() if remaining <= 0.0: raise Empty self.not_empty.wait(remaining) item = self._get() self.not_full.notify() return item finally: self.not_empty.release()
Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case).
get
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/gevent/_threading.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/_threading.py
MIT
def __new__(self, projparams=None, preserve_units=False, **kwargs): """ initialize a Proj class instance. Proj4 projection control parameters must either be given in a dictionary 'projparams' or as keyword arguments. See the proj documentation (http://trac.osgeo.org/proj/) for more information about specifying projection parameters. Example usage: >>> from pyproj import Proj >>> p = Proj(proj='utm',zone=10,ellps='WGS84') # use kwargs >>> x,y = p(-120.108, 34.36116666) >>> 'x=%9.3f y=%11.3f' % (x,y) 'x=765975.641 y=3805993.134' >>> 'lon=%8.3f lat=%5.3f' % p(x,y,inverse=True) 'lon=-120.108 lat=34.361' >>> # do 3 cities at a time in a tuple (Fresno, LA, SF) >>> lons = (-119.72,-118.40,-122.38) >>> lats = (36.77, 33.93, 37.62 ) >>> x,y = p(lons, lats) >>> 'x: %9.3f %9.3f %9.3f' % x 'x: 792763.863 925321.537 554714.301' >>> 'y: %9.3f %9.3f %9.3f' % y 'y: 4074377.617 3763936.941 4163835.303' >>> lons, lats = p(x, y, inverse=True) # inverse transform >>> 'lons: %8.3f %8.3f %8.3f' % lons 'lons: -119.720 -118.400 -122.380' >>> 'lats: %8.3f %8.3f %8.3f' % lats 'lats: 36.770 33.930 37.620' >>> p2 = Proj('+proj=utm +zone=10 +ellps=WGS84') # use proj4 string >>> x,y = p2(-120.108, 34.36116666) >>> 'x=%9.3f y=%11.3f' % (x,y) 'x=765975.641 y=3805993.134' >>> p = Proj(init="epsg:32667") >>> 'x=%12.3f y=%12.3f (meters)' % p(-114.057222, 51.045) 'x=-1783486.760 y= 6193833.196 (meters)' >>> p = Proj("+init=epsg:32667",preserve_units=True) >>> 'x=%12.3f y=%12.3f (feet)' % p(-114.057222, 51.045) 'x=-5851322.810 y=20320934.409 (feet)' >>> p = Proj(proj='hammer') # hammer proj and inverse >>> x,y = p(-30,40) >>> 'x=%12.3f y=%12.3f' % (x,y) 'x=-2711575.083 y= 4395506.619' >>> lon,lat = p(x,y,inverse=True) >>> 'lon=%9.3f lat=%9.3f (degrees)' % (lon,lat) 'lon= -30.000 lat= 40.000 (degrees)' """ # if projparams is None, use kwargs. if projparams is None: if len(kwargs) == 0: raise RuntimeError('no projection control parameters specified') else: projstring = _dict2string(kwargs) elif isinstance(projparams, string_types): # if projparams is a string or a unicode string, interpret as a proj4 init string. projstring = projparams else: # projparams a dict projstring = _dict2string(projparams) # make sure units are meters if preserve_units is False. if not projstring.count('+units=') and not preserve_units: projstring = '+units=m '+projstring else: kvpairs = [] for kvpair in projstring.split(): if kvpair.startswith('+units') and not preserve_units: k,v = kvpair.split('=') kvpairs.append(k+'=m ') else: kvpairs.append(kvpair+' ') projstring = ''.join(kvpairs) # look for EPSG, replace with epsg (EPSG only works # on case-insensitive filesystems). projstring = projstring.replace('EPSG','epsg') return _proj.Proj.__new__(self, projstring)
initialize a Proj class instance. Proj4 projection control parameters must either be given in a dictionary 'projparams' or as keyword arguments. See the proj documentation (http://trac.osgeo.org/proj/) for more information about specifying projection parameters. Example usage: >>> from pyproj import Proj >>> p = Proj(proj='utm',zone=10,ellps='WGS84') # use kwargs >>> x,y = p(-120.108, 34.36116666) >>> 'x=%9.3f y=%11.3f' % (x,y) 'x=765975.641 y=3805993.134' >>> 'lon=%8.3f lat=%5.3f' % p(x,y,inverse=True) 'lon=-120.108 lat=34.361' >>> # do 3 cities at a time in a tuple (Fresno, LA, SF) >>> lons = (-119.72,-118.40,-122.38) >>> lats = (36.77, 33.93, 37.62 ) >>> x,y = p(lons, lats) >>> 'x: %9.3f %9.3f %9.3f' % x 'x: 792763.863 925321.537 554714.301' >>> 'y: %9.3f %9.3f %9.3f' % y 'y: 4074377.617 3763936.941 4163835.303' >>> lons, lats = p(x, y, inverse=True) # inverse transform >>> 'lons: %8.3f %8.3f %8.3f' % lons 'lons: -119.720 -118.400 -122.380' >>> 'lats: %8.3f %8.3f %8.3f' % lats 'lats: 36.770 33.930 37.620' >>> p2 = Proj('+proj=utm +zone=10 +ellps=WGS84') # use proj4 string >>> x,y = p2(-120.108, 34.36116666) >>> 'x=%9.3f y=%11.3f' % (x,y) 'x=765975.641 y=3805993.134' >>> p = Proj(init="epsg:32667") >>> 'x=%12.3f y=%12.3f (meters)' % p(-114.057222, 51.045) 'x=-1783486.760 y= 6193833.196 (meters)' >>> p = Proj("+init=epsg:32667",preserve_units=True) >>> 'x=%12.3f y=%12.3f (feet)' % p(-114.057222, 51.045) 'x=-5851322.810 y=20320934.409 (feet)' >>> p = Proj(proj='hammer') # hammer proj and inverse >>> x,y = p(-30,40) >>> 'x=%12.3f y=%12.3f' % (x,y) 'x=-2711575.083 y= 4395506.619' >>> lon,lat = p(x,y,inverse=True) >>> 'lon=%9.3f lat=%9.3f (degrees)' % (lon,lat) 'lon= -30.000 lat= 40.000 (degrees)'
__new__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/pyproj/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/pyproj/__init__.py
MIT
def __call__(self, *args, **kw): #,lon,lat,inverse=False,radians=False,errcheck=False): """ Calling a Proj class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y native map projection coordinates (in meters). If optional keyword 'inverse' is True (default is False), the inverse transformation from x/y to lon/lat is performed. If optional keyword 'radians' is True (default is False) the units of lon/lat are radians instead of degrees. If optional keyword 'errcheck' is True (default is False) an exception is raised if the transformation is invalid. If errcheck=False and the transformation is invalid, no exception is raised and 1.e30 is returned. Inputs should be doubles (they will be cast to doubles if they are not, causing a slight performance hit). Works with numpy and regular python array objects, python sequences and scalars, but is fastest for array objects. """ inverse = kw.get('inverse', False) radians = kw.get('radians', False) errcheck = kw.get('errcheck', False) #if len(args) == 1: # latlon = np.array(args[0], copy=True, # order='C', dtype=float, ndmin=2) # if inverse: # _proj.Proj._invn(self, latlon, radians=radians, errcheck=errcheck) # else: # _proj.Proj._fwdn(self, latlon, radians=radians, errcheck=errcheck) # return latlon lon, lat = args # process inputs, making copies that support buffer API. inx, xisfloat, xislist, xistuple = _copytobuffer(lon) iny, yisfloat, yislist, yistuple = _copytobuffer(lat) # call proj4 functions. inx and iny modified in place. if inverse: _proj.Proj._inv(self, inx, iny, radians=radians, errcheck=errcheck) else: _proj.Proj._fwd(self, inx, iny, radians=radians, errcheck=errcheck) # if inputs were lists, tuples or floats, convert back. outx = _convertback(xisfloat,xislist,xistuple,inx) outy = _convertback(yisfloat,yislist,xistuple,iny) return outx, outy
Calling a Proj class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y native map projection coordinates (in meters). If optional keyword 'inverse' is True (default is False), the inverse transformation from x/y to lon/lat is performed. If optional keyword 'radians' is True (default is False) the units of lon/lat are radians instead of degrees. If optional keyword 'errcheck' is True (default is False) an exception is raised if the transformation is invalid. If errcheck=False and the transformation is invalid, no exception is raised and 1.e30 is returned. Inputs should be doubles (they will be cast to doubles if they are not, causing a slight performance hit). Works with numpy and regular python array objects, python sequences and scalars, but is fastest for array objects.
__call__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/pyproj/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/pyproj/__init__.py
MIT
def transform(p1, p2, x, y, z=None, radians=False): """ x2, y2, z2 = transform(p1, p2, x1, y1, z1, radians=False) Transform points between two coordinate systems defined by the Proj instances p1 and p2. The points x1,y1,z1 in the coordinate system defined by p1 are transformed to x2,y2,z2 in the coordinate system defined by p2. z1 is optional, if it is not set it is assumed to be zero (and only x2 and y2 are returned). In addition to converting between cartographic and geographic projection coordinates, this function can take care of datum shifts (which cannot be done using the __call__ method of the Proj instances). It also allows for one of the coordinate systems to be geographic (proj = 'latlong'). If optional keyword 'radians' is True (default is False) and p1 is defined in geographic coordinate (pj.is_latlong() is True), x1,y1 is interpreted as radians instead of the default degrees. Similarly, if p2 is defined in geographic coordinates and radians=True, x2, y2 are returned in radians instead of degrees. if p1.is_latlong() and p2.is_latlong() both are False, the radians keyword has no effect. x,y and z can be numpy or regular python arrays, python lists/tuples or scalars. Arrays are fastest. For projections in geocentric coordinates, values of x and y are given in meters. z is always meters. Example usage: >>> # projection 1: UTM zone 15, grs80 ellipse, NAD83 datum >>> # (defined by epsg code 26915) >>> p1 = Proj(init='epsg:26915') >>> # projection 2: UTM zone 15, clrk66 ellipse, NAD27 datum >>> p2 = Proj(init='epsg:26715') >>> # find x,y of Jefferson City, MO. >>> x1, y1 = p1(-92.199881,38.56694) >>> # transform this point to projection 2 coordinates. >>> x2, y2 = transform(p1,p2,x1,y1) >>> '%9.3f %11.3f' % (x1,y1) '569704.566 4269024.671' >>> '%9.3f %11.3f' % (x2,y2) '569722.342 4268814.027' >>> '%8.3f %5.3f' % p2(x2,y2,inverse=True) ' -92.200 38.567' >>> # process 3 points at a time in a tuple >>> lats = (38.83,39.32,38.75) # Columbia, KC and StL Missouri >>> lons = (-92.22,-94.72,-90.37) >>> x1, y1 = p1(lons,lats) >>> x2, y2 = transform(p1,p2,x1,y1) >>> xy = x1+y1 >>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy '567703.344 351730.944 728553.093 4298200.739 4353698.725 4292319.005' >>> xy = x2+y2 >>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy '567721.149 351747.558 728569.133 4297989.112 4353489.644 4292106.305' >>> lons, lats = p2(x2,y2,inverse=True) >>> xy = lons+lats >>> '%8.3f %8.3f %8.3f %5.3f %5.3f %5.3f' % xy ' -92.220 -94.720 -90.370 38.830 39.320 38.750' >>> # test datum shifting, installation of extra datum grid files. >>> p1 = Proj(proj='latlong',datum='WGS84') >>> x1 = -111.5; y1 = 45.25919444444 >>> p2 = Proj(proj="utm",zone=10,datum='NAD27') >>> x2, y2 = transform(p1, p2, x1, y1) >>> "%s %s" % (str(x2)[:9],str(y2)[:9]) '1402285.9 5076292.4' """ # check that p1 and p2 are from the Proj class if not isinstance(p1, Proj): raise TypeError("p1 must be a Proj class") if not isinstance(p2, Proj): raise TypeError("p2 must be a Proj class") # process inputs, making copies that support buffer API. inx, xisfloat, xislist, xistuple = _copytobuffer(x) iny, yisfloat, yislist, yistuple = _copytobuffer(y) if z is not None: inz, zisfloat, zislist, zistuple = _copytobuffer(z) else: inz = None # call pj_transform. inx,iny,inz buffers modified in place. _proj._transform(p1,p2,inx,iny,inz,radians) # if inputs were lists, tuples or floats, convert back. outx = _convertback(xisfloat,xislist,xistuple,inx) outy = _convertback(yisfloat,yislist,xistuple,iny) if inz is not None: outz = _convertback(zisfloat,zislist,zistuple,inz) return outx, outy, outz else: return outx, outy
x2, y2, z2 = transform(p1, p2, x1, y1, z1, radians=False) Transform points between two coordinate systems defined by the Proj instances p1 and p2. The points x1,y1,z1 in the coordinate system defined by p1 are transformed to x2,y2,z2 in the coordinate system defined by p2. z1 is optional, if it is not set it is assumed to be zero (and only x2 and y2 are returned). In addition to converting between cartographic and geographic projection coordinates, this function can take care of datum shifts (which cannot be done using the __call__ method of the Proj instances). It also allows for one of the coordinate systems to be geographic (proj = 'latlong'). If optional keyword 'radians' is True (default is False) and p1 is defined in geographic coordinate (pj.is_latlong() is True), x1,y1 is interpreted as radians instead of the default degrees. Similarly, if p2 is defined in geographic coordinates and radians=True, x2, y2 are returned in radians instead of degrees. if p1.is_latlong() and p2.is_latlong() both are False, the radians keyword has no effect. x,y and z can be numpy or regular python arrays, python lists/tuples or scalars. Arrays are fastest. For projections in geocentric coordinates, values of x and y are given in meters. z is always meters. Example usage: >>> # projection 1: UTM zone 15, grs80 ellipse, NAD83 datum >>> # (defined by epsg code 26915) >>> p1 = Proj(init='epsg:26915') >>> # projection 2: UTM zone 15, clrk66 ellipse, NAD27 datum >>> p2 = Proj(init='epsg:26715') >>> # find x,y of Jefferson City, MO. >>> x1, y1 = p1(-92.199881,38.56694) >>> # transform this point to projection 2 coordinates. >>> x2, y2 = transform(p1,p2,x1,y1) >>> '%9.3f %11.3f' % (x1,y1) '569704.566 4269024.671' >>> '%9.3f %11.3f' % (x2,y2) '569722.342 4268814.027' >>> '%8.3f %5.3f' % p2(x2,y2,inverse=True) ' -92.200 38.567' >>> # process 3 points at a time in a tuple >>> lats = (38.83,39.32,38.75) # Columbia, KC and StL Missouri >>> lons = (-92.22,-94.72,-90.37) >>> x1, y1 = p1(lons,lats) >>> x2, y2 = transform(p1,p2,x1,y1) >>> xy = x1+y1 >>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy '567703.344 351730.944 728553.093 4298200.739 4353698.725 4292319.005' >>> xy = x2+y2 >>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy '567721.149 351747.558 728569.133 4297989.112 4353489.644 4292106.305' >>> lons, lats = p2(x2,y2,inverse=True) >>> xy = lons+lats >>> '%8.3f %8.3f %8.3f %5.3f %5.3f %5.3f' % xy ' -92.220 -94.720 -90.370 38.830 39.320 38.750' >>> # test datum shifting, installation of extra datum grid files. >>> p1 = Proj(proj='latlong',datum='WGS84') >>> x1 = -111.5; y1 = 45.25919444444 >>> p2 = Proj(proj="utm",zone=10,datum='NAD27') >>> x2, y2 = transform(p1, p2, x1, y1) >>> "%s %s" % (str(x2)[:9],str(y2)[:9]) '1402285.9 5076292.4'
transform
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/pyproj/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/pyproj/__init__.py
MIT
def _copytobuffer(x): """ return a copy of x as an object that supports the python Buffer API (python array if input is float, list or tuple, numpy array if input is a numpy array). returns copyofx, isfloat, islist, istuple (islist is True if input is a list, istuple is true if input is a tuple, isfloat is true if input is a float). """ # make sure x supports Buffer API and contains doubles. isfloat = False; islist = False; istuple = False # first, if it's a numpy array scalar convert to float # (array scalars don't support buffer API) if hasattr(x,'shape'): if x.shape == (): return _copytobuffer_return_scalar(x) else: try: # typecast numpy arrays to double. # (this makes a copy - which is crucial # since buffer is modified in place) x.dtype.char # Basemap issue # https://github.com/matplotlib/basemap/pull/223/files # (deal with input array in fortran order) inx = x.copy(order="C").astype('d') # inx,isfloat,islist,istuple return inx,False,False,False except: try: # perhaps they are Numeric/numarrays? # sorry, not tested yet. # i don't know Numeric/numarrays has `shape'. x.typecode() inx = x.astype('d') # inx,isfloat,islist,istuple return inx,False,False,False except: raise TypeError('input must be an array, list, tuple or scalar') else: # perhaps they are regular python arrays? if hasattr(x, 'typecode'): #x.typecode inx = array('d',x) # try to convert to python array # a list. elif type(x) == list: inx = array('d',x) islist = True # a tuple. elif type(x) == tuple: inx = array('d',x) istuple = True # a scalar? else: return _copytobuffer_return_scalar(x) return inx,isfloat,islist,istuple
return a copy of x as an object that supports the python Buffer API (python array if input is float, list or tuple, numpy array if input is a numpy array). returns copyofx, isfloat, islist, istuple (islist is True if input is a list, istuple is true if input is a tuple, isfloat is true if input is a float).
_copytobuffer
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/pyproj/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/pyproj/__init__.py
MIT
def __new__(self, initstring=None, **kwargs): """ initialize a Geod class instance. Geodetic parameters for specifying the ellipsoid can be given in a dictionary 'initparams', as keyword arguments, or as as proj4 geod initialization string. Following is a list of the ellipsoids that may be defined using the 'ellps' keyword (these are stored in the model variable pj_ellps):: MERIT a=6378137.0 rf=298.257 MERIT 1983 SGS85 a=6378136.0 rf=298.257 Soviet Geodetic System 85 GRS80 a=6378137.0 rf=298.257222101 GRS 1980(IUGG, 1980) IAU76 a=6378140.0 rf=298.257 IAU 1976 airy a=6377563.396 b=6356256.910 Airy 1830 APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965 airy a=6377563.396 b=6356256.910 Airy 1830 APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965 NWL9D a=6378145.0. rf=298.25 Naval Weapons Lab., 1965 mod_airy a=6377340.189 b=6356034.446 Modified Airy andrae a=6377104.43 rf=300.0 Andrae 1876 (Den., Iclnd.) aust_SA a=6378160.0 rf=298.25 Australian Natl & S. Amer. 1969 GRS67 a=6378160.0 rf=298.247167427 GRS 67(IUGG 1967) bessel a=6377397.155 rf=299.1528128 Bessel 1841 bess_nam a=6377483.865 rf=299.1528128 Bessel 1841 (Namibia) clrk66 a=6378206.4 b=6356583.8 Clarke 1866 clrk80 a=6378249.145 rf=293.4663 Clarke 1880 mod. CPM a=6375738.7 rf=334.29 Comm. des Poids et Mesures 1799 delmbr a=6376428. rf=311.5 Delambre 1810 (Belgium) engelis a=6378136.05 rf=298.2566 Engelis 1985 evrst30 a=6377276.345 rf=300.8017 Everest 1830 evrst48 a=6377304.063 rf=300.8017 Everest 1948 evrst56 a=6377301.243 rf=300.8017 Everest 1956 evrst69 a=6377295.664 rf=300.8017 Everest 1969 evrstSS a=6377298.556 rf=300.8017 Everest (Sabah & Sarawak) fschr60 a=6378166. rf=298.3 Fischer (Mercury Datum) 1960 fschr60m a=6378155. rf=298.3 Modified Fischer 1960 fschr68 a=6378150. rf=298.3 Fischer 1968 helmert a=6378200. rf=298.3 Helmert 1906 hough a=6378270.0 rf=297. Hough helmert a=6378200. rf=298.3 Helmert 1906 hough a=6378270.0 rf=297. Hough intl a=6378388.0 rf=297. International 1909 (Hayford) krass a=6378245.0 rf=298.3 Krassovsky, 1942 kaula a=6378163. rf=298.24 Kaula 1961 lerch a=6378139. rf=298.257 Lerch 1979 mprts a=6397300. rf=191. Maupertius 1738 new_intl a=6378157.5 b=6356772.2 New International 1967 plessis a=6376523. b=6355863. Plessis 1817 (France) SEasia a=6378155.0 b=6356773.3205 Southeast Asia walbeck a=6376896.0 b=6355834.8467 Walbeck WGS60 a=6378165.0 rf=298.3 WGS 60 WGS66 a=6378145.0 rf=298.25 WGS 66 WGS72 a=6378135.0 rf=298.26 WGS 72 WGS84 a=6378137.0 rf=298.257223563 WGS 84 sphere a=6370997.0 b=6370997.0 Normal Sphere (r=6370997) The parameters of the ellipsoid may also be set directly using the 'a' (semi-major or equatorial axis radius) keyword, and any one of the following keywords: 'b' (semi-minor, or polar axis radius), 'e' (eccentricity), 'es' (eccentricity squared), 'f' (flattening), or 'rf' (reciprocal flattening). See the proj documentation (http://trac.osgeo.org/proj/) for more See the proj documentation (http://trac.osgeo.org/proj/) for more information about specifying ellipsoid parameters (specifically, the chapter 'Specifying the Earth's figure' in the main Proj users manual). Example usage: >>> from pyproj import Geod >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. >>> # specify the lat/lons of some cities. >>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.) >>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.) >>> newyork_lat = 40.+(47./60.); newyork_lon = -73.-(58./60.) >>> london_lat = 51.+(32./60.); london_lon = -(5./60.) >>> # compute forward and back azimuths, plus distance >>> # between Boston and Portland. >>> az12,az21,dist = g.inv(boston_lon,boston_lat,portland_lon,portland_lat) >>> "%7.3f %6.3f %12.3f" % (az12,az21,dist) '-66.531 75.654 4164192.708' >>> # compute latitude, longitude and back azimuth of Portland, >>> # given Boston lat/lon, forward azimuth and distance to Portland. >>> endlon, endlat, backaz = g.fwd(boston_lon, boston_lat, az12, dist) >>> "%6.3f %6.3f %13.3f" % (endlat,endlon,backaz) '45.517 -123.683 75.654' >>> # compute the azimuths, distances from New York to several >>> # cities (pass a list) >>> lons1 = 3*[newyork_lon]; lats1 = 3*[newyork_lat] >>> lons2 = [boston_lon, portland_lon, london_lon] >>> lats2 = [boston_lat, portland_lat, london_lat] >>> az12,az21,dist = g.inv(lons1,lats1,lons2,lats2) >>> for faz,baz,d in list(zip(az12,az21,dist)): "%7.3f %7.3f %9.3f" % (faz,baz,d) ' 54.663 -123.448 288303.720' '-65.463 79.342 4013037.318' ' 51.254 -71.576 5579916.651' >>> g2 = Geod('+ellps=clrk66') # use proj4 style initialization string >>> az12,az21,dist = g2.inv(boston_lon,boston_lat,portland_lon,portland_lat) >>> "%7.3f %6.3f %12.3f" % (az12,az21,dist) '-66.531 75.654 4164192.708' """ # if initparams is a proj-type init string, # convert to dict. ellpsd = {} if initstring is not None: for kvpair in initstring.split(): # Actually only +a and +b are needed # We can ignore safely any parameter that doesn't have a value if kvpair.find('=') == -1: continue k,v = kvpair.split('=') k = k.lstrip('+') if k in ['a','b','rf','f','es','e']: v = float(v) ellpsd[k] = v # merge this dict with kwargs dict. kwargs = dict(list(kwargs.items()) + list(ellpsd.items())) self.sphere = False if 'ellps' in kwargs: # ellipse name given, look up in pj_ellps dict ellps_dict = pj_ellps[kwargs['ellps']] a = ellps_dict['a'] if ellps_dict['description']=='Normal Sphere': self.sphere = True if 'b' in ellps_dict: b = ellps_dict['b'] es = 1. - (b * b) / (a * a) f = (a - b)/a elif 'rf' in ellps_dict: f = 1./ellps_dict['rf'] b = a*(1. - f) es = 1. - (b * b) / (a * a) else: # a (semi-major axis) and one of # b the semi-minor axis # rf the reciprocal flattening # f flattening # es eccentricity squared # must be given. a = kwargs['a'] if 'b' in kwargs: b = kwargs['b'] es = 1. - (b * b) / (a * a) f = (a - b)/a elif 'rf' in kwargs: f = 1./kwargs['rf'] b = a*(1. - f) es = 1. - (b * b) / (a * a) elif 'f' in kwargs: f = kwargs['f'] b = a*(1. - f) es = 1. - (b/a)**2 elif 'es' in kwargs: es = kwargs['es'] b = math.sqrt(a**2 - es*a**2) f = (a - b)/a elif 'e' in kwargs: es = kwargs['e']**2 b = math.sqrt(a**2 - es*a**2) f = (a - b)/a else: b = a f = 0. es = 0. #msg='ellipse name or a, plus one of f,es,b must be given' #raise ValueError(msg) if math.fabs(f) < 1.e-8: self.sphere = True self.a = a self.b = b self.f = f self.es = es return _proj.Geod.__new__(self, a, f)
initialize a Geod class instance. Geodetic parameters for specifying the ellipsoid can be given in a dictionary 'initparams', as keyword arguments, or as as proj4 geod initialization string. Following is a list of the ellipsoids that may be defined using the 'ellps' keyword (these are stored in the model variable pj_ellps):: MERIT a=6378137.0 rf=298.257 MERIT 1983 SGS85 a=6378136.0 rf=298.257 Soviet Geodetic System 85 GRS80 a=6378137.0 rf=298.257222101 GRS 1980(IUGG, 1980) IAU76 a=6378140.0 rf=298.257 IAU 1976 airy a=6377563.396 b=6356256.910 Airy 1830 APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965 airy a=6377563.396 b=6356256.910 Airy 1830 APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965 NWL9D a=6378145.0. rf=298.25 Naval Weapons Lab., 1965 mod_airy a=6377340.189 b=6356034.446 Modified Airy andrae a=6377104.43 rf=300.0 Andrae 1876 (Den., Iclnd.) aust_SA a=6378160.0 rf=298.25 Australian Natl & S. Amer. 1969 GRS67 a=6378160.0 rf=298.247167427 GRS 67(IUGG 1967) bessel a=6377397.155 rf=299.1528128 Bessel 1841 bess_nam a=6377483.865 rf=299.1528128 Bessel 1841 (Namibia) clrk66 a=6378206.4 b=6356583.8 Clarke 1866 clrk80 a=6378249.145 rf=293.4663 Clarke 1880 mod. CPM a=6375738.7 rf=334.29 Comm. des Poids et Mesures 1799 delmbr a=6376428. rf=311.5 Delambre 1810 (Belgium) engelis a=6378136.05 rf=298.2566 Engelis 1985 evrst30 a=6377276.345 rf=300.8017 Everest 1830 evrst48 a=6377304.063 rf=300.8017 Everest 1948 evrst56 a=6377301.243 rf=300.8017 Everest 1956 evrst69 a=6377295.664 rf=300.8017 Everest 1969 evrstSS a=6377298.556 rf=300.8017 Everest (Sabah & Sarawak) fschr60 a=6378166. rf=298.3 Fischer (Mercury Datum) 1960 fschr60m a=6378155. rf=298.3 Modified Fischer 1960 fschr68 a=6378150. rf=298.3 Fischer 1968 helmert a=6378200. rf=298.3 Helmert 1906 hough a=6378270.0 rf=297. Hough helmert a=6378200. rf=298.3 Helmert 1906 hough a=6378270.0 rf=297. Hough intl a=6378388.0 rf=297. International 1909 (Hayford) krass a=6378245.0 rf=298.3 Krassovsky, 1942 kaula a=6378163. rf=298.24 Kaula 1961 lerch a=6378139. rf=298.257 Lerch 1979 mprts a=6397300. rf=191. Maupertius 1738 new_intl a=6378157.5 b=6356772.2 New International 1967 plessis a=6376523. b=6355863. Plessis 1817 (France) SEasia a=6378155.0 b=6356773.3205 Southeast Asia walbeck a=6376896.0 b=6355834.8467 Walbeck WGS60 a=6378165.0 rf=298.3 WGS 60 WGS66 a=6378145.0 rf=298.25 WGS 66 WGS72 a=6378135.0 rf=298.26 WGS 72 WGS84 a=6378137.0 rf=298.257223563 WGS 84 sphere a=6370997.0 b=6370997.0 Normal Sphere (r=6370997) The parameters of the ellipsoid may also be set directly using the 'a' (semi-major or equatorial axis radius) keyword, and any one of the following keywords: 'b' (semi-minor, or polar axis radius), 'e' (eccentricity), 'es' (eccentricity squared), 'f' (flattening), or 'rf' (reciprocal flattening). See the proj documentation (http://trac.osgeo.org/proj/) for more See the proj documentation (http://trac.osgeo.org/proj/) for more information about specifying ellipsoid parameters (specifically, the chapter 'Specifying the Earth's figure' in the main Proj users manual). Example usage: >>> from pyproj import Geod >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. >>> # specify the lat/lons of some cities. >>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.) >>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.) >>> newyork_lat = 40.+(47./60.); newyork_lon = -73.-(58./60.) >>> london_lat = 51.+(32./60.); london_lon = -(5./60.) >>> # compute forward and back azimuths, plus distance >>> # between Boston and Portland. >>> az12,az21,dist = g.inv(boston_lon,boston_lat,portland_lon,portland_lat) >>> "%7.3f %6.3f %12.3f" % (az12,az21,dist) '-66.531 75.654 4164192.708' >>> # compute latitude, longitude and back azimuth of Portland, >>> # given Boston lat/lon, forward azimuth and distance to Portland. >>> endlon, endlat, backaz = g.fwd(boston_lon, boston_lat, az12, dist) >>> "%6.3f %6.3f %13.3f" % (endlat,endlon,backaz) '45.517 -123.683 75.654' >>> # compute the azimuths, distances from New York to several >>> # cities (pass a list) >>> lons1 = 3*[newyork_lon]; lats1 = 3*[newyork_lat] >>> lons2 = [boston_lon, portland_lon, london_lon] >>> lats2 = [boston_lat, portland_lat, london_lat] >>> az12,az21,dist = g.inv(lons1,lats1,lons2,lats2) >>> for faz,baz,d in list(zip(az12,az21,dist)): "%7.3f %7.3f %9.3f" % (faz,baz,d) ' 54.663 -123.448 288303.720' '-65.463 79.342 4013037.318' ' 51.254 -71.576 5579916.651' >>> g2 = Geod('+ellps=clrk66') # use proj4 style initialization string >>> az12,az21,dist = g2.inv(boston_lon,boston_lat,portland_lon,portland_lat) >>> "%7.3f %6.3f %12.3f" % (az12,az21,dist) '-66.531 75.654 4164192.708'
__new__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/pyproj/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/pyproj/__init__.py
MIT
def fwd(self, lons, lats, az, dist, radians=False): """ forward transformation - Returns longitudes, latitudes and back azimuths of terminus points given longitudes (lons) and latitudes (lats) of initial points, plus forward azimuths (az) and distances (dist). latitudes (lats) of initial points, plus forward azimuths (az) and distances (dist). Works with numpy and regular python array objects, python sequences and scalars. if radians=True, lons/lats and azimuths are radians instead of degrees. Distances are in meters. """ # process inputs, making copies that support buffer API. inx, xisfloat, xislist, xistuple = _copytobuffer(lons) iny, yisfloat, yislist, yistuple = _copytobuffer(lats) inz, zisfloat, zislist, zistuple = _copytobuffer(az) ind, disfloat, dislist, distuple = _copytobuffer(dist) _proj.Geod._fwd(self, inx, iny, inz, ind, radians=radians) # if inputs were lists, tuples or floats, convert back. outx = _convertback(xisfloat,xislist,xistuple,inx) outy = _convertback(yisfloat,yislist,xistuple,iny) outz = _convertback(zisfloat,zislist,zistuple,inz) return outx, outy, outz
forward transformation - Returns longitudes, latitudes and back azimuths of terminus points given longitudes (lons) and latitudes (lats) of initial points, plus forward azimuths (az) and distances (dist). latitudes (lats) of initial points, plus forward azimuths (az) and distances (dist). Works with numpy and regular python array objects, python sequences and scalars. if radians=True, lons/lats and azimuths are radians instead of degrees. Distances are in meters.
fwd
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/pyproj/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/pyproj/__init__.py
MIT
def inv(self,lons1,lats1,lons2,lats2,radians=False): """ inverse transformation - Returns forward and back azimuths, plus distances between initial points (specified by lons1, lats1) and terminus points (specified by lons2, lats2). Works with numpy and regular python array objects, python sequences and scalars. if radians=True, lons/lats and azimuths are radians instead of degrees. Distances are in meters. """ # process inputs, making copies that support buffer API. inx, xisfloat, xislist, xistuple = _copytobuffer(lons1) iny, yisfloat, yislist, yistuple = _copytobuffer(lats1) inz, zisfloat, zislist, zistuple = _copytobuffer(lons2) ind, disfloat, dislist, distuple = _copytobuffer(lats2) _proj.Geod._inv(self,inx,iny,inz,ind,radians=radians) # if inputs were lists, tuples or floats, convert back. outx = _convertback(xisfloat,xislist,xistuple,inx) outy = _convertback(yisfloat,yislist,xistuple,iny) outz = _convertback(zisfloat,zislist,zistuple,inz) return outx, outy, outz
inverse transformation - Returns forward and back azimuths, plus distances between initial points (specified by lons1, lats1) and terminus points (specified by lons2, lats2). Works with numpy and regular python array objects, python sequences and scalars. if radians=True, lons/lats and azimuths are radians instead of degrees. Distances are in meters.
inv
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/pyproj/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/pyproj/__init__.py
MIT
def npts(self, lon1, lat1, lon2, lat2, npts, radians=False): """ Given a single initial point and terminus point (specified by python floats lon1,lat1 and lon2,lat2), returns a list of longitude/latitude pairs describing npts equally spaced intermediate points along the geodesic between the initial and terminus points. if radians=True, lons/lats are radians instead of degrees. Example usage: >>> from pyproj import Geod >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. >>> # specify the lat/lons of Boston and Portland. >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. >>> # specify the lat/lons of Boston and Portland. >>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.) >>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.) >>> # find ten equally spaced points between Boston and Portland. >>> lonlats = g.npts(boston_lon,boston_lat,portland_lon,portland_lat,10) >>> for lon,lat in lonlats: '%6.3f %7.3f' % (lat, lon) '43.528 -75.414' '44.637 -79.883' '45.565 -84.512' '46.299 -89.279' '46.830 -94.156' '47.149 -99.112' '47.251 -104.106' '47.136 -109.100' '46.805 -114.051' '46.262 -118.924' >>> # test with radians=True (inputs/outputs in radians, not degrees) >>> import math >>> dg2rad = math.radians(1.) >>> rad2dg = math.degrees(1.) >>> lonlats = g.npts(dg2rad*boston_lon,dg2rad*boston_lat,dg2rad*portland_lon,dg2rad*portland_lat,10,radians=True) >>> for lon,lat in lonlats: '%6.3f %7.3f' % (rad2dg*lat, rad2dg*lon) '43.528 -75.414' '44.637 -79.883' '45.565 -84.512' '46.299 -89.279' '46.830 -94.156' '47.149 -99.112' '47.251 -104.106' '47.136 -109.100' '46.805 -114.051' '46.262 -118.924' """ lons, lats = _proj.Geod._npts(self, lon1, lat1, lon2, lat2, npts, radians=radians) return list(zip(lons, lats))
Given a single initial point and terminus point (specified by python floats lon1,lat1 and lon2,lat2), returns a list of longitude/latitude pairs describing npts equally spaced intermediate points along the geodesic between the initial and terminus points. if radians=True, lons/lats are radians instead of degrees. Example usage: >>> from pyproj import Geod >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. >>> # specify the lat/lons of Boston and Portland. >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. >>> # specify the lat/lons of Boston and Portland. >>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.) >>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.) >>> # find ten equally spaced points between Boston and Portland. >>> lonlats = g.npts(boston_lon,boston_lat,portland_lon,portland_lat,10) >>> for lon,lat in lonlats: '%6.3f %7.3f' % (lat, lon) '43.528 -75.414' '44.637 -79.883' '45.565 -84.512' '46.299 -89.279' '46.830 -94.156' '47.149 -99.112' '47.251 -104.106' '47.136 -109.100' '46.805 -114.051' '46.262 -118.924' >>> # test with radians=True (inputs/outputs in radians, not degrees) >>> import math >>> dg2rad = math.radians(1.) >>> rad2dg = math.degrees(1.) >>> lonlats = g.npts(dg2rad*boston_lon,dg2rad*boston_lat,dg2rad*portland_lon,dg2rad*portland_lat,10,radians=True) >>> for lon,lat in lonlats: '%6.3f %7.3f' % (rad2dg*lat, rad2dg*lon) '43.528 -75.414' '44.637 -79.883' '45.565 -84.512' '46.299 -89.279' '46.830 -94.156' '47.149 -99.112' '47.251 -104.106' '47.136 -109.100' '46.805 -114.051' '46.262 -118.924'
npts
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/win32/pyproj/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/pyproj/__init__.py
MIT
def register(cls, subclass): """Register a virtual subclass of an ABC.""" if not isinstance(subclass, (type, types.ClassType)): raise TypeError("Can only register classes") if issubclass(subclass, cls): return # Already a subclass # Subtle: test for cycles *after* testing for "already a subclass"; # this means we allow X.register(X) and interpret it as a no-op. if issubclass(cls, subclass): # This would create a cycle, which is bad for the algorithm below raise RuntimeError("Refusing to create an inheritance cycle") cls._abc_registry.add(subclass) ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
Register a virtual subclass of an ABC.
register
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/abc.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/abc.py
MIT
def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__) print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter for name in sorted(cls.__dict__.keys()): if name.startswith("_abc_"): value = getattr(cls, name) print >> file, "%s: %r" % (name, value)
Debug helper to print the ABC registry.
_dump_registry
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/abc.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/abc.py
MIT
def open(file, flag='r', mode=0666): """Open or create database at path given by *file*. Optional argument *flag* can be 'r' (default) for read-only access, 'w' for read-write access of an existing database, 'c' for read-write access to a new or existing database, and 'n' for read-write access to a new database. Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it only if it doesn't exist; and 'n' always creates a new database. """ # guess the type of an existing database from whichdb import whichdb result=whichdb(file) if result is None: # db doesn't exist if 'c' in flag or 'n' in flag: # file doesn't exist and the new # flag was used so use default type mod = _defaultmod else: raise error, "need 'c' or 'n' flag to open new db" elif result == "": # db type cannot be determined raise error, "db type could not be determined" else: mod = __import__(result) return mod.open(file, flag, mode)
Open or create database at path given by *file*. Optional argument *flag* can be 'r' (default) for read-only access, 'w' for read-write access of an existing database, 'c' for read-write access to a new or existing database, and 'n' for read-write access to a new database. Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it only if it doesn't exist; and 'n' always creates a new database.
open
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/anydbm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/anydbm.py
MIT
def error(self, message): """error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(_sys.stderr) self.exit(2, _('%s: error: %s\n') % (self.prog, message))
error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception.
error
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/argparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/argparse.py
MIT
def literal_eval(node_or_string): """ Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. """ _safe_names = {'None': None, 'True': True, 'False': False} if isinstance(node_or_string, basestring): node_or_string = parse(node_or_string, mode='eval') if isinstance(node_or_string, Expression): node_or_string = node_or_string.body def _convert(node): if isinstance(node, Str): return node.s elif isinstance(node, Num): return node.n elif isinstance(node, Tuple): return tuple(map(_convert, node.elts)) elif isinstance(node, List): return list(map(_convert, node.elts)) elif isinstance(node, Dict): return dict((_convert(k), _convert(v)) for k, v in zip(node.keys, node.values)) elif isinstance(node, Name): if node.id in _safe_names: return _safe_names[node.id] elif isinstance(node, BinOp) and \ isinstance(node.op, (Add, Sub)) and \ isinstance(node.right, Num) and \ isinstance(node.right.n, complex) and \ isinstance(node.left, Num) and \ isinstance(node.left.n, (int, long, float)): left = node.left.n right = node.right.n if isinstance(node.op, Add): return left + right else: return left - right raise ValueError('malformed string') return _convert(node_or_string)
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
literal_eval
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def dump(node, annotate_fields=True, include_attributes=False): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True. """ def _format(node): if isinstance(node, AST): fields = [(a, _format(b)) for a, b in iter_fields(node)] rv = '%s(%s' % (node.__class__.__name__, ', '.join( ('%s=%s' % field for field in fields) if annotate_fields else (b for a, b in fields) )) if include_attributes and node._attributes: rv += fields and ', ' or ' ' rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) for a in node._attributes) return rv + ')' elif isinstance(node, list): return '[%s]' % ', '.join(_format(x) for x in node) return repr(node) if not isinstance(node, AST): raise TypeError('expected AST, got %r' % node.__class__.__name__) return _format(node)
Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True.
dump
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def copy_location(new_node, old_node): """ Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ for attr in 'lineno', 'col_offset': if attr in old_node._attributes and attr in new_node._attributes \ and hasattr(old_node, attr): setattr(new_node, attr, getattr(old_node, attr)) return new_node
Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*.
copy_location
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def fix_missing_locations(node): """ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*. """ def _fix(node, lineno, col_offset): if 'lineno' in node._attributes: if not hasattr(node, 'lineno'): node.lineno = lineno else: lineno = node.lineno if 'col_offset' in node._attributes: if not hasattr(node, 'col_offset'): node.col_offset = col_offset else: col_offset = node.col_offset for child in iter_child_nodes(node): _fix(child, lineno, col_offset) _fix(node, 1, 0) return node
When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*.
fix_missing_locations
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def increment_lineno(node, n=1): """ Increment the line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file. """ for child in walk(node): if 'lineno' in child._attributes: child.lineno = getattr(child, 'lineno', 0) + n return node
Increment the line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file.
increment_lineno
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*.
iter_fields
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def iter_child_nodes(node): """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): for item in field: if isinstance(item, AST): yield item
Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes.
iter_child_nodes
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def get_docstring(node, clean=True): """ Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised. """ if not isinstance(node, (FunctionDef, ClassDef, Module)): raise TypeError("%r can't have docstrings" % node.__class__.__name__) if node.body and isinstance(node.body[0], Expr) and \ isinstance(node.body[0].value, Str): if clean: import inspect return inspect.cleandoc(node.body[0].value.s) return node.body[0].value.s
Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised.
get_docstring
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def walk(node): """ Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) while todo: node = todo.popleft() todo.extend(iter_child_nodes(node)) yield node
Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
walk
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field, value in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(value)
Called if no explicit visitor function exists for a node.
generic_visit
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ast.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ast.py
MIT
def readable (self): "predicate for inclusion in the readable for select()" # cannot use the old predicate, it violates the claim of the # set_terminator method. # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size) return 1
predicate for inclusion in the readable for select()
readable
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/asynchat.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/asynchat.py
MIT
def writable (self): "predicate for inclusion in the writable for select()" return self.producer_fifo or (not self.connected)
predicate for inclusion in the writable for select()
writable
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/asynchat.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/asynchat.py
MIT
def _run_exitfuncs(): """run any registered exit functions _exithandlers is traversed in reverse order so functions are executed last in, first out. """ exc_info = None while _exithandlers: func, targs, kargs = _exithandlers.pop() try: func(*targs, **kargs) except SystemExit: exc_info = sys.exc_info() except: import traceback print >> sys.stderr, "Error in atexit._run_exitfuncs:" traceback.print_exc() exc_info = sys.exc_info() if exc_info is not None: raise exc_info[0], exc_info[1], exc_info[2]
run any registered exit functions _exithandlers is traversed in reverse order so functions are executed last in, first out.
_run_exitfuncs
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/atexit.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/atexit.py
MIT
def b64encode(s, altchars=None): """Encode a string using Base64. s is the string to encode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings. The encoded string is returned. """ # Strip off the trailing newline encoded = binascii.b2a_base64(s)[:-1] if altchars is not None: return encoded.translate(string.maketrans(b'+/', altchars[:2])) return encoded
Encode a string using Base64. s is the string to encode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings. The encoded string is returned.
b64encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/base64.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/base64.py
MIT
def b64decode(s, altchars=None): """Decode a Base64 encoded string. s is the string to decode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the '+' and '/' characters. The decoded string is returned. A TypeError is raised if s is incorrectly padded. Characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. """ if altchars is not None: s = s.translate(string.maketrans(altchars[:2], '+/')) try: return binascii.a2b_base64(s) except binascii.Error, msg: # Transform this exception for consistency raise TypeError(msg)
Decode a Base64 encoded string. s is the string to decode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the '+' and '/' characters. The decoded string is returned. A TypeError is raised if s is incorrectly padded. Characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check.
b64decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/base64.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/base64.py
MIT