code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def traverse_rootdistorder(self, ascending=True, leaves=True, internal=True): '''Perform a traversal of the ``Node`` objects in this ``Tree`` in either ascending (``ascending=True``) or descending (``ascending=False``) order of distance from the root Args: ``ascending`` (``bool``): ``True``...
Perform a traversal of the ``Node`` objects in this ``Tree`` in either ascending (``ascending=True``) or descending (``ascending=False``) order of distance from the root Args: ``ascending`` (``bool``): ``True`` to perform traversal in ascending distance from the root, otherwise ``False`` for descen...
def build(self, recipe, plugin=None): """ Execute a recipe and creates new folder and files. :param recipe: Name of the recipe :param plugin: Name of the plugin, to which the recipe must belong. """ if recipe not in self.recipes.keys(): raise RecipeMissingExc...
Execute a recipe and creates new folder and files. :param recipe: Name of the recipe :param plugin: Name of the plugin, to which the recipe must belong.
def get_log_nodes(self, log_id, ancestor_levels, descendant_levels, include_siblings): """Gets a portion of the hierarchy for the given log. arg: log_id (osid.id.Id): the ``Id`` to query arg: ancestor_levels (cardinal): the maximum number of ancestor levels to include. A v...
Gets a portion of the hierarchy for the given log. arg: log_id (osid.id.Id): the ``Id`` to query arg: ancestor_levels (cardinal): the maximum number of ancestor levels to include. A value of 0 returns no parents in the node. arg: descendant_levels (cardi...
def getComicData(self, comic): """Return dictionary with comic info.""" if comic not in self.data: if os.path.exists(self.jsonFn(comic)): with codecs.open(self.jsonFn(comic), 'r', self.encoding) as f: self.data[comic] = json.load(f) else: ...
Return dictionary with comic info.
def create_module_item(self, course_id, module_id, module_item_type, module_item_content_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_new_tab=None, module_item_page_url=None, module_item_position=...
Create a module item. Create and return a new module item
def getContext(self, context_name = 'default'): """Get a context by name, create the default context if it does not exist Params: context_name (string): Context name Raises: KeyError: If the context name does not exist Returns: bubbler.Bubbler: Named context """ if con...
Get a context by name, create the default context if it does not exist Params: context_name (string): Context name Raises: KeyError: If the context name does not exist Returns: bubbler.Bubbler: Named context
def delete_intel_notifications(self, ids, timeout=None): """ Programmatically delete notifications via the Intel API. :param ids: A list of IDs to delete from the notification feed. :returns: The post response. """ if not isinstance(ids, list): raise TypeError("ids m...
Programmatically delete notifications via the Intel API. :param ids: A list of IDs to delete from the notification feed. :returns: The post response.
def _prepare_put_or_patch(self, kwargs): """Retrieve the appropriate request items for put or patch calls.""" requests_params = self._handle_requests_params(kwargs) update_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] read_only = self....
Retrieve the appropriate request items for put or patch calls.
def cleanup(self): """Clean up this Pipeline and all Datastore records used for coordination. Only works when called on a root pipeline. Child pipelines will ignore calls to this method. After this method is called, Pipeline.from_id() and related status methods will return inconsistent or missing ...
Clean up this Pipeline and all Datastore records used for coordination. Only works when called on a root pipeline. Child pipelines will ignore calls to this method. After this method is called, Pipeline.from_id() and related status methods will return inconsistent or missing results. This method is ...
def demultiplex_cells(fastq, out_dir, readnumber, prefix, cb_histogram, cb_cutoff): ''' Demultiplex a fastqtransformed FASTQ file into a FASTQ file for each cell. ''' annotations = detect_fastq_annotations(fastq) re_string = construct_transformed_regex(annotations) parser_...
Demultiplex a fastqtransformed FASTQ file into a FASTQ file for each cell.
def read_crl(crl): ''' Returns a dict containing details of a certificate revocation list. Input can be a PEM string or file path. :depends: - OpenSSL command line tool csl: A path or PEM encoded string containing the CSL to read. CLI Example: .. code-block:: bash salt...
Returns a dict containing details of a certificate revocation list. Input can be a PEM string or file path. :depends: - OpenSSL command line tool csl: A path or PEM encoded string containing the CSL to read. CLI Example: .. code-block:: bash salt '*' x509.read_crl /etc/pki/myc...
def reader(path_or_f): """ Turns a path to a compressed file into a file-like object of (decompressed) data. :Parameters: path : `str` the path to the dump file to read """ if hasattr(path_or_f, "read"): return path_or_f else: path = path_or_f path =...
Turns a path to a compressed file into a file-like object of (decompressed) data. :Parameters: path : `str` the path to the dump file to read
async def ttl(self, key, param=None): """get time to live of a specific identity""" identity = self._gen_identity(key, param) return await self.client.ttl(identity)
get time to live of a specific identity
def save_token(self, access_token): """ Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`. """ key = self._generate_cache_key(access_token.token) self.mc.set(key, access_token.__dict__) unique_token_key = self._...
Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`.
def stringify(self, value): """Convert value to string This method is used to generate a simple JSON representation of the object (without dereferencing objects etc.) """ # SuperModel -> UID if ISuperModel.providedBy(value): return str(value) # DateTi...
Convert value to string This method is used to generate a simple JSON representation of the object (without dereferencing objects etc.)
def show(cmap, var, vmin=None, vmax=None): '''Show a colormap for a chosen input variable var side by side with black and white and jet colormaps. :param cmap: Colormap instance :param var: Variable to plot. :param vmin=None: Min plot value. :param vmax=None: Max plot value. ''' # get...
Show a colormap for a chosen input variable var side by side with black and white and jet colormaps. :param cmap: Colormap instance :param var: Variable to plot. :param vmin=None: Min plot value. :param vmax=None: Max plot value.
def distance(self, i, j): # TODO: check docstring """Returns the distance between node i and node j Parameters ---------- i : type Descr j : type Desc Returns ------- float Distance between ...
Returns the distance between node i and node j Parameters ---------- i : type Descr j : type Desc Returns ------- float Distance between node i and node j.
def read(self, *, level=0, alignment=1) -> bytes: ''' Read the content of the texture into a buffer. Keyword Args: level (int): The mipmap level. alignment (int): The byte alignment of the pixels. Returns: bytes ''' ...
Read the content of the texture into a buffer. Keyword Args: level (int): The mipmap level. alignment (int): The byte alignment of the pixels. Returns: bytes
def wait_for_notification(self, notification_class=BaseNotification): """Wait for the specified notification to be displayed. Args: notification_class (:py:class:`BaseNotification`, optional): The notification class to wait for. If `None` is specified it will...
Wait for the specified notification to be displayed. Args: notification_class (:py:class:`BaseNotification`, optional): The notification class to wait for. If `None` is specified it will wait for any notification to be closed. Defaults to `BaseNotific...
def namedb_accounts_vest(cur, block_height): """ Vest tokens at this block to all recipients. Goes through the vesting table and debits each account that should vest on this block. """ sql = 'SELECT * FROM account_vesting WHERE block_id = ?' args = (block_height,) vesting_rows = namedb_quer...
Vest tokens at this block to all recipients. Goes through the vesting table and debits each account that should vest on this block.
def _CheckWindowsRegistryKeyPath( self, filename, artifact_definition, key_path): """Checks if a path is a valid Windows Registry key path. Args: filename (str): name of the artifacts definition file. artifact_definition (ArtifactDefinition): artifact definition. key_path (str): Windows...
Checks if a path is a valid Windows Registry key path. Args: filename (str): name of the artifacts definition file. artifact_definition (ArtifactDefinition): artifact definition. key_path (str): Windows Registry key path to validate. Returns: bool: True if the Windows Registry key path...
def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): ''' Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either ...
Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a ...
def check_bed_coords(in_file, data): """Ensure BED file coordinates match reference genome. Catches errors like using a hg38 BED file for an hg19 genome run. """ if dd.get_ref_file(data): contig_sizes = {} for contig in ref.file_contigs(dd.get_ref_file(data)): contig_sizes[c...
Ensure BED file coordinates match reference genome. Catches errors like using a hg38 BED file for an hg19 genome run.
def run_init(args): """ Run project initialization. This will ask the user for input. Parameters ---------- args : argparse named arguments """ root = args.root if root is None: root = '.' root = os.path.abspath(root) project_data = _get_package_data() project_...
Run project initialization. This will ask the user for input. Parameters ---------- args : argparse named arguments
def _process(self, envelope, session, mode, **kwargs): """ :meth:`.WMessengerOnionLayerProto.process` implementation """ if mode == WMessengerOnionPackerLayerProto.Mode.pack: return self.pack(envelope, session, **kwargs) else: # mode == WMessengerOnionPackerLayerProto.Mode.unpack return self.unpack(envel...
:meth:`.WMessengerOnionLayerProto.process` implementation
def grant_permission_to_users(self, permission, **kwargs): # noqa: E501 """Grants a specific user permission to multiple users # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
Grants a specific user permission to multiple users # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.grant_permission_to_users(permission, async_req=True) >>> r...
def read_file(self, file: Union[IO, asyncio.StreamWriter]=None): '''Read from connection to file. Args: file: A file object or a writer stream. ''' if file: file_is_async = hasattr(file, 'drain') while True: data = yield from self._connection...
Read from connection to file. Args: file: A file object or a writer stream.
def upgrade(yes, dry_run, patches): """ Upgrade the datamodel by applying recusively the patches available """ patcher = _get_mongopatcher() if dry_run: patcher.discover_and_apply(directory=patches, dry_run=dry_run) else: if (yes or prompt_bool("Are you sure you want to alter %s"...
Upgrade the datamodel by applying recusively the patches available
def contains_point(self, pt): """Is the point inside this rect?""" return (self.l < pt.x and self.r > pt.x and self.t < pt.y and self.b > pt.y)
Is the point inside this rect?
def urlForViewState(self, person, viewState): """ Return a url for L{OrganizerFragment} which will display C{person} in state C{viewState}. @type person: L{Person} @type viewState: L{ORGANIZER_VIEW_STATES} constant. @rtype: L{url.URL} """ # ideally there...
Return a url for L{OrganizerFragment} which will display C{person} in state C{viewState}. @type person: L{Person} @type viewState: L{ORGANIZER_VIEW_STATES} constant. @rtype: L{url.URL}
def iter_statuses(self, number=-1, etag=None): """Iterate over the deployment statuses for this deployment. :param int number: (optional), the number of statuses to return. Default: -1, returns all statuses. :param str etag: (optional), the ETag header value from the last time ...
Iterate over the deployment statuses for this deployment. :param int number: (optional), the number of statuses to return. Default: -1, returns all statuses. :param str etag: (optional), the ETag header value from the last time you iterated over the statuses. :returns: g...
def reindex(args): """ %prog agpfile assume the component line order is correct, modify coordinates, this is necessary mostly due to manual edits (insert/delete) that disrupts the target coordinates. """ p = OptionParser(reindex.__doc__) p.add_option("--nogaps", default=False, action="s...
%prog agpfile assume the component line order is correct, modify coordinates, this is necessary mostly due to manual edits (insert/delete) that disrupts the target coordinates.
def build_from_job_list(scheme_files, templates, base_output_dir): """Use $scheme_files as a job lists and build base16 templates using $templates (a list of TemplateGroup objects).""" queue = Queue() for scheme in scheme_files: queue.put(scheme) if len(scheme_files) < 40: thread_nu...
Use $scheme_files as a job lists and build base16 templates using $templates (a list of TemplateGroup objects).
def bin_pkg_info(path, saltenv='base'): ''' .. versionadded:: 2015.8.0 Parses RPM metadata and returns a dictionary of information about the package (name, version, etc.). path Path to the file. Can either be an absolute path to a file on the minion, or a salt fileserver URL (e.g. ...
.. versionadded:: 2015.8.0 Parses RPM metadata and returns a dictionary of information about the package (name, version, etc.). path Path to the file. Can either be an absolute path to a file on the minion, or a salt fileserver URL (e.g. ``salt://path/to/file.rpm``). If a salt file...
def activate_view(self, request, user_id, token): """ View function that activates the given User by setting `is_active` to true if the provided information is verified. """ try: user = self.user_model.objects.get(id=user_id, is_active=False) except self.user_...
View function that activates the given User by setting `is_active` to true if the provided information is verified.
def update(self, enabled): """ Update the InstalledAddOnExtensionInstance :param bool enabled: A Boolean indicating if the Extension will be invoked :returns: Updated InstalledAddOnExtensionInstance :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_exten...
Update the InstalledAddOnExtensionInstance :param bool enabled: A Boolean indicating if the Extension will be invoked :returns: Updated InstalledAddOnExtensionInstance :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance
def call_rpc(self, address, rpc_id, payload=b""): """Call an RPC by its address and ID. Args: address (int): The address of the mock tile this RPC is for rpc_id (int): The number of the RPC payload (bytes): A byte string of payload parameters up to 20 bytes ...
Call an RPC by its address and ID. Args: address (int): The address of the mock tile this RPC is for rpc_id (int): The number of the RPC payload (bytes): A byte string of payload parameters up to 20 bytes Returns: bytes: The response payload from the RPC
def save(self, saveModelDir): """ Save the model in the given directory. :param saveModelDir: (string) Absolute directory path for saving the model. This directory should only be used to store a saved model. If the directory does not exist, it will be created automatically and popula...
Save the model in the given directory. :param saveModelDir: (string) Absolute directory path for saving the model. This directory should only be used to store a saved model. If the directory does not exist, it will be created automatically and populated with model data. A pre-ex...
def driver_name(self): """ Returns the name of the driver that provides this tacho motor device. """ (self._driver_name, value) = self.get_cached_attr_string(self._driver_name, 'driver_name') return value
Returns the name of the driver that provides this tacho motor device.
def is_driver(self): """Check whether the file is a Windows driver. This will return true only if there are reliable indicators of the image being a driver. """ # Checking that the ImageBase field of the OptionalHeader is above or # equal to 0x80000000 (that is, whether...
Check whether the file is a Windows driver. This will return true only if there are reliable indicators of the image being a driver.
def _get_simple_score(self, profile: List[str], negated_classes: List[str], bg_mean_pic: float, bg_mean_max_pic: float, bg_mean_sum_pic: float, negation_weight: Opt...
Simple score is the average of the relative mean ic, max ic, and sum ic (relative to global stats) :param ic_map: dictionary of class - information content mappings :param bg_mean_pic: the average of the average IC in the background profile annotations :param...
def _kalman_prediction_step(k, p_m , p_P, p_dyn_model_callable, calc_grad_log_likelihood=False, p_dm = None, p_dP = None): """ Desctrete prediction function Input: k:int Iteration No. Starts at 0. Total number of iterations equal to th...
Desctrete prediction function Input: k:int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. p_m: matrix of size (state_dim, time_series_no) Mean value from the previous step. For "multiple time se...
def ipaddress(): ''' Determine our own IP adress. This seems to be far more complicated than you would think: ''' try: import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("gmail.com", 80)) result = s.getsockname()[0] s.close() ...
Determine our own IP adress. This seems to be far more complicated than you would think:
def convert_geojson_to_shapefile(geojson_path): """Convert geojson file to shapefile. It will create a necessary file next to the geojson file. It will not affect another files (e.g. .xml, .qml, etc). :param geojson_path: The path to geojson file. :type geojson_path: basestring :returns: True...
Convert geojson file to shapefile. It will create a necessary file next to the geojson file. It will not affect another files (e.g. .xml, .qml, etc). :param geojson_path: The path to geojson file. :type geojson_path: basestring :returns: True if shapefile layer created, False otherwise. :rtyp...
def threadsafe_generator(generator_func): """A decorator that takes a generator function and makes it thread-safe. """ def decoration(*args, **keyword_args): """A thread-safe decoration for a generator function.""" return ThreadSafeIter(generator_func(*args, **keyword_args)) return decor...
A decorator that takes a generator function and makes it thread-safe.
def is_set(name): """Helper method to check if given property is set""" val = os.environ.get(name, '0') assert val == '0' or val == '1', f"env var {name} has value {val}, expected 0 or 1" return val == '1'
Helper method to check if given property is set
def _set_ldp(self, v, load=False): """ Setter method for ldp, mapped from YANG variable /mpls_state/ldp (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp is considered as a private method. Backends looking to populate this variable should do so via ...
Setter method for ldp, mapped from YANG variable /mpls_state/ldp (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ldp() directly. YANG ...
def register(): """ Calls the shots, based on signals """ signals.article_generator_finalized.connect(link_source_files) signals.page_generator_finalized.connect(link_source_files) signals.page_writer_finalized.connect(write_source_files)
Calls the shots, based on signals
def write(self): """ Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning. """ if self.text is None: # Text has not been sent through the pipe yet. # Do not write anything until it is set to no...
Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning.
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Set CPC Power Save (any CPC mode).""" assert wait_for_completion is True # async not supported yet cpc_oid = uri_parms[0] try: cpc = hmc.cpcs.lookup_by_oid(cpc_oid) ...
Operation: Set CPC Power Save (any CPC mode).
def connect(self, (host, port)): ''' Connect using a host,port tuple ''' super(GeventTransport, self).connect((host, port), klass=socket.socket)
Connect using a host,port tuple
def _validate_config(self): """Ensure at least one switch is configured""" if len(cfg.CONF.ml2_arista.get('switch_info')) < 1: msg = _('Required option - when "sec_group_support" is enabled, ' 'at least one switch must be specified ') LOG.exception(msg) ...
Ensure at least one switch is configured
def __get_enabled_heuristics(self, url): """ Get the enabled heuristics for a site, merging the default and the overwrite together. The config will only be read once and the merged site-config will be cached. :param str url: The url to get the heuristics for. """...
Get the enabled heuristics for a site, merging the default and the overwrite together. The config will only be read once and the merged site-config will be cached. :param str url: The url to get the heuristics for.
def process_event(self, module_name, event, default_event=False): """ Process the event for the named module. Events may have been declared in i3status.conf, modules may have on_click() functions. There is a default middle click event etc. """ # get the module that the e...
Process the event for the named module. Events may have been declared in i3status.conf, modules may have on_click() functions. There is a default middle click event etc.
def edit_pool(self, id): """ Edit a pool. """ # extract attributes p = Pool.get(int(id)) if 'name' in request.json: p.name = validate_string(request.json, 'name') if 'description' in request.json: p.description = validate_string(request.json, 'des...
Edit a pool.
def validated_element(x, tags=None, attrs=None): """Checks if the root element of an XML document or Element meets the supplied criteria. *tags* if specified is either a single allowable tag name or sequence of allowable alternatives *attrs* if specified is a sequence of required attributes, each of which...
Checks if the root element of an XML document or Element meets the supplied criteria. *tags* if specified is either a single allowable tag name or sequence of allowable alternatives *attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives ...
def _back_compatible_gemini(conf_files, data): """Provide old install directory for configuration with GEMINI supplied tidy VCFs. Handles new style (bcbio installed) and old style (GEMINI installed) configuration and data locations. """ if vcfanno.is_human(data, builds=["37"]): for f in con...
Provide old install directory for configuration with GEMINI supplied tidy VCFs. Handles new style (bcbio installed) and old style (GEMINI installed) configuration and data locations.
def _connect_db(self): """ Open database connection """ # Get database configuration db_args = {} db_args['host'] = self._cfg.get('nipapd', 'db_host') db_args['database'] = self._cfg.get('nipapd', 'db_name') db_args['user'] = self._cfg.get('nipapd', 'db_user') ...
Open database connection
def set_of(*generators): """ Generates a set consisting solely of the specified generators. This is a class factory, it makes a class which is a closure around the specified generators. """ class SetOfGenerators(ArbitraryInterface): """ A closure class around the generators spec...
Generates a set consisting solely of the specified generators. This is a class factory, it makes a class which is a closure around the specified generators.
def get_wyu_news(self, page): """获取新闻列表 :param page: 页码 :return: json """ if page <= 0: return [] res = WyuNews.__wyu_news(page) soup = BeautifulSoup(res, from_encoding='utf-8') tag_a = soup.find_all(self.__get_tag_a) tag_td = soup.fin...
获取新闻列表 :param page: 页码 :return: json
def make_screenshot(self, screenshot_name=None): """ Shortcut for ``get_screenshot_as_file`` but with configured path. If you are using base :py:class:`~webdriverwrapper.unittest.testcase.WebdriverTestCase`. or pytest, ``screenshot_path`` is passed to driver automatically. If ``...
Shortcut for ``get_screenshot_as_file`` but with configured path. If you are using base :py:class:`~webdriverwrapper.unittest.testcase.WebdriverTestCase`. or pytest, ``screenshot_path`` is passed to driver automatically. If ``screenshot_name`` is not passed, current timestamp is used. ...
def gen_pypirc(username=None, password=None): # type: (str, str) -> None """ Generate ~/.pypirc with the given credentials. Useful for CI builds. Can also get credentials through env variables ``PYPI_USER`` and ``PYPI_PASS``. Args: username (str): pypi username. If not given it...
Generate ~/.pypirc with the given credentials. Useful for CI builds. Can also get credentials through env variables ``PYPI_USER`` and ``PYPI_PASS``. Args: username (str): pypi username. If not given it will try to take it from the `` PYPI_USER`` env variable. passwo...
def parse_csv_file(csv_filepath, expect_negative_correlation = False, STDev_cutoff = 1.0, headers_start_with = 'ID', comments_start_with = None, separator = ','): """ Analyzes a CSV file. Expects a CSV file with a header line starting with headers_start_with e.g. "ID,experimental value, prediction 1 value, ...
Analyzes a CSV file. Expects a CSV file with a header line starting with headers_start_with e.g. "ID,experimental value, prediction 1 value, prediction 2 value," Record IDs are expected in the first column. Experimental values are expected in the second column. Predicted values are expected in the subse...
def map_arguments(self, arguments): """ Returns the mapped function arguments. If no mapping functions are defined, the arguments are returned as they were supplied. :param arguments: List of arguments for bound function as strings. :return: Mapped arguments. """ ...
Returns the mapped function arguments. If no mapping functions are defined, the arguments are returned as they were supplied. :param arguments: List of arguments for bound function as strings. :return: Mapped arguments.
def register(coordinator): """Registers this module as a worker with the given coordinator.""" fetch_queue = Queue.Queue() coordinator.register(FetchItem, fetch_queue) for i in xrange(FLAGS.fetch_threads): coordinator.worker_threads.append( FetchThread(fetch_queue, coordinator.input_...
Registers this module as a worker with the given coordinator.
def add_errback(self, errback, *errback_args, **errback_kwargs): """Add a errback without an associated callback.""" return self.add_callbacks(None, errback=errback, errback_args=errback_args, errback_kwargs=errback_kwargs)
Add a errback without an associated callback.
def getFragment(self): """Return the final fragment""" # assert self.innerHTML fragment = self.fragmentClass() self.openElements[0].reparentChildren(fragment) return fragment
Return the final fragment
def layout_item(layout, item_id, item_class): """Fetch a specific item according to its type in a layout. There's some sip casting conversion issues with QgsLayout::itemById. Don't use it, and use this function instead. See https://github.com/inasafe/inasafe/issues/4271 :param layout: The layout t...
Fetch a specific item according to its type in a layout. There's some sip casting conversion issues with QgsLayout::itemById. Don't use it, and use this function instead. See https://github.com/inasafe/inasafe/issues/4271 :param layout: The layout to look in. :type layout: QgsLayout :param it...
def get_airport_stats(self, iata, page=1, limit=100): """Retrieve the performance statistics at an airport Given the IATA code of an airport, this method returns the performance statistics for the airport. Args: iata (str): The IATA code for an airport, e.g. HYD page (i...
Retrieve the performance statistics at an airport Given the IATA code of an airport, this method returns the performance statistics for the airport. Args: iata (str): The IATA code for an airport, e.g. HYD page (int): Optional page number; for users who are on a plan with fligh...
def standardize_strings(arg, strtype=settings.MODERNRPC_PY2_STR_TYPE, encoding=settings.MODERNRPC_PY2_STR_ENCODING): """ Python 2 only. Lookup given *arg* and convert its str or unicode value according to MODERNRPC_PY2_STR_TYPE and MODERNRPC_PY2_STR_ENCODING settings. """ assert six.PY2, "This funct...
Python 2 only. Lookup given *arg* and convert its str or unicode value according to MODERNRPC_PY2_STR_TYPE and MODERNRPC_PY2_STR_ENCODING settings.
def enable( self, cmd="enable", pattern="password", re_flags=re.IGNORECASE, default_username="manager", ): """Enter enable mode""" if self.check_enable_mode(): return "" output = self.send_command_timing(cmd) if ( "usern...
Enter enable mode
def tas53(msg): """Aircraft true airspeed, BDS 5,3 message Args: msg (String): 28 bytes hexadecimal message Returns: float: true airspeed in knots """ d = hex2bin(data(msg)) if d[33] == '0': return None tas = bin2int(d[34:46]) * 0.5 # kts return round(tas, 1...
Aircraft true airspeed, BDS 5,3 message Args: msg (String): 28 bytes hexadecimal message Returns: float: true airspeed in knots
def add_listener(self, callback, mask=EVENT_ALL): """ Add a listener for scheduler events. When a matching event occurs, ``callback`` is executed with the event object as its sole argument. If the ``mask`` parameter is not provided, the callback will receive events of all types...
Add a listener for scheduler events. When a matching event occurs, ``callback`` is executed with the event object as its sole argument. If the ``mask`` parameter is not provided, the callback will receive events of all types. For further info: https://apscheduler.readthedocs.io/en/lat...
def _next_method(self): """Read the next method from the source, once one complete method has been assembled it is placed in the internal queue.""" queue = self.queue put = self._quick_put read_frame = self.source.read_frame while not queue: try: ...
Read the next method from the source, once one complete method has been assembled it is placed in the internal queue.
def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: ...
Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned.
def _write(self, s, s_length=None, flush=False, ignore_overflow=False, err_msg=None): """Write ``s`` :type s: str|unicode :param s: String to write :param s_length: Custom length of ``s`` :param flush: Set this to flush the terminal stream after writing :...
Write ``s`` :type s: str|unicode :param s: String to write :param s_length: Custom length of ``s`` :param flush: Set this to flush the terminal stream after writing :param ignore_overflow: Set this to ignore if s will exceed the terminal's width :param err_m...
def record_diff(old, new): """ Generate a human-readable diff of two performance records. """ return '\n'.join(difflib.ndiff( ['%s: %s' % (k, v) for op in old for k, v in op.items()], ['%s: %s' % (k, v) for op in new for k, v in op.items()], ))
Generate a human-readable diff of two performance records.
def _decode(cls, value): """Decode the given value, reverting '%'-encoded groups.""" value = cls._DEC_RE.sub(lambda x: '%c' % int(x.group(1), 16), value) return json.loads(value)
Decode the given value, reverting '%'-encoded groups.
def connect(self, host=None, port=None): """Connects to given host address and port.""" host = self.host if host is None else host port = self.port if port is None else port self.socket.connect(host, port)
Connects to given host address and port.
def graph_to_svg(graph): """ Turn a networkx graph into an SVG string, using graphviz dot. Parameters ---------- graph: networkx graph Returns --------- svg: string, pictoral layout in SVG format """ import tempfile import subprocess with tempfile.NamedTemporaryFile() ...
Turn a networkx graph into an SVG string, using graphviz dot. Parameters ---------- graph: networkx graph Returns --------- svg: string, pictoral layout in SVG format
def validate_types(schemas_and_tables): '''normalize a list of desired annotation types if passed None returns all types, otherwise checks that types exist Parameters ---------- types: list[str] or None Returns ------- list[str] list of types Raises ------ UnknownAn...
normalize a list of desired annotation types if passed None returns all types, otherwise checks that types exist Parameters ---------- types: list[str] or None Returns ------- list[str] list of types Raises ------ UnknownAnnotationTypeException If types contains...
def makeplantloop(idf, loopname, sloop, dloop, testing=None): """make plant loop with pip components""" # -------- <testing --------- testn = 0 # -------- testing> --------- newplantloop = idf.newidfobject("PLANTLOOP", Name=loopname) # -------- <testing --------- testn = doingtesting(testing...
make plant loop with pip components
def get_matches(expr_lst, ts): """ Get a list of TimeSeries objects that match the given expression. :param list expr_lst: Expression :param list ts: TimeSeries :return list new_ts: Matched time series objects :return list idxs: Indices of matched objects """ logger_ts.info("enter get_ma...
Get a list of TimeSeries objects that match the given expression. :param list expr_lst: Expression :param list ts: TimeSeries :return list new_ts: Matched time series objects :return list idxs: Indices of matched objects
def GET_account_history(self, path_info, account_addr): """ Get the history of an account at a given page. Returns [{...}] """ if not check_account_address(account_addr): return self._reply_json({'error': 'Invalid address'}, status_code=400) qs_values = path_...
Get the history of an account at a given page. Returns [{...}]
def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise Comm...
Set hardware clock to value of software clock.
def commits(self, drop_collections=True): """ Returns a table of git log data, with "commits" as rows/observations. :param bool drop_collections: Defaults to True. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame """ base_df = s...
Returns a table of git log data, with "commits" as rows/observations. :param bool drop_collections: Defaults to True. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame
def get_vnetwork_portgroups_output_vnetwork_pgs_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups") config = get_vnetwork_portgroups output = ET.SubElement(get_vnetwork_portgroups, ...
Auto Generated Code
def replace(self, rdata, filtered=False): r""" Replace data. :param rdata: Replacement data :type rdata: list of lists :param filtered: Filtering type :type filtered: :ref:`CsvFiltered` .. [[[cog cog.out(exobj.get_sphinx_autodoc(width=63)) ]]] .. Auto...
r""" Replace data. :param rdata: Replacement data :type rdata: list of lists :param filtered: Filtering type :type filtered: :ref:`CsvFiltered` .. [[[cog cog.out(exobj.get_sphinx_autodoc(width=63)) ]]] .. Auto-generated exceptions documentation for .....
def init_virtualenv(self): """Add a virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user instal...
Add a virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, ...
def cdf(arr, pos=None): ''' Return the cumulative density function of a given array or its intensity at a given position (0-1) ''' r = (arr.min(), arr.max()) hist, bin_edges = np.histogram(arr, bins=2 * int(r[1] - r[0]), range=r) hist = np.asfarray(hist) / hist.sum() cdf = np.c...
Return the cumulative density function of a given array or its intensity at a given position (0-1)
def basic(username, password): """Add basic authentication to the requests of the clients.""" none() _config.username = username _config.password = password
Add basic authentication to the requests of the clients.
def _notf(ins): ''' Negates top of the stack (48 bits) ''' output = _float_oper(ins.quad[2]) output.append('call __NOTF') output.append('push af') REQUIRES.add('notf.asm') return output
Negates top of the stack (48 bits)
def short_codes(self): """ Access the short_codes :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList """ if self._short_codes is None: self._short_codes = ShortCodeList(self._version...
Access the short_codes :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList
def iter_values(self): """ Generate each float Y value in this series, in the order they appear on the chart. A value of `None` represents a missing Y value (corresponding to a blank Excel cell). """ yVal = self._element.yVal if yVal is None: return ...
Generate each float Y value in this series, in the order they appear on the chart. A value of `None` represents a missing Y value (corresponding to a blank Excel cell).
def visit_list(self, node, *args, **kwargs): """As transformers may return lists in some places this method can be used to enforce a list as return value. """ rv = self.visit(node, *args, **kwargs) if not isinstance(rv, list): rv = [rv] return rv
As transformers may return lists in some places this method can be used to enforce a list as return value.
def _extract_cookies(self, response: Response): '''Load the cookie headers from the Response.''' self._cookie_jar.extract_cookies( response, response.request, self._get_cookie_referrer_host() )
Load the cookie headers from the Response.
def format_price(self, price): """Formats the price with the set decimal mark and currency """ # ensure we have a float price = api.to_float(price, default=0.0) dm = self.get_decimal_mark() cur = self.get_currency_symbol() price = "%s %.2f" % (cur, price) ...
Formats the price with the set decimal mark and currency
def is_list(self, key): """Return True if variable is a list or a tuple""" data = self.model.get_data() return isinstance(data[key], (tuple, list))
Return True if variable is a list or a tuple
def listThirdPartyLibs(self, configuration = 'Development'): """ Lists the supported Unreal-bundled third-party libraries """ interrogator = self._getUE4BuildInterrogator() return interrogator.list(self.getPlatformIdentifier(), configuration, self._getLibraryOverrides())
Lists the supported Unreal-bundled third-party libraries
def keyPressEvent(self, event): """ Listens for the enter event to check if the query is setup. """ if event.key() in (Qt.Key_Enter, Qt.Key_Return): self.queryEntered.emit(self.query()) super(XOrbQuickFilterWidget, self).keyPressEvent(event)
Listens for the enter event to check if the query is setup.