text
stringlengths
81
112k
Embeds the current exception information into the given one (which will replace the current one). For example:: try: ... except OSError as ex: raise chained(MyError("database not found!")) def chained(wrapping_exc): # pylint: disable=W0212 """ Embeds the cur...
Get a user profile. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. event...
Get a user's best scores. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. ...
Get a user's most recent scores, within the last 24 hours. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. ...
Get the top scores for a given beatmap. Parameters ---------- beatmap_id Individual Beatmap ID to lookup. username : str or int A `str` representing the user's username, or an `int` representing the user's id. If specified, restricts returned scores to the specif...
Get beatmaps. Parameters ---------- since : datetime If specified, restrict results to beatmaps *ranked* after this date. beatmapset_id If specified, restrict results to a specific beatmap set. beatmap_id If specified, restrict results to a sp...
Get a multiplayer match. Parameters ---------- match_id The ID of the match to retrieve. This is the ID that you see in a online multiplayer match summary. This does not correspond the in-game game ID. def get_match(self, match_id): """Get a multiplayer match. ...
Return True if data are copied * optimized for http->fs copy * not supported return_status async def copy(self, key_source, storage_dest, key_dest): """ Return True if data are copied * optimized for http->fs copy * not supported return_status """ from aioworkers...
>>> import_name('datetime.datetime.utcnow') is not None True >>> import_name('aioworkers.utils.import_name') is not None True def import_name(stref: str): """ >>> import_name('datetime.datetime.utcnow') is not None True >>> import_name('aioworkers.utils.import_name') is not None True ...
A context-manager for setting connection options; the original values of the options will be restored when the context-manager exits. For example:: with c.options(gui_mode = False): c.cmd.vol_list() def options(self, **options): """A context-manager for setting con...
Sets the value of the given options (as keyword arguments). Note that underscored in the option's name will be replaced with hyphens (i.e., ``c.set_options(gui_mode = True)`` will set the option ``gui-mode``) def set_options(self, **options): """Sets the value of the given options (as k...
Creates an SSL transport to the first endpoint (aserver) to which we successfully connect def connect_ssl(cls, user, password, endpoints, ca_certs=None, validate=None): """ Creates an SSL transport to the first endpoint (aserver) to which we successfully connect ...
Creates a MultiEndpointTransport, so that if the current endpoint (aserver) fails, it would automatically move to the next available endpoint. If ``auto_discover`` is ``True``, we will execute ipinterface_list on the system to discover all management IP interfaces and add them t...
Executes the given command (with the given arguments) on the given remote target of the connected machine def execute_remote(self, remote_target, cmd, **kwargs): """ Executes the given command (with the given arguments) on the given remote target of the connected machine """ ...
Returns a new client for the given user. This is a lightweight client that only uses different credentials and shares the transport with the underlying client def get_user_client(self, user, password, populate=True): """ Returns a new client for the given user. This is a lightweight ...
Returns a new client for the remote target. This is a lightweight client that only uses different credentials and shares the transport with the underlying client def get_remote_client(self, target_name, user=None, password=None): """ Returns a new client for the remote target. This is a...
A context-manager for ``get_user_client``. Allows the execution of commands as a different user with ease. Example: >>> c.cmd.vol_list() >>> with c.as_user("user", "password"): ... c.cmd.vol_list() def as_user(self, user, password): """ A context-manager fo...
Calculated accuracy. See Also -------- <https://osu.ppy.sh/help/wiki/Accuracy> def accuracy(self, mode: OsuMode): """Calculated accuracy. See Also -------- <https://osu.ppy.sh/help/wiki/Accuracy> """ if mode is OsuMode.osu: return ( ...
creates a mirror and returns a mirror object. target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_cg name def create_mirror(self, resource_name, target_name, mirror_type, slave_reso...
return all non snapshots volumes in cg def get_cg_volumes(self, group_id): """ return all non snapshots volumes in cg """ for volume in self.xcli_client.cmd.vol_list(cg=group_id): if volume.snapshot_of == '': yield volume.name
returns true if connection should verify certificate def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT, ca_certs=None, validate=None): ''' returns true if connection should verify certificate ''' if not ca_certs: return False ...
Add converter :param klass: class or str :param conv: callable :param score: :return: def add_converter(cls, klass, conv, score=0): """ Add converter :param klass: class or str :param conv: callable :param score: :return: """ if is...
Helper function to recursively populates a Bunch from an XML tree. Returns leaf XML elements as a simple value, branch elements are returned as Bunches containing their subelements as value or recursively generated Bunch members. def _populate_bunch_with_element(element): """ Helper function to rec...
Generates Bunches, each representing a single subelement of the response. If an element_type is requested, only elements whose tag matches the element_type are returned. If the response has no subelements (for example, in a <return>-less command), yields None. def all(self, element_type=None, r...
Processes the response as a single-element response, like config_get or system_counters_get. If there is more then one element in the response or no elements this raises a ResponseError def as_single_element(self): """ Processes the response as a single-element response, ...
Return the objects for each individual set flag. def enabled_flags(self): """Return the objects for each individual set flag.""" if not self.value: yield self.__flags_members__[0] return val = self.value while val: lowest_bit = val & -val ...
Check if any flags are set. (OsuMod.Hidden | OsuMod.HardRock) in flags # Check if either hidden or hardrock are enabled. OsuMod.keyMod in flags # Check if any keymod is enabled. def contains_any(self, other): """Check if any flags are set. (OsuMod.Hidden | OsuMod.HardRock) in flags # ...
Get the cumulative time percentage of each stopwatch (including the current split). Returns ------- cumulative_elapsed_time_percentage : List[float] def get_percentage(self): """Get the cumulative time percentage of each stopwatch (including the current split). Returns ...
Get the mean elapsed time per split of each stopwatch (excluding the current split). Returns ------- mean_elapsed_time_per_split : List[datetime.timedelta] def get_mean_per_split(self): """Get the mean elapsed time per split of each stopwatch (excluding the current split). Ret...
Get all statistics as a dictionary. Returns ------- statistics : Dict[str, List] def get_statistics(self): """Get all statistics as a dictionary. Returns ------- statistics : Dict[str, List] """ return { 'cumulative_elapsed_time': se...
Converts the query string from a target uri, uses cls.default_query to populate default arguments. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.default_query will be set if not passe...
Override this method to use values from the parsed uri to initialize the expected target. def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): """Override this method to use values from the parsed uri to ...
Sending multiple `HTTP` requests `ON` `GREEN` thread def hog(concurrency, requests, limit, timeout, params, paramfile, headers, headerfile, method, url): '''Sending multiple `HTTP` requests `ON` `GREEN` thread''' params = parse_from_list_and_file(params, paramfile) headers = parse_from_list_and_fi...
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict def _append_value(self, value, _file, _name): """Call this function to write contents. Ke...
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_array(self, value, _file): """Call this function to write array contents. Keyword arguments: * value - dict, conten...
Call this function to write dict contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_dict(self, value, _file): """Call this function to write dict contents. Keyword arguments: * value - dict, content t...
Call this function to write data contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_data(self, value, _file): """Call this function to write data contents. Keyword arguments: * value - dict, content t...
Call this function to write date contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_date(self, value, _file): """Call this function to write date contents. Keyword arguments: * value - dict, content t...
Call this function to write integer contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_integer(self, value, _file): """Call this function to write integer contents. Keyword arguments: * value - dict, ...
Register proper and improper file mappings. def register_output_name(self, input_folder, rel_name, rel_output_name): """Register proper and improper file mappings.""" self.improper_input_file_mapping[rel_name].add(rel_output_name) self.proper_input_file_mapping[os.path.join(input_folder, rel_na...
Find and install all extensions def _discover(self): """Find and install all extensions""" for ep in pkg_resources.iter_entry_points('yamlsettings10'): ext = ep.load() if callable(ext): ext = ext() self.add(ext)
Retrieve extension for the given protocol :param protocol: name of the protocol :type protocol: string :raises NoProtocolError: no extension registered for protocol def get_extension(self, protocol): """Retrieve extension for the given protocol :param protocol: name of the pro...
Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.base.YamlSettingsExtension def add(self, extension): """Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.b...
Load first yamldict target found in uri list. :param target_uris: Uris to try and open :param load_method: load callback :type target_uri: list or string :type load_method: callback :returns: yamldict def _load_first(self, target_uris, load_method, **kwargs): """Load f...
Load first yamldict target found in uri. :param target_uris: Uris to try and open :param fields: Fields to filter. Default: None :type target_uri: list or string :type fields: list :returns: yamldict def load(self, target_uris, fields=None, **kwargs): """Load first yam...
Load *all* YAML settings from a list of file paths given. - File paths in the list gets the priority by their orders of the list. def load_all(self, target_uris, **kwargs): ''' Load *all* YAML settings from a list of file paths given. - File paths in the list gets ...
Parse all YAML documents in a stream and produce corresponding YAMLDict objects. def load_all(stream): """ Parse all YAML documents in a stream and produce corresponding YAMLDict objects. """ loader = YAMLDictLoader(stream) try: while loader.check_data(): yield loader.ge...
Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead. def dump(data, stream=None, **kwargs): """ Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead. """ return yaml.dump_all( [data], stream=stream,...
Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead. def dump_all(data_list, stream=None, **kwargs): """ Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead. """ return yaml.dump_all( data_list, st...
Traverse through all keys and values (in-order) and replace keys and values with the return values from the callback function. def traverse(self, callback): ''' Traverse through all keys and values (in-order) and replace keys and values with the return values fro...
Update the content (i.e. keys and values) with yaml_dict. def update(self, yaml_dict): ''' Update the content (i.e. keys and values) with yaml_dict. ''' def _update_node(base_node, update_node): if isinstance(update_node, YAMLDict) or \ isinstance(update_node, di...
Use yaml_dict as self's new base and update with existing reverse of update. def rebase(self, yaml_dict): ''' Use yaml_dict as self's new base and update with existing reverse of update. ''' base = yaml_dict.clone() base.update(self) self.clear() ...
Remove all keys other than the keys specified. def limit(self, keys): ''' Remove all keys other than the keys specified. ''' if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in ...
Save YAML settings to the specified file path. def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
Save *all* YAML settings to the specified file path. def save_all(yaml_dicts, filepath): ''' Save *all* YAML settings to the specified file path. ''' yamldict.dump_all(yaml_dicts, open(filepath, 'w'), default_flow_style=False)
Override YAML settings with loaded values from filepaths. - File paths in the list gets the priority by their orders of the list. def update_from_file(yaml_dict, filepaths): ''' Override YAML settings with loaded values from filepaths. - File paths in the list gets the priority by their order...
Override YAML settings with values from the environment variables. - The letter '_' is delimit the hierarchy of the YAML settings such that the value of 'config.databases.local' will be overridden by CONFIG_DATABASES_LOCAL. def update_from_env(yaml_dict, prefix=None): ''' Override ...
Draw a circle def circle(rad=0.5): """Draw a circle""" _ctx = _state["ctx"] _ctx.arc(0, 0, rad, 0, 2 * math.pi) _ctx.set_line_width(0) _ctx.stroke_preserve() # _ctx.set_source_rgb(0.3, 0.4, 0.6) _ctx.fill()
Draw a line def line(x, y, width=0.1): """Draw a line""" ctx = _state["ctx"] ctx.move_to(0, 0) ctx.line_to(x, y) ctx.close_path() # _ctx.set_source_rgb (0.3, 0.2, 0.5) ctx.set_line_width(width) ctx.stroke()
Draw a triangle def triangle(rad=0.5): """Draw a triangle""" # half_height = math.sqrt(3) * side / 6 # half_height = side / 2 ctx = _state["ctx"] side = 3 * rad / math.sqrt(3) ctx.move_to(0, -rad / 2) ctx.line_to(-side / 2, -rad / 2) ctx.line_to(0, rad) ctx.line_to(side / 2, -rad / ...
Draw a box def box(side=1): """Draw a box""" half_side = side / 2 _state["ctx"].rectangle(-half_side, -half_side, side, side) _state["ctx"].fill()
Initially dump file heads and tails. def _dump_header(self): """Initially dump file heads and tails.""" with open(self._file, 'w') as _file: _file.write(self._hsrt) self._sptr = _file.tell() _file.write(self._hend)
Simulate behaviour of "from package_name._version import VERSION", and return VERSION. def find_version( package_name: str, version_module_name: str = '_version', version_variable_name: str = 'VERSION') -> str: """Simulate behaviour of "from package_name._version import VERSION", and return VERSION...
Find packages to pack. def find_packages(root_directory: str = '.') -> t.List[str]: """Find packages to pack.""" exclude = ['test*', 'test.*'] if ('bdist_wheel' in sys.argv or 'bdist' in sys.argv) else [] packages_list = setuptools.find_packages(root_directory, exclude=exclude) return packages_list
Read contents of requirements.txt file and return data from its relevant lines. Only non-empty and non-comment lines are relevant. def parse_requirements( requirements_path: str = 'requirements.txt') -> t.List[str]: """Read contents of requirements.txt file and return data from its relevant lines. ...
Find version number classifiers in given list and partition them into 2 groups. def partition_version_classifiers( classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ', only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]: """Find version number cl...
Determine the minimum required Python version. def find_required_python_version( classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ', only_suffix: str = ' :: Only') -> t.Optional[str]: """Determine the minimum required Python version.""" versions_min, versio...
Parse text assuming it's an RST markup. def parse_rst(text: str) -> docutils.nodes.document: """Parse text assuming it's an RST markup.""" parser = docutils.parsers.rst.Parser() components = (docutils.parsers.rst.Parser,) settings = docutils.frontend.OptionParser(components=components).get_default_valu...
Resolve all relative links in a given RST document. All links of form `link`_ become `link <base_link/link>`_. def resolve_relative_rst_links(text: str, base_link: str): """Resolve all relative links in a given RST document. All links of form `link`_ become `link <base_link/link>`_. """ document ...
Called for "reference" nodes. def visit_reference(self, node: docutils.nodes.reference) -> None: """Called for "reference" nodes.""" # if len(node.children) != 1 or not isinstance(node.children[0], docutils.nodes.Text) \ # or not all(_ in node.attributes for _ in ('name', 'refuri')): ...
Return first existing of given class field names. def try_fields(cls, *names) -> t.Optional[t.Any]: """Return first existing of given class field names.""" for name in names: if hasattr(cls, name): return getattr(cls, name) raise AttributeError((cls, names))
Parse readme and resolve relative links in it if it is feasible. Links are resolved if readme is in rst format and the package is hosted on GitHub. def parse_readme(cls, readme_path: str = 'README.rst', encoding: str = 'utf-8') -> str: """Parse readme and resolve relative links in it if it is feasible...
Fill in possibly missing package metadata. def prepare(cls) -> None: """Fill in possibly missing package metadata.""" if cls.version is None: cls.version = find_version(cls.name) if cls.long_description is None: cls.long_description = cls.parse_readme() if cls.pa...
Run setuptools.setup() with correct arguments. def setup(cls) -> None: """Run setuptools.setup() with correct arguments.""" cls.prepare() setuptools.setup( name=cls.name, version=cls.version, description=cls.description, long_description=cls.long_description, url=cls.url...
Renders current buffer surface to IPython image def surface_to_image(surface): """Renders current buffer surface to IPython image""" from IPython.display import Image buf = BytesIO() surface.write_to_png(buf) data = buf.getvalue() buf.close() return Image(data=data)
Returns a WxHx[3-4] numpy array representing the RGB picture. If `transparent` is True the image is WxHx4 and represents a RGBA picture, i.e. array[i,j] is the [r,g,b,a] value of the pixel at position [i,j]. If `transparent` is false, a RGB array is returned. Parameter y_origin ("top" or "bottom") dec...
Stop recursion if resolution is too low on number of components is too high def check_limits(user_rule): """Stop recursion if resolution is too low on number of components is too high """ def wrapper(*args, **kwargs): """The body of the decorator """ global _state _state["cnt_elements"...
Initializes global state def init(canvas_size=(512, 512), max_depth=12, face_color=None, background_color=None): """Initializes global state""" global _background_color _background_color = background_color global _ctx global cnt_elements global MAX_DEPTH global WIDTH global HEIGHT ...
function to convert HTML-styly color string to RGB values Args: s: Color in HTML format Returns: list of three RGB color components def htmlcolor_to_rgb(str_color): """function to convert HTML-styly color string to RGB values Args: s: Color in HTML format Returns: ...
Compile docstrings into HTML strings, with shortcode support. def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None): """Compile docstrings into HTML strings, with shortcode support.""" if not is_two_file: _, data = self.split_metadata(data, None, lang) ...
Compile the docstring into HTML and save as dest. def compile(self, source, dest, is_two_file=True, post=None, lang=None): """Compile the docstring into HTML and save as dest.""" makedirs(os.path.dirname(dest)) with io.open(dest, "w+", encoding="utf8") as out_file: with io.open(sour...
Create a new post. def create_post(self, path, **kw): """Create a new post.""" content = kw.pop('content', None) onefile = kw.pop('onefile', False) # is_page is not used by create_post as of now. kw.pop('is_page', False) metadata = {} metadata.update(self.default...
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict def _append_value(self, value, _file, _name): """Call this function to write contents. Ke...
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_array(self, value, _file): """Call this function to write array contents. Keyword arguments: * value - dict, conten...
Call this function to write branch contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_branch(self, value, _file): """Call this function to write branch contents. Keyword arguments: * value - dict, con...
Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_bytes(self, value, _file): """Call this function to write bytes contents. Keyword arguments: * value - dict, conten...
Call this function to write number contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_number(self, value, _file): # pylint: disable=no-self-use """Call this function to write number contents. Keyword arguments: ...
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict def _append_value(self, value, _file, _name): """Call this function to write contents. Ke...
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_array(self, value, _file): """Call this function to write array contents. Keyword arguments: * value - dict, conten...
Call this function to write object contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_object(self, value, _file): """Call this function to write object contents. Keyword arguments: * value - dict, con...
Call this function to write string contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_string(self, value, _file): # pylint: disable=no-self-use """Call this function to write string contents. Keyword arguments: ...
Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_bytes(self, value, _file): # pylint: disable=no-self-use """Call this function to write bytes contents. Keyword arguments: ...
Call this function to write date contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file def _append_date(self, value, _file): # pylint: disable=no-self-use """Call this function to write date contents. Keyword arguments: ...
Start the stopwatch if it is paused. If the stopwatch is already started, then nothing will happen. Parameters ---------- verbose : Optional[bool] Wether to log. If `None`, use `verbose_start` set during initialization. end_in_new_line : Optional[bool]] ...
Pause the stopwatch. If the stopwatch is already paused, nothing will happen. def pause(self): """Pause the stopwatch. If the stopwatch is already paused, nothing will happen. """ if self._end_time is not None: # the stopwatch is already paused return ...
Get the elapsed time of the current split. def get_elapsed_time(self): """Get the elapsed time of the current split. """ if self._start_time is None or self._end_time is not None: # the stopwatch is paused return self._elapsed_time return self._elapsed_time + (da...
Save the elapsed time of the current split and restart the stopwatch. The current elapsed time will be appended to :attr:`split_elapsed_time`. If the stopwatch is paused, then it will remain paused. Otherwise, it will continue running. Parameters ---------- verbose : Op...
Reset the stopwatch. def reset(self): """Reset the stopwatch. """ self._start_time = None self._end_time = None self._elapsed_time = datetime.timedelta() self._cumulative_elapsed_time = datetime.timedelta() self.split_elapsed_time = []
Wrapper for using bbduk to quality trim reads. Contains arguments used in OLC Assembly Pipeline, but these can be overwritten by using keyword parameters. :param forward_in: Forward reads you want to quality trim. :param returncmd: If set to true, function will return the cmd string passed to subprocess as ...
Finds the genome size of an organsim, based on the peaks file created by kmercountexact.sh :param peaks_file: Path to peaks file created by kmercountexact. :param haploid: Set to True if organism of interest is haploid, False if not. Default True. :return: size of genome, as an int. If size could not be fou...