signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def activate(): | global PathFinder, FileFinder, ff_path_hook<EOL>path_hook_index = len(sys.path_hooks)<EOL>sys.path_hooks.append(ff_path_hook)<EOL>sys.path_importer_cache.clear()<EOL>pathfinder_index = len(sys.meta_path)<EOL>sys.meta_path.append(PathFinder)<EOL>return path_hook_index, pathfinder_index<EOL> | Install the path-based import components. | f125:m0 |
@contextlib.contextmanager<EOL>def enable_pep420(): | path_hook_index, pathfinder_index = activate()<EOL>yield path_hook_index, pathfinder_index<EOL>deactivate(path_hook_index, pathfinder_index)<EOL> | Enabling support of pep420, now available on python2
:param force: if set, filefinder2 code will be enabled for python3 as well.
CAREFUL : this is only intended for import-time debugging purposes from python code.
:return: | f125:m2 |
def all_suffixes(): | return SOURCE_SUFFIXES + BYTECODE_SUFFIXES + EXTENSION_SUFFIXES<EOL> | Returns a list of all recognized module suffixes for this process | f126:m1 |
@classmethod<EOL><INDENT>def invalidate_caches(cls):<DEDENT> | for finder in sys.path_importer_cache.values():<EOL><INDENT>if hasattr(finder, '<STR_LIT>'):<EOL><INDENT>finder.invalidate_caches()<EOL><DEDENT><DEDENT> | Call the invalidate_caches() method on all path entry finders
stored in sys.path_importer_caches (where implemented). | f131:c0:m0 |
@classmethod<EOL><INDENT>def _path_hooks(cls, path): <DEDENT> | if sys.path_hooks is not None and not sys.path_hooks:<EOL><INDENT>warnings.warn('<STR_LIT>', ImportWarning)<EOL><DEDENT>for hook in sys.path_hooks:<EOL><INDENT>try:<EOL><INDENT>return hook(path)<EOL><DEDENT>except ImportError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Search sys.path_hooks for a finder for 'path'. | f131:c0:m1 |
@classmethod<EOL><INDENT>def _path_importer_cache(cls, path): <DEDENT> | if path == '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>path = os.getcwd()<EOL><DEDENT>except FileNotFoundError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>try:<EOL><INDENT>finder = sys.path_importer_cache[path]<EOL><DEDENT>except KeyError:<EOL><INDENT>finder = cls._path_hooks(path)<EOL>sys.path_importer_cache[path] = finder<EOL><DEDENT>return finder<EOL> | Get the finder for the path entry from sys.path_importer_cache.
If the path entry is not in the cache, find the appropriate finder
and cache it. If no finder is available, store None. | f131:c0:m2 |
@classmethod<EOL><INDENT>def _get_spec(cls, fullname, path, target=None):<DEDENT> | <EOL>namespace_path = []<EOL>for entry in path:<EOL><INDENT>if not isinstance(entry, (str, bytes)):<EOL><INDENT>continue<EOL><DEDENT>finder = cls._path_importer_cache(entry)<EOL>if finder is not None:<EOL><INDENT>if hasattr(finder, '<STR_LIT>'):<EOL><INDENT>spec = finder.find_spec(fullname, target)<EOL><DEDENT>else:<EOL><INDENT>spec = cls._legacy_get_spec(fullname, finder)<EOL><DEDENT>if spec is None:<EOL><INDENT>continue<EOL><DEDENT>if spec.loader is not None:<EOL><INDENT>return spec<EOL><DEDENT>portions = spec.submodule_search_locations<EOL>if portions is None:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT>namespace_path.extend(portions)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>spec = ModuleSpec(fullname, None)<EOL>spec.submodule_search_locations = namespace_path<EOL>return spec<EOL><DEDENT> | Find the loader or namespace_path for this module/package name. | f131:c0:m4 |
@classmethod<EOL><INDENT>def find_module(cls, fullname, path=None):<DEDENT> | spec = cls.find_spec(fullname, path)<EOL>if spec is None:<EOL><INDENT>return None<EOL><DEDENT>elif spec.loader is None and spec.submodule_search_locations:<EOL><INDENT>return NamespaceLoader2(spec.name, spec.submodule_search_locations)<EOL><DEDENT>else:<EOL><INDENT>return spec.loader<EOL><DEDENT> | find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.
This method is for python2 only | f131:c0:m5 |
@classmethod<EOL><INDENT>def find_spec(cls, fullname, path=None, target=None):<DEDENT> | if path is None:<EOL><INDENT>path = sys.path<EOL><DEDENT>spec = cls._get_spec(fullname, path, target)<EOL>if spec is None:<EOL><INDENT>return None<EOL><DEDENT>elif spec.loader is None:<EOL><INDENT>namespace_path = spec.submodule_search_locations<EOL>if namespace_path:<EOL><INDENT>spec.origin = '<STR_LIT>'<EOL>spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)<EOL>return spec<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return spec<EOL><DEDENT> | find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache. | f131:c0:m6 |
def __init__(self, path, *loader_details): | loaders = []<EOL>for loader, suffixes in loader_details:<EOL><INDENT>loaders.extend((suffix, loader) for suffix in suffixes)<EOL><DEDENT>self._loaders = loaders<EOL>self.path = path or '<STR_LIT:.>'<EOL> | Initialize with the path to search on and a variable number of
2-tuples containing the loader and the file suffixes the loader
recognizes. | f131:c1:m0 |
def find_spec(self, fullname, target=None): | is_namespace = False<EOL>tail_module = fullname.rpartition('<STR_LIT:.>')[<NUM_LIT:2>]<EOL>base_path = os.path.join(self.path, tail_module)<EOL>for suffix, loader_class in self._loaders:<EOL><INDENT>init_filename = '<STR_LIT>' + suffix<EOL>init_full_path = os.path.join(base_path, init_filename)<EOL>full_path = base_path + suffix<EOL>if os.path.isfile(init_full_path):<EOL><INDENT>return self._get_spec(loader_class, fullname, init_full_path, [base_path], target)<EOL><DEDENT>if os.path.isfile(full_path): <EOL><INDENT>return self._get_spec(loader_class, fullname, full_path, None, target)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>is_namespace = os.path.isdir(base_path)<EOL><DEDENT>if is_namespace:<EOL><INDENT>_verbose_message('<STR_LIT>'.format(base_path))<EOL>spec = ModuleSpec(fullname, None)<EOL>spec.submodule_search_locations = [base_path]<EOL>return spec<EOL><DEDENT>return None<EOL> | Try to find a spec for the specified module. Returns the
matching spec, or None if not found. | f131:c1:m2 |
def find_loader(self, fullname): | spec = self.find_spec(fullname)<EOL>if spec is None:<EOL><INDENT>return None, []<EOL><DEDENT>return spec.loader, spec.submodule_search_locations or []<EOL> | Try to find a loader for the specified module, or the namespace
package portions. Returns (loader, list-of-portions).
This method is deprecated. Use find_spec() instead. | f131:c1:m3 |
def find_module(self, fullname): | spec = self.find_spec(fullname)<EOL>if spec is None:<EOL><INDENT>return None<EOL><DEDENT>if spec.loader is None and len(spec.submodule_search_locations):<EOL><INDENT>spec.loader = NamespaceLoader2(spec.name, spec.submodule_search_locations)<EOL><DEDENT>return spec.loader<EOL> | Try to find a loader for the specified module, or the namespace
package portions. Returns loader. | f131:c1:m4 |
@classmethod<EOL><INDENT>def path_hook(cls, *loader_details):<DEDENT> | def path_hook_for_FileFinder2(path):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not os.path.isdir(path):<EOL><INDENT>raise _ImportError('<STR_LIT>', path=path)<EOL><DEDENT>return cls(path, *loader_details)<EOL><DEDENT>return path_hook_for_FileFinder2<EOL> | A class method which returns a closure to use on sys.path_hook
which will return an instance using the specified loaders and the path
called on the closure.
If the path called on the closure is not a directory, ImportError is
raised. | f131:c1:m5 |
def strip_encoding_cookie(filelike): | it = iter(filelike)<EOL>try:<EOL><INDENT>first = next(it)<EOL>if not cookie_comment_re.match(first):<EOL><INDENT>yield first<EOL><DEDENT>second = next(it)<EOL>if not cookie_comment_re.match(second):<EOL><INDENT>yield second<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT>for line in it:<EOL><INDENT>yield line<EOL><DEDENT> | Generator to pull lines from a text-mode file, skipping the encoding
cookie if it is found in the first two lines. | f133:m0 |
def source_to_unicode(txt, errors='<STR_LIT:replace>', skip_encoding_cookie=True): | if isinstance(txt, six.text_type):<EOL><INDENT>return txt<EOL><DEDENT>if isinstance(txt, six.binary_type):<EOL><INDENT>buffer = io.BytesIO(txt)<EOL><DEDENT>else:<EOL><INDENT>buffer = txt<EOL><DEDENT>try:<EOL><INDENT>encoding, _ = detect_encoding(buffer.readline)<EOL><DEDENT>except SyntaxError:<EOL><INDENT>encoding = "<STR_LIT:ascii>"<EOL><DEDENT>buffer.seek(<NUM_LIT:0>)<EOL>newline_decoder = io.IncrementalNewlineDecoder(None, True)<EOL>text = io.TextIOWrapper(buffer, encoding, errors=errors, line_buffering=True)<EOL>text.mode = '<STR_LIT:r>'<EOL>if skip_encoding_cookie:<EOL><INDENT>return u"<STR_LIT>".join(strip_encoding_cookie(text))<EOL><DEDENT>else:<EOL><INDENT>return text.read()<EOL><DEDENT> | Converts a bytes string with python source code to unicode.
Unicode strings are passed through unchanged. Byte strings are checked
for the python source file encoding cookie to determine encoding.
txt can be either a bytes buffer or a string containing the source
code. | f133:m1 |
def decode_source(source_bytes): | <EOL>newline_decoder = io.IncrementalNewlineDecoder(None, True)<EOL>return newline_decoder.decode(source_to_unicode(source_bytes))<EOL> | Decode bytes representing source code and return the string.
Universal newline support is used in the decoding. | f133:m2 |
def get_supported_file_loaders_2(force=False): | if force or (<NUM_LIT:2>, <NUM_LIT:7>) <= sys.version_info < (<NUM_LIT:3>, <NUM_LIT:4>): <EOL><INDENT>import imp<EOL>loaders = []<EOL>for suffix, mode, type in imp.get_suffixes():<EOL><INDENT>if type == imp.PY_SOURCE:<EOL><INDENT>loaders.append((SourceFileLoader2, [suffix]))<EOL><DEDENT>else:<EOL><INDENT>loaders.append((ImpFileLoader2, [suffix]))<EOL><DEDENT><DEDENT>return loaders<EOL><DEDENT>elif sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:4>): <EOL><INDENT>from importlib.machinery import (<EOL>SOURCE_SUFFIXES, SourceFileLoader,<EOL>BYTECODE_SUFFIXES, SourcelessFileLoader,<EOL>EXTENSION_SUFFIXES, ExtensionFileLoader,<EOL>)<EOL>extensions = ExtensionFileLoader, EXTENSION_SUFFIXES<EOL>source = SourceFileLoader, SOURCE_SUFFIXES<EOL>bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES<EOL>return [extensions, source, bytecode]<EOL><DEDENT> | Returns a list of file-based module loaders.
Each item is a tuple (loader, suffixes). | f134:m0 |
def _find_parent_path_names(self): | parent, dot, me = self._name.rpartition('<STR_LIT:.>')<EOL>if dot == '<STR_LIT>':<EOL><INDENT>return '<STR_LIT>', '<STR_LIT:path>'<EOL><DEDENT>return parent, '<STR_LIT>'<EOL> | Returns a tuple of (parent-module-name, parent-path-attr-name) | f134:c0:m1 |
def is_package(self, fullname): | filename = os.path.split(self.get_filename(fullname))[<NUM_LIT:1>]<EOL>filename_base = filename.rsplit('<STR_LIT:.>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>tail_name = fullname.rpartition('<STR_LIT:.>')[<NUM_LIT:2>]<EOL>return filename_base == '<STR_LIT>' and tail_name != '<STR_LIT>'<EOL> | Concrete implementation of InspectLoader.is_package by checking if
the path returned by get_filename has a filename of '__init__.py'. | f134:c1:m0 |
def create_module(self, spec): | mod = sys.modules.setdefault(spec.name, types.ModuleType(spec.name))<EOL>return mod<EOL> | Creates the module, and also insert it into sys.modules, adding this onto py2 import logic. | f134:c1:m1 |
def exec_module(self, module): | code = self.get_code(module.__name__)<EOL>if code is None:<EOL><INDENT>raise ImportError('<STR_LIT>'<EOL>'<STR_LIT>'.format(module.__name__))<EOL><DEDENT>exec(code, module.__dict__)<EOL> | Execute the module. | f134:c1:m2 |
def load_module(self, fullname): | if fullname in sys.modules:<EOL><INDENT>mod = sys.modules[fullname]<EOL>self.exec_module(mod)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>spec = spec_from_loader(fullname, self)<EOL>mod = module_from_spec(spec)<EOL>assert mod.__name__ in sys.modules<EOL>self.exec_module(mod)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>if fullname in sys.modules:<EOL><INDENT>del sys.modules[fullname]<EOL><DEDENT>raise<EOL><DEDENT><DEDENT>return sys.modules[fullname]<EOL> | Load the specified module into sys.modules and return it.
This method is for python2 only, but implemented with backported py3 methods. | f134:c1:m3 |
def create_module(self, spec): | mod = super(NamespaceLoader2, self).create_module(spec)<EOL>return mod<EOL> | Improve python2 semantics for module creation. | f134:c2:m1 |
def load_module(self, name): | _verbose_message('<STR_LIT>', self.path)<EOL>if name in sys.modules:<EOL><INDENT>mod = sys.modules[name]<EOL>self.exec_module(mod)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>spec = ModuleSpec(name, self, origin='<STR_LIT>', is_package=True)<EOL>spec.submodule_search_locations = self.path<EOL>mod = module_from_spec(spec)<EOL>assert mod.__name__ in sys.modules<EOL>self.exec_module(mod)<EOL><DEDENT>except:<EOL><INDENT>if name in sys.modules:<EOL><INDENT>del sys.modules[name]<EOL><DEDENT>raise<EOL><DEDENT><DEDENT>return sys.modules[name]<EOL> | Load a namespace module as if coming from an empty file. | f134:c2:m2 |
def set_data(self, path, data): | Optional method which writes data (bytes) to a file path (a str).
Implementing this method allows for the writing of bytecode files. | f134:c3:m0 |
|
def get_source(self, name): | path = self.get_filename(name)<EOL>try:<EOL><INDENT>source_bytes = self.get_data(path)<EOL><DEDENT>except OSError as exc:<EOL><INDENT>e = _ImportError('<STR_LIT>',<EOL>name=name)<EOL>e.__cause__ = exc<EOL>raise e<EOL><DEDENT>return decode_source(source_bytes)<EOL> | Concrete implementation of InspectLoader.get_source. | f134:c3:m1 |
def source_to_code(self, data, path): | return compile(data, path, '<STR_LIT>', dont_inherit=True)<EOL> | Return the code object compiled from source.
The 'data' argument can be any object type that compile() supports. | f134:c3:m2 |
def __init__(self, fullname, path=None): | self.name = fullname<EOL>self.path = path<EOL> | Cache the module name and the path to the file found by the
finder. | f134:c4:m0 |
def get_filename(self, fullname): | return self.path<EOL> | Return the path to the source file as found by the finder. | f134:c4:m3 |
def get_data(self, path): | with io.FileIO(path, '<STR_LIT:r>') as file:<EOL><INDENT>return file.read()<EOL><DEDENT> | Return the data from path as raw bytes. | f134:c4:m4 |
def __init__(self, fullname, path): | super(SourceFileLoader2, self).__init__(fullname, path)<EOL> | Cache the module name and the path to the file found by the
finder.
:param fullname the name of the module to load
:param path to the module or the package.
If it is a package the path must point to a directory.
Otherwise the path to the python module is needed | f134:c5:m0 |
def exec_module(self, module): | path = [os.path.dirname(module.__file__)] <EOL>file = None<EOL>try:<EOL><INDENT>file, pathname, description = imp.find_module(module.__name__.rpartition('<STR_LIT:.>')[-<NUM_LIT:1>], path)<EOL>module = imp.load_module(module.__name__, file, pathname, description)<EOL><DEDENT>finally:<EOL><INDENT>if file:<EOL><INDENT>file.close()<EOL><DEDENT><DEDENT> | Execute the module using the old imp. | f134:c6:m1 |
def load_module(self, name): | <EOL>if name in sys.modules:<EOL><INDENT>return sys.modules[name]<EOL><DEDENT>try:<EOL><INDENT>for name_idx, name_part in enumerate(name.split('<STR_LIT:.>')):<EOL><INDENT>pkgname = "<STR_LIT:.>".join(name.split('<STR_LIT:.>')[:name_idx+<NUM_LIT:1>])<EOL>if pkgname not in sys.modules:<EOL><INDENT>if '<STR_LIT:.>' in pkgname:<EOL><INDENT>if '<STR_LIT>' in vars(sys.modules[pkgname.rpartition('<STR_LIT:.>')[<NUM_LIT:0>]]):<EOL><INDENT>path = sys.modules[pkgname.rpartition('<STR_LIT:.>')[<NUM_LIT:0>]].__path__<EOL><DEDENT>else:<EOL><INDENT>raise ImportError("<STR_LIT>".format(pkgname.rpartition('<STR_LIT:.>')[<NUM_LIT:0>]))<EOL><DEDENT><DEDENT>else: <EOL><INDENT>path = os.path.dirname(sys.modules[pkgname].__file__)if pkgname in sys.modules else None<EOL><DEDENT>try:<EOL><INDENT>file, pathname, description = imp.find_module(pkgname.rpartition('<STR_LIT:.>')[-<NUM_LIT:1>], path)<EOL>sys.modules[pkgname] = imp.load_module(pkgname, file, pathname, description)<EOL><DEDENT>finally:<EOL><INDENT>if file:<EOL><INDENT>file.close()<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>if name in sys.modules:<EOL><INDENT>del sys.modules[name]<EOL><DEDENT>raise<EOL><DEDENT>return sys.modules[name]<EOL> | Load a module from a file. | f134:c6:m2 |
def _verbose_message(message, *args, **kwargs): | verbosity = kwargs.pop('<STR_LIT>', <NUM_LIT:1>)<EOL>if sys.flags.verbose >= verbosity:<EOL><INDENT>if not message.startswith(('<STR_LIT:#>', '<STR_LIT>')):<EOL><INDENT>message = '<STR_LIT>' + message<EOL><DEDENT>print(message.format(*args), file=sys.stderr)<EOL><DEDENT> | Print the message to stderr if -v/PYTHONVERBOSE is turned on. | f135:m0 |
def initialize_options(self): | pass<EOL> | init options | f136:c0:m0 |
def finalize_options(self): | pass<EOL> | finalize options | f136:c0:m1 |
def run(self): | <EOL>subprocess.check_call(<EOL>"<STR_LIT>".format(__version__), shell=True)<EOL>subprocess.check_call("<STR_LIT>", shell=True)<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>sys.exit()<EOL> | runner | f136:c0:m2 |
def initialize_options(self): | <EOL>pass<EOL> | init options | f136:c1:m0 |
def finalize_options(self): | pass<EOL> | finalize options | f136:c1:m1 |
def run(self): | <EOL>subprocess.check_call("<STR_LIT>", shell=True)<EOL>subprocess.check_call("<STR_LIT>", shell=True)<EOL>subprocess.check_call("<STR_LIT>", shell=True)<EOL>subprocess.check_call("<STR_LIT>".format(__version__), shell=True)<EOL>subprocess.check_call("<STR_LIT>", shell=True)<EOL>sys.exit()<EOL> | runner | f136:c1:m2 |
def clean_module(name): | try:<EOL><INDENT>del sys.modules[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>return<EOL> | Clean a module import so all variables in it will be created again | f138:m0 |
def _hasher_first_run(self, preimage): | new_hasher = self._backend.keccak256<EOL>assert new_hasher(b'<STR_LIT>') == b"<STR_LIT>" <EOL>self.hasher = new_hasher<EOL>return new_hasher(preimage)<EOL> | Invoke the backend on-demand, and check an expected hash result,
then replace this first run with the new hasher method.
This is a bit of a hacky way to minimize overhead on hash calls after this first one. | f143:c0:m1 |
def __init__(self, parent, title, values, index=<NUM_LIT:0>): | super().__init__(parent, title, self.activate)<EOL>if len(values):<EOL><INDENT>self._values = values<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._index = index<EOL>self._selection = values[index]<EOL>self.help = "<STR_LIT>"<EOL>self.type = "<STR_LIT>"<EOL>self.logger=logging.getLogger("<STR_LIT>")<EOL> | Set the possible values for this control. | f154:c0:m0 |
def activate(self, event): | self._index += <NUM_LIT:1><EOL>if self._index >= len(self._values):<EOL><INDENT>self._index = <NUM_LIT:0><EOL><DEDENT>self._selection = self._values[self._index]<EOL>self.ao2.speak(self._selection)<EOL> | Change the value. | f154:c0:m1 |
def __init__(self, parent, title, value=False, stateChecked="<STR_LIT>", stateUnchecked="<STR_LIT>"): | super().__init__(parent, title, self.activate)<EOL>self.type = "<STR_LIT>"<EOL>self.logger = logging.getLogger("<STR_LIT>")<EOL>self.value = value<EOL>self.stateChecked = stateChecked<EOL>self.stateUnchecked = stateUnchecked<EOL>self.help = "<STR_LIT>"<EOL> | Set the title and the initial state. | f155:c0:m0 |
def activate(self, event): | self.value = not self.value<EOL>self.selected()<EOL> | Toggle the state. | f155:c0:m1 |
def __init__(self, parent, title): | super().__init__(parent, title, "<STR_LIT>", logger=logging.getLogger("<STR_LIT>"))<EOL>self.type = "<STR_LIT>"<EOL>self.help = "<STR_LIT>"<EOL> | Set the title, and alter the help message. | f157:c0:m0 |
def get_title(self): | return "<STR_LIT:{}>".format(self.title)<EOL> | Get the title. | f157:c0:m1 |
def __init__(self, parent, title, actions): | super().__init__(parent, title, "<STR_LIT>", logger=logging.getLogger("<STR_LIT>"),<EOL>help="<STR_LIT>")<EOL>self.activateActionHandler = self.add_keydown(actions, key=(lambda v: v ==pygame.K_RETURN or v == pygame.K_SPACE))<EOL> | Action will be called when the enter key is pressed. | f159:c0:m0 |
def cancel(self, event): | self.parent.reset_control()<EOL> | Close this dialog by handing focus back to the parent container. | f164:c0:m2 |
def __init__(self, parent, title, type, logger=None, help="<STR_LIT>"): | super().__init__(logger)<EOL>if not isinstance(parent, EventManager):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.parent = parent<EOL>self.title = title<EOL>self.help = help<EOL>self.ao2 = Auto()<EOL>self._type = type<EOL> | Set the title, type, logger, and help for this item. | f165:c0:m0 |
def get_title(self): | return "<STR_LIT>".format(self.title, self.type)<EOL> | Get the title. | f165:c0:m3 |
def selected(self, interrupt=False): | self.ao2.output(self.get_title(), interrupt=interrupt)<EOL> | This object has been selected. | f165:c0:m4 |
def get_help(self): | self.ao2.output(self.help)<EOL> | Show help for this control. | f165:c0:m5 |
def handle_event(self, event): | return super().handle_event(event)<EOL> | Return True if the event was handled by this control, False otherwise. | f165:c0:m6 |
def __str__(self): | return "<STR_LIT>".format(self.__class__, self.type, self.title, self.help)<EOL> | Return the data for this class for printing | f165:c0:m7 |
@abstractmethod<EOL><INDENT>def add(self, e):<DEDENT> | pass<EOL> | Adds an element to this object. | f167:c0:m1 |
@abstractmethod<EOL><INDENT>def remove(self, e):<DEDENT> | pass<EOL> | Removes an element from this object. | f167:c0:m2 |
@abstractmethod<EOL><INDENT>def next(self, event):<DEDENT> | pass<EOL> | Navigate to the next element. | f167:c0:m3 |
@abstractmethod<EOL><INDENT>def previous(self, event):<DEDENT> | pass<EOL> | Navigate to the previous element. | f167:c0:m4 |
@abstractmethod<EOL><INDENT>def get_current_element(self):<DEDENT> | pass<EOL> | Return the current element in the queue. | f167:c0:m5 |
@abstractmethod<EOL><INDENT>def set_control(self, element):<DEDENT> | pass<EOL> | Set control of this object to the given element. Used by external elements to change the currently focused element. | f167:c0:m6 |
@abstractmethod<EOL><INDENT>def reset_control(self):<DEDENT> | pass<EOL> | Reset control to the currently selected Element before set_control was called. | f167:c0:m7 |
@abstractmethod<EOL><INDENT>def handle_event(self, event):<DEDENT> | <EOL>for h in self._events.get(event.type, []):<EOL><INDENT>for k, v in h.params.items():<EOL><INDENT>if not v(getattr(event, k, v)):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>h.call_actions(event)<EOL>if self._logger is not None:<EOL><INDENT>self._logger.debug("<STR_LIT>".format(event))<EOL><DEDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | An abstract method that must be overwritten by child classes used to handle events.
event - the event to be handled
returns true or false if the event could be handled here
default code is given for this method, however subclasses must still override this method to insure the subclass has the correct behavior. | f170:c0:m1 |
@property<EOL><INDENT>def events(self):<DEDENT> | return self._events<EOL> | Return all event handlers. | f170:c0:m2 |
@property<EOL><INDENT>def logger(self):<DEDENT> | return self._logger<EOL> | Return the curreunt logger if it is not None. | f170:c0:m3 |
@logger.setter<EOL><INDENT>def logger(self, logger):<DEDENT> | if logger is None or not isinstance(logger, Logger):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._logger = logger<EOL> | Set the logger if is not None, and it is of type Logger. | f170:c0:m4 |
def add_handler(self, type, actions, **kwargs): | l = self._events.get(type, [])<EOL>h = Handler(self, type, kwargs, actions)<EOL>l.append(h)<EOL>self._events[type] = l<EOL>return h<EOL> | Add an event handler to be processed by this session.
type - The type of the event (pygame.QUIT, pygame.KEYUP ETC).
actions - The methods which should be called when an event matching this specification is received.
more than one action can be tied to a single event. This allows for secondary actions to occur along side already existing actions such as the down errow in the List.
You can either pass the actions or action as a single parameter or as a list.
kwargs - An arbitrary number of parameters which must be satisfied in order for the event to match.
The keywords are directly matched with the instance variables found in the current event
Each value for kwargs can optionally be a lambda which must evaluate to True in order for the match to work.
Example:
session.add_handler(pygame.QUIT, session.do_quit)
session.add_handler(pygame.KEYDOWN, lambda: ao2.speak("You pressed the enter key."), key = pygame.K_RETURN) | f170:c0:m5 |
def remove_handler(self, handler): | try:<EOL><INDENT>self._events[handler.type].remove(handler)<EOL>return True<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT> | Remove a handler from the list.
handler - The handler (as returned by add_handler) to remove.
Returns True on success, False otherwise. | f170:c0:m6 |
def add_keydown(self, actions, **kwargs): | return self.add_handler(pygame.KEYDOWN, actions, **kwargs)<EOL> | Add a pygame.KEYDOWN event handler.
actions - The methods to be called when this key is pressed.
kwargs - The kwargs to be passed to self.add_handler.
See the documentation for self.add_handler for examples. | f170:c0:m7 |
def add_keyup(self, actions, **kwargs): | return self.add_handler(pygame.KEYUP, actions, **kwargs)<EOL> | See the documentation for self.add_keydown. | f170:c0:m8 |
def change_event_params(self, handler, **kwargs): | if not isinstance(handler, Handler):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not self.remove_handler(handler):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.add_handler(handler.type, handler.actions, **kwargs)<EOL>self.event = handler.event<EOL> | This allows the client to change the parameters for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
kwargs - the variable number of keyword arguments for the parameters that must match the properties of the corresponding event. | f170:c0:m9 |
def change_event_actions(self, handler, actions): | if not isinstance(handler, Handler):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not self.remove_handler(handler):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.add_handler(handler.type, actions, handler.params)<EOL>self.event = handler.event<EOL> | This allows the client to change the actions for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
actions - The methods that are called when this handler is varified against the current event. | f170:c0:m10 |
def __init__(self, handlerSource, type, params, actions): | self._handlerSource = handlerSource <EOL>self._type = type<EOL>self._params = {}<EOL>self._actions = [actions] if not isinstance(actions, list) else actions<EOL>self._event = None <EOL>if self._handlerSource.logger is not None:<EOL><INDENT>self._handlerSource.logger.debug("<STR_LIT>".format(self))<EOL><DEDENT>for k, v in params.items():<EOL><INDENT>if callable(v):<EOL><INDENT>self._params[k] = v<EOL><DEDENT>else:<EOL><INDENT>self._params[k] = lambda value, actual = v: value == actual<EOL><DEDENT><DEDENT> | Create a new event handler.
handlerSource - The handlerSource class to which this handler is attached.
type - The type of this handler.
params - A dictionary containing parameters the calling event must conform to in order to succeed. The values of this dictionary can either be simple values or lambdas.
In the case of simple values, each value will be turned into a lambda of the form lambda against, actual = value: against == value.
actions - The functions which should be called when this handler has been verified.
When the provided actions are called, the current event that triggered the action is passed in as the first argument | f171:c0:m0 |
def call_actions(self, event, *args, **kwargs): | self._event = event<EOL>for func in self._actions:<EOL><INDENT>func(event, *args, **kwargs)<EOL><DEDENT> | Call each function in self._actions after setting self._event. | f171:c0:m5 |
def __str__(self): | return "<STR_LIT>".format(<EOL>self._handlerSource,<EOL>self._type,<EOL>self._params,<EOL>self._actions<EOL>)<EOL> | Return the data for this handler for testing. | f171:c0:m6 |
def __repr__(self): | return str(self)<EOL> | Return the Data in literal form for this object. | f171:c0:m7 |
def __init__(self): | super().__init__(logging.getLogger("<STR_LIT>"))<EOL>self._control = None <EOL>self._running = True<EOL> | Initialise a new Session object. | f172:c0:m0 |
def main_loop(self): | while True:<EOL><INDENT>for e in pygame.event.get():<EOL><INDENT>self.handle_event(e)<EOL><DEDENT>self.step()<EOL>pygame.time.wait(<NUM_LIT:5>)<EOL><DEDENT> | Runs the main game loop. | f172:c0:m1 |
def handle_event(self, event): | if self._control is not None and self._control.handle_event(event):<EOL><INDENT>return True<EOL><DEDENT>return super().handle_event(event)<EOL> | Handle an event. | f172:c0:m2 |
def step(self): | pass<EOL> | Method to be overwritten, to be called at the end of each iteration of the main loop. | f172:c0:m3 |
def on_exit(self): | pass<EOL> | Method to be overwritten, to be called at the end of program execution write before the program naturally ends. | f172:c0:m4 |
def quit(self, event): | self.logger.info("<STR_LIT>")<EOL>self.on_exit()<EOL>sys.exit()<EOL> | Quit the game. | f172:c0:m7 |
def stop_loop(self): | self._running = False<EOL>self.logger.debug("<STR_LIT>")<EOL> | Pause the game by setting self._running to False. | f172:c0:m8 |
def resume_loop(self): | self._running = True<EOL>self.logger.debug("<STR_LIT>")<EOL> | Unpause the game by setting self._running to True. | f172:c0:m9 |
def run_command(cmd_to_run): | with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file:<EOL><INDENT>popen = subprocess.Popen(cmd_to_run, stdout=stdout_file, stderr=stderr_file)<EOL>popen.wait()<EOL>stderr_file.seek(<NUM_LIT:0>)<EOL>stdout_file.seek(<NUM_LIT:0>)<EOL>stderr = stderr_file.read()<EOL>stdout = stdout_file.read()<EOL>if six.PY3:<EOL><INDENT>stderr = stderr.decode()<EOL>stdout = stdout.decode()<EOL><DEDENT>return stderr, stdout<EOL><DEDENT> | Wrapper around subprocess that pipes the stderr and stdout from `cmd_to_run`
to temporary files. Using the temporary files gets around subprocess.PIPE's
issues with handling large buffers.
Note: this command will block the python process until `cmd_to_run` has completed.
Returns a tuple, containing the stderr and stdout as strings. | f176:m0 |
def __init__(self, *args, **kwargs): | self.__values__ = dict((key, None) for key in self.__fields__)<EOL>for key, field in self.__fields__.items():<EOL><INDENT>field.__model__ = self<EOL><DEDENT>if args and args[<NUM_LIT:0>]:<EOL><INDENT>for key, value in kwargs.items():<EOL><INDENT>setattr(self, key, value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>errors = ErrorContainer()<EOL>for key, value in kwargs.items():<EOL><INDENT>try:<EOL><INDENT>setattr(self, key, value)<EOL><DEDENT>except UnitError as e:<EOL><INDENT>errors[key] = e<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>raise errors<EOL><DEDENT><DEDENT> | Args:
*args:
arg[0]: True or False.
**kwargs:
key: An option name.
value: An option's setting value. | f187:c1:m0 |
def __call__(self, *args, **kwargs): | self.__init__(*args, **kwargs)<EOL>return self<EOL> | Args:
Equal to __init__ constructor.
Returns:
self | f187:c1:m1 |
def __init__(self, field, *args, **kwargs): | self.field = field<EOL>self.args = args<EOL>self.kwargs = kwargs<EOL>validates = []<EOL>for key in field.__order__:<EOL><INDENT>option = field.__options__[key]<EOL>if key in kwargs:<EOL><INDENT>option.value = kwargs[key]<EOL>validates.append(<EOL>partial(option.func, field, option)<EOL>)<EOL><DEDENT>elif hasattr(option, "<STR_LIT:default>"):<EOL><INDENT>option.value = option.default<EOL>validates.append(<EOL>partial(option.func, field, option)<EOL>)<EOL><DEDENT>elif option.required or key in args:<EOL><INDENT>validates.append(partial(option.func, field, option))<EOL><DEDENT><DEDENT>self.validates = validates<EOL> | Args:
field: A Field instance.
*args: A list of validate function names.
**kwargs: Keyword arguments of the Field constructor.
key: An option name
value: An option setting value. | f188:c0:m0 |
def validate(self, value): | for validate in self.validates:<EOL><INDENT>value = validate(value)<EOL><DEDENT>return value<EOL> | Validate value.
Args:
value:
Returns:
A validated value.
Raises:
UnitError | f188:c0:m1 |
def __init__(self, field, option, value): | self.field = field<EOL>self.option = option<EOL>self.value = value<EOL>self.model_name = field.__model_name__<EOL>super(UnitError, self).__init__()<EOL> | Args:
field: A Field instance.
option: A option instance.
value: A value tried to set. | f190:c2:m0 |
def __init__(self, **kwargs): | self.name = "<STR_LIT>"<EOL>self.kwargs = kwargs<EOL>self.required = kwargs.get("<STR_LIT>", False)<EOL>self.value = None<EOL>if "<STR_LIT:default>" in kwargs:<EOL><INDENT>self.default = kwargs["<STR_LIT:default>"]<EOL><DEDENT> | Args:
**kwargs:
required: Whether this option is required (Default is False).
default: The option's default setting value. | f191:c0:m0 |
def __call__(self, func): | self.name = func.__name__<EOL>self.func = func<EOL>return self<EOL> | Args:
name: The option name.
func: The validation function.
Returns:
self | f191:c0:m1 |
def __init__(self, *args, **kwargs): | length = len(args)<EOL>validate_names = []<EOL>if not length:<EOL><INDENT>self._name = "<STR_LIT>"<EOL><DEDENT>elif length == <NUM_LIT:1>:<EOL><INDENT>arg = args[<NUM_LIT:0>]<EOL>if isinstance(arg, str):<EOL><INDENT>self._name = arg<EOL><DEDENT>else:<EOL><INDENT>validate_names = arg<EOL>self._name = "<STR_LIT>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._name = args[<NUM_LIT:0>]<EOL>validate_names = args[<NUM_LIT:1>]<EOL><DEDENT>self.__args__ = args<EOL>self.__kwargs__ = kwargs<EOL>self._value = None<EOL>self.__model_name__ = "<STR_LIT>"<EOL>self.__model__ = None<EOL>self.__validator__ = self.__Validator__(<EOL>self, *validate_names, **kwargs<EOL>)<EOL> | Args:
*args:
args[0]: A field name or list of option names.
args[1]: A list of option names.
*kwargs:
key: An option name.
value: An option's setting value. | f191:c2:m0 |
def __call__(self, request, *args, **kwargs): | try:<EOL><INDENT>obj = self.get_object(request, *args, **kwargs)<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>raise Http404('<STR_LIT>')<EOL><DEDENT>feedgen = self.get_feed(obj, request)<EOL>response = HttpResponse(content_type=feedgen.mime_type)<EOL>if hasattr(self, '<STR_LIT>') or hasattr(self, '<STR_LIT>'):<EOL><INDENT>response['<STR_LIT>'] = http_date(<EOL>timegm(feedgen.latest_post_date().utctimetuple()))<EOL><DEDENT>feedgen.write(response, '<STR_LIT:utf-8>')<EOL>filename = self._get_dynamic_attr('<STR_LIT>', obj)<EOL>if filename:<EOL><INDENT>response['<STR_LIT>'] = '<STR_LIT>' % filename<EOL><DEDENT>return response<EOL> | Copied from django.contrib.syndication.views.Feed
Supports file_name as a dynamic attr. | f195:c0:m0 |
def _get_dynamic_attr(self, attname, obj, default=None): | try:<EOL><INDENT>attr = getattr(self, attname)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return default<EOL><DEDENT>if callable(attr):<EOL><INDENT>try:<EOL><INDENT>code = six.get_function_code(attr)<EOL><DEDENT>except AttributeError:<EOL><INDENT>code = six.get_function_code(attr.__call__)<EOL><DEDENT>if code.co_argcount == <NUM_LIT:2>: <EOL><INDENT>return attr(obj)<EOL><DEDENT>else:<EOL><INDENT>return attr()<EOL><DEDENT><DEDENT>return attr<EOL> | Copied from django.contrib.syndication.views.Feed (v1.7.1) | f195:c0:m1 |
def build_rrule(count=None, interval=None, bysecond=None, byminute=None,<EOL>byhour=None, byweekno=None, bymonthday=None, byyearday=None,<EOL>bymonth=None, until=None, bysetpos=None, wkst=None, byday=None,<EOL>freq=None): | result = {}<EOL>if count is not None:<EOL><INDENT>result['<STR_LIT>'] = count<EOL><DEDENT>if interval is not None:<EOL><INDENT>result['<STR_LIT>'] = interval<EOL><DEDENT>if bysecond is not None:<EOL><INDENT>result['<STR_LIT>'] = bysecond<EOL><DEDENT>if byminute is not None:<EOL><INDENT>result['<STR_LIT>'] = byminute<EOL><DEDENT>if byhour is not None:<EOL><INDENT>result['<STR_LIT>'] = byhour<EOL><DEDENT>if byweekno is not None:<EOL><INDENT>result['<STR_LIT>'] = byweekno<EOL><DEDENT>if bymonthday is not None:<EOL><INDENT>result['<STR_LIT>'] = bymonthday<EOL><DEDENT>if byyearday is not None:<EOL><INDENT>result['<STR_LIT>'] = byyearday<EOL><DEDENT>if bymonth is not None:<EOL><INDENT>result['<STR_LIT>'] = bymonth<EOL><DEDENT>if until is not None:<EOL><INDENT>result['<STR_LIT>'] = until<EOL><DEDENT>if bysetpos is not None:<EOL><INDENT>result['<STR_LIT>'] = bysetpos<EOL><DEDENT>if wkst is not None:<EOL><INDENT>result['<STR_LIT>'] = wkst<EOL><DEDENT>if byday is not None:<EOL><INDENT>result['<STR_LIT>'] = byday<EOL><DEDENT>if freq is not None:<EOL><INDENT>if freq not in vRecur.frequencies:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>.format(vRecur.frequencies))<EOL><DEDENT>result['<STR_LIT>'] = freq<EOL><DEDENT>return result<EOL> | Build rrule dictionary for vRecur class.
:param count: int
:param interval: int
:param bysecond: int
:param byminute: int
:param byhour: int
:param byweekno: int
:param bymonthday: int
:param byyearday: int
:param bymonth: int
:param until: datetime
:param bysetpos: int
:param wkst: str, two-letter weekday
:param byday: weekday
:param freq: str, frequency name ('WEEK', 'MONTH', etc)
:return: dict | f196:m0 |
def build_rrule_from_text(rrule_str): | recurr = vRecur()<EOL>return recurr.from_ical(rrule_str)<EOL> | Build an rrule from a serialzed RRULE string. | f196:m1 |
def build_rrule_from_recurrences_rrule(rule): | from recurrence import serialize<EOL>line = serialize(rule)<EOL>if line.startswith('<STR_LIT>'):<EOL><INDENT>line = line[<NUM_LIT:6>:]<EOL><DEDENT>return build_rrule_from_text(line)<EOL> | Build rrule dictionary for vRecur class from a django_recurrences rrule.
django_recurrences is a popular implementation for recurrences in django.
https://pypi.org/project/django-recurrence/
this is a shortcut to interface between recurrences and icalendar. | f196:m2 |