Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
16,200
def traverse_rootdistorder(self, ascending=True, leaves=True, internal=True): for node in self.root.traverse_rootdistorder(ascending=ascending, leaves=leaves, internal=internal): yield node
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...
16,201
def build(self, recipe, plugin=None): if recipe not in self.recipes.keys(): raise RecipeMissingException("Recipe %s unknown." % recipe) recipe_obj = self.recipes[recipe] if plugin is not None: if recipe_obj.plugin != plugin: raise RecipeWrongPlu...
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.
16,202
def get_log_nodes(self, log_id, ancestor_levels, descendant_levels, include_siblings): return objects.LogNode(self.get_log_node_ids( log_id=log_id, ancestor_levels=ancestor_levels, descendant_levels=descendant_levels, include_siblings=in...
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...
16,203
def getComicData(self, comic): if comic not in self.data: if os.path.exists(self.jsonFn(comic)): with codecs.open(self.jsonFn(comic), , self.encoding) as f: self.data[comic] = json.load(f) else: self.data[comic] = {:{}} ...
Return dictionary with comic info.
16,204
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
16,205
def getContext(self, context_name = ): if context_name == and not in self.contexts: self() return self.contexts[context_name]
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
16,206
def delete_intel_notifications(self, ids, timeout=None): if not isinstance(ids, list): raise TypeError("ids must be a list") data = json.dumps(ids) try: response = requests.post( self.base + + self.api_key, data=data, ...
Programmatically delete notifications via the Intel API. :param ids: A list of IDs to delete from the notification feed. :returns: The post response.
16,207
def _prepare_put_or_patch(self, kwargs): requests_params = self._handle_requests_params(kwargs) update_uri = self._meta_data[] session = self._meta_data[]._meta_data[] read_only = self._meta_data.get(, []) return requests_params, update_uri, session, read_only
Retrieve the appropriate request items for put or patch calls.
16,208
def cleanup(self): if self._root_pipeline_key is None: raise UnexpectedPipelineError( ) if not self.is_root: return task = taskqueue.Task( params=dict(root_pipeline_key=self._root_pipeline_key), url=self.base_path + , headers={: self._root_pipeline_key}) ...
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 ...
16,209
def demultiplex_cells(fastq, out_dir, readnumber, prefix, cb_histogram, cb_cutoff): annotations = detect_fastq_annotations(fastq) re_string = construct_transformed_regex(annotations) parser_re = re.compile(re_string) readstring = "" if not readnumber else "_R{}".format(readnu...
Demultiplex a fastqtransformed FASTQ file into a FASTQ file for each cell.
16,210
def read_crl(crl): * text = _text_or_file(crl) text = get_pem_entry(text, pem_type=) crltempfile = tempfile.NamedTemporaryFile() crltempfile.write(salt.utils.stringutils.to_str(text)) crltempfile.flush() crlparsed = _parse_openssl_crl(crltempfile.name) crltempfile.close() return cr...
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...
16,211
def reader(path_or_f): if hasattr(path_or_f, "read"): return path_or_f else: path = path_or_f path = normalize_path(path) _, extension = extract_extension(path) reader_func = FILE_READERS[extension] return reader_func(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
16,212
async def ttl(self, key, param=None): identity = self._gen_identity(key, param) return await self.client.ttl(identity)
get time to live of a specific identity
16,213
def save_token(self, access_token): key = self._generate_cache_key(access_token.token) self.mc.set(key, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, ...
Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`.
16,214
def stringify(self, value): if ISuperModel.providedBy(value): return str(value) elif isinstance(value, (DateTime)): return value.ISO8601() elif safe_hasattr(value, "filename"): return value.filename elif isi...
Convert value to string This method is used to generate a simple JSON representation of the object (without dereferencing objects etc.)
16,215
def show(cmap, var, vmin=None, vmax=None): lat, lon, z, data = read(var) fig = plt.figure(figsize=(16, 12)) ax = fig.add_subplot(3, 1, 1) map1 = ax.scatter(lon, -z, c=data, cmap=, s=10, linewidths=0., vmin=vmin, vmax=vmax) plt.colorbar(map1, ax=ax) ax = fig.add_subplot(3,...
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.
16,216
def distance(self, i, j): a, b = i, j if a.name() > b.name(): a, b = b, a return self._matrix[self._nodes[a.name()]][self._nodes[b.name()]]
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.
16,217
def read(self, *, level=0, alignment=1) -> bytes: return self.mglo.read(level, alignment)
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
16,218
def wait_for_notification(self, notification_class=BaseNotification): if notification_class: if notification_class is BaseNotification: message = "No notification was shown." else: message = "{0} was not shown.".format(notification_class.__name__)...
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...
16,219
def namedb_accounts_vest(cur, block_height): sql = args = (block_height,) vesting_rows = namedb_query_execute(cur, sql, args) rows = [] for row in vesting_rows: tmp = {} tmp.update(row) rows.append(tmp) for row in rows: addr = row[] token_type = ro...
Vest tokens at this block to all recipients. Goes through the vesting table and debits each account that should vest on this block.
16,220
def _CheckWindowsRegistryKeyPath( self, filename, artifact_definition, key_path): result = True key_path_segments = key_path.lower().split() if key_path_segments[0] == : result = False logging.warning(( ).format( artifact_defin...
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...
16,221
def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): **["foo", "bar"]*[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]<package>old<old-version>new<new-version> refreshdb = salt.utils.data.is_true(refresh) pkg_to_install = [] old ...
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 ...
16,222
def check_bed_coords(in_file, data): if dd.get_ref_file(data): contig_sizes = {} for contig in ref.file_contigs(dd.get_ref_file(data)): contig_sizes[contig.name] = contig.size with utils.open_gzipsafe(in_file) as in_handle: for line in in_handle: ...
Ensure BED file coordinates match reference genome. Catches errors like using a hg38 BED file for an hg19 genome run.
16,223
def run_init(args): root = args.root if root is None: root = root = os.path.abspath(root) project_data = _get_package_data() project_name = project_data[] directories = [os.path.join(root, ), os.path.join(root, ), os.path.join(root, ), ...
Run project initialization. This will ask the user for input. Parameters ---------- args : argparse named arguments
16,224
def _process(self, envelope, session, mode, **kwargs): if mode == WMessengerOnionPackerLayerProto.Mode.pack: return self.pack(envelope, session, **kwargs) else: return self.unpack(envelope, session, **kwargs)
:meth:`.WMessengerOnionLayerProto.process` implementation
16,225
def grant_permission_to_users(self, permission, **kwargs): kwargs[] = True if kwargs.get(): return self.grant_permission_to_users_with_http_info(permission, **kwargs) else: (data) = self.grant_permission_to_users_with_http_info(permission, **kwargs) ...
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...
16,226
def read_file(self, file: Union[IO, asyncio.StreamWriter]=None): if file: file_is_async = hasattr(file, ) while True: data = yield from self._connection.read(4096) if not data: break if file: file.write(data) ...
Read from connection to file. Args: file: A file object or a writer stream.
16,227
def upgrade(yes, dry_run, patches): 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" % green(patcher.db))): patcher.discove...
Upgrade the datamodel by applying recusively the patches available
16,228
def contains_point(self, pt): 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?
16,229
def urlForViewState(self, person, viewState): organizerURL = self._webTranslator.linkTo(self.storeID) return url.URL( netloc=, scheme=, pathsegs=organizerURL.split()[1:], querysegs=((, person.name), (, viewSta...
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}
16,230
def iter_statuses(self, number=-1, etag=None): i = self._iter(int(number), self.statuses_url, DeploymentStatus, etag=etag) i.headers = Deployment.CUSTOM_HEADERS return i
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...
16,231
def reindex(args): p = OptionParser(reindex.__doc__) p.add_option("--nogaps", default=False, action="store_true", help="Remove all gap lines [default: %default]") p.add_option("--inplace", default=False, action="store_true", help="Replace input file [default: %default]...
%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.
16,232
def build_from_job_list(scheme_files, templates, base_output_dir): queue = Queue() for scheme in scheme_files: queue.put(scheme) if len(scheme_files) < 40: thread_num = len(scheme_files) else: thread_num = 40 threads = [] for _ in range(thread_num): thread ...
Use $scheme_files as a job lists and build base16 templates using $templates (a list of TemplateGroup objects).
16,233
def bin_pkg_info(path, saltenv=): ** if __salt__[](path): newpath = __salt__[](path, saltenv) if not newpath: raise CommandExecutionError( {1}\ .format(path, saltenv) ) path = newpath else: if not os.path.exists(pat...
.. 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...
16,234
def activate_view(self, request, user_id, token): try: user = self.user_model.objects.get(id=user_id, is_active=False) except self.user_model.DoesNotExist: raise Http404(_("Your URL may have expired.")) if not RegistrationTokenGenerator().check_token(user, token...
View function that activates the given User by setting `is_active` to true if the provided information is verified.
16,235
def update(self, enabled): data = values.of({: enabled, }) payload = self._version.update( , self._uri, data=data, ) return InstalledAddOnExtensionInstance( self._version, payload, installed_add_on_sid=sel...
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
16,236
def call_rpc(self, address, rpc_id, payload=b""): if rpc_id < 0 or rpc_id > 0xFFFF: raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id)) if address not in self._rpc_overlays and address not in self._tiles: raise TileNotFoundError("Unknown tile address, no regis...
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
16,237
def save(self, saveModelDir): logger = self._getLogger() logger.debug("(%s) Creating local checkpoint in %r...", self, saveModelDir) modelPickleFilePath = self._getModelPickleFilePath(saveModelDir) if os.path.exists(saveModelDir): if not os.path.isdir(saveModelDi...
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...
16,238
def driver_name(self): (self._driver_name, value) = self.get_cached_attr_string(self._driver_name, ) return value
Returns the name of the driver that provides this tacho motor device.
16,239
def is_driver(self): if not hasattr(self, ): self.parse_data_directories(directories=[ DIRECTORY_ENTRY[]]) return True retur...
Check whether the file is a Windows driver. This will return true only if there are reliable indicators of the image being a driver.
16,240
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...
16,241
def _kalman_prediction_step(k, p_m , p_P, p_dyn_model_callable, calc_grad_log_likelihood=False, p_dm = None, p_dP = None): A = p_dyn_model_callable.Ak(k,p_m,p_P) Q = p_dyn_model_callable.Qk(k) m_pred = p_dyn_model_callable.f_a(k, p_m...
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...
16,242
def ipaddress(): try: import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("gmail.com", 80)) result = s.getsockname()[0] s.close() return result except Exception: return ""
Determine our own IP adress. This seems to be far more complicated than you would think:
16,243
def convert_geojson_to_shapefile(geojson_path): layer = QgsVectorLayer(geojson_path, , ) if not layer.isValid(): return False shapefile_path = os.path.splitext(geojson_path)[0] + QgsVectorFileWriter.writeAsVectorFormat( layer, shapefile_path, , layer.cr...
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...
16,244
def threadsafe_generator(generator_func): def decoration(*args, **keyword_args): return ThreadSafeIter(generator_func(*args, **keyword_args)) return decoration
A decorator that takes a generator function and makes it thread-safe.
16,245
def is_set(name): val = os.environ.get(name, ) assert val == or val == , f"env var {name} has value {val}, expected 0 or 1" return val ==
Helper method to check if given property is set
16,246
def _set_ldp(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ldp.ldp, is_container=, presence=False, yang_name="ldp", rest_name="ldp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u: u, ...
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 ...
16,247
def register(): 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
16,248
def write(self): if self.text is None: return None if self._last_text == self.text: char_delay = 0 else: char_delay = self.char_delay self._last_text = self.text with self.lock: ctl = Control()...
Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning.
16,249
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): assert wait_for_completion is True cpc_oid = uri_parms[0] try: cpc = hmc.cpcs.lookup_by_oid(cpc_oid) except KeyError: raise InvalidResourceError(method, uri) ...
Operation: Set CPC Power Save (any CPC mode).
16,250
def connect(self, (host, port)): super(GeventTransport, self).connect((host, port), klass=socket.socket)
Connect using a host,port tuple
16,251
def _validate_config(self): if len(cfg.CONF.ml2_arista.get()) < 1: msg = _( ) LOG.exception(msg) raise arista_exc.AristaConfigError(msg=msg)
Ensure at least one switch is configured
16,252
def __get_enabled_heuristics(self, url): if url in self.__sites_heuristics: return self.__sites_heuristics[url] site = self.__sites_object[url] heuristics = dict(self.cfg_heuristics["enabled_heuristics"]) if "overwrite_heuristics" in site: for heuristic,...
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.
16,253
def process_event(self, module_name, event, default_event=False): module_info = self.output_modules.get(module_name) if module_info["type"] == "py3status": module = module_info["module"] module.click_event(event) if self.config["debug"]: ...
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.
16,254
def edit_pool(self, id): p = Pool.get(int(id)) if in request.json: p.name = validate_string(request.json, ) if in request.json: p.description = validate_string(request.json, ) if in request.json: p.default_type = validate_string(r...
Edit a pool.
16,255
def validated_element(x, tags=None, attrs=None): ele = to_ele(x) if tags: if isinstance(tags, (str, bytes)): tags = [tags] if ele.tag not in tags: raise XMLError("Element [%s] does not meet requirement" % ele.tag) if attrs: for req in attrs: i...
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 ...
16,256
def _back_compatible_gemini(conf_files, data): if vcfanno.is_human(data, builds=["37"]): for f in conf_files: if f and os.path.basename(f) == "gemini.conf" and os.path.exists(f): with open(f) as in_handle: for line in in_handle: if...
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.
16,257
def _connect_db(self): db_args = {} db_args[] = self._cfg.get(, ) db_args[] = self._cfg.get(, ) db_args[] = self._cfg.get(, ) db_args[] = self._cfg.get(, ) db_args[] = self._cfg.get(, ) db_args[] = self._cfg.get(, ) if ...
Open database connection
16,258
def set_of(*generators): class SetOfGenerators(ArbitraryInterface): @classmethod def arbitrary(cls): arbitrary_set = set() for generator in generators: arbitrary_set |= { arbitrary(generator) ...
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.
16,259
def get_wyu_news(self, page): if page <= 0: return [] res = WyuNews.__wyu_news(page) soup = BeautifulSoup(res, from_encoding=) tag_a = soup.find_all(self.__get_tag_a) tag_td = soup.find_all(self.__get_tag_td) result = [] for index, item in en...
获取新闻列表 :param page: 页码 :return: json
16,260
def make_screenshot(self, screenshot_name=None): if not self.screenshot_path: raise Exception() if not screenshot_name: screenshot_name = str(time.time()) self.get_screenshot_as_file(.format(self.screenshot_path, screenshot_name))
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. ...
16,261
def gen_pypirc(username=None, password=None): path = join(conf.getenv(), ) username = username or conf.getenv(, None) password = password or conf.getenv(, None) if username is None or password is None: log.err("You must provide $PYPI_USER and $PYPI_PASS") sys.exit(1) log....
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...
16,262
def parse_csv_file(csv_filepath, expect_negative_correlation = False, STDev_cutoff = 1.0, headers_start_with = , comments_start_with = None, separator = ): assert (os.path.exists(csv_filepath)) return parse_csv(get_file_lines(csv_filepath), expect_negative_correlation = expect_negative...
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...
16,263
def map_arguments(self, arguments): if self.argument_mappings is None: return arguments return [f(a) for f, a in zip(self.argument_mappings, 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.
16,264
def register(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_queue))
Registers this module as a worker with the given coordinator.
16,265
def add_errback(self, errback, *errback_args, **errback_kwargs): return self.add_callbacks(None, errback=errback, errback_args=errback_args, errback_kwargs=errback_kwargs)
Add a errback without an associated callback.
16,266
def getFragment(self): fragment = self.fragmentClass() self.openElements[0].reparentChildren(fragment) return fragment
Return the final fragment
16,267
def layout_item(layout, item_id, item_class): item = layout.itemById(item_id) if item is None: return item if issubclass(item_class, QgsLayoutMultiFrame): frame = sip.cast(item, QgsLayoutFrame) multi_frame = frame.multiFrame() return sip.cast(multi_fra...
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...
16,268
def get_airport_stats(self, iata, page=1, limit=100): url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit) return self._fr24.get_airport_stats(url)
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...
16,269
def standardize_strings(arg, strtype=settings.MODERNRPC_PY2_STR_TYPE, encoding=settings.MODERNRPC_PY2_STR_ENCODING): assert six.PY2, "This function should be used with Python 2 only" if not strtype: return arg if strtype == six.binary_type or strtype == : return _generic_conv...
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.
16,270
def enable( self, cmd="enable", pattern="password", re_flags=re.IGNORECASE, default_username="manager", ): if self.check_enable_mode(): return "" output = self.send_command_timing(cmd) if ( "username" in output.lower() ...
Enter enable mode
16,271
def tas53(msg): d = hex2bin(data(msg)) if d[33] == : return None tas = bin2int(d[34:46]) * 0.5 return round(tas, 1)
Aircraft true airspeed, BDS 5,3 message Args: msg (String): 28 bytes hexadecimal message Returns: float: true airspeed in knots
16,272
def add_listener(self, callback, mask=EVENT_ALL): self._scheduler.add_listener(callback, mask)
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...
16,273
def _next_method(self): queue = self.queue put = self._quick_put read_frame = self.source.read_frame while not queue: try: frame_type, channel, payload = read_frame() except Exception as exc: ...
Read the next method from the source, once one complete method has been assembled it is placed in the internal queue.
16,274
def get_cleaned_data_for_step(self, step): if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.clean...
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.
16,275
def _write(self, s, s_length=None, flush=False, ignore_overflow=False, err_msg=None): if not ignore_overflow: s_length = len(s) if s_length is None else s_length if err_msg is None: err_msg = ( "Terminal has {} columns; attempte...
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...
16,276
def record_diff(old, new): return .join(difflib.ndiff( [ % (k, v) for op in old for k, v in op.items()], [ % (k, v) for op in new for k, v in op.items()], ))
Generate a human-readable diff of two performance records.
16,277
def _decode(cls, value): value = cls._DEC_RE.sub(lambda x: % int(x.group(1), 16), value) return json.loads(value)
Decode the given value, reverting '%'-encoded groups.
16,278
def connect(self, host=None, port=None): 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.
16,279
def graph_to_svg(graph): import tempfile import subprocess with tempfile.NamedTemporaryFile() as dot_file: nx.drawing.nx_agraph.write_dot(graph, dot_file.name) svg = subprocess.check_output([, dot_file.name, ]) return svg
Turn a networkx graph into an SVG string, using graphviz dot. Parameters ---------- graph: networkx graph Returns --------- svg: string, pictoral layout in SVG format
16,280
def validate_types(schemas_and_tables): all_types = get_types() if not (all(sn in all_types for sn, tn in schemas_and_tables)): bad_types = [sn for sn, tn in schemas_and_tables if sn not in all_types] msg = .format(bad_types) raise UnknownAnnotationTypeExceptio...
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...
16,281
def makeplantloop(idf, loopname, sloop, dloop, testing=None): testn = 0 newplantloop = idf.newidfobject("PLANTLOOP", Name=loopname) testn = doingtesting(testing, testn, newplantloop) if testn == None: returnnone() fields = SomeFields.p_fields flnames = [fie...
make plant loop with pip components
16,282
def get_matches(expr_lst, ts): logger_ts.info("enter get_matches") new_ts = [] idxs = [] match = False try: for idx, ts_data in enumerate(ts): for expr in expr_lst: try: val = ts_data[expr[0]] if ex...
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
16,283
def GET_account_history(self, path_info, account_addr): if not check_account_address(account_addr): return self._reply_json({: }, status_code=400) qs_values = path_info[] page = qs_values.get(, None) if page is None: page = "0" try: ...
Get the history of an account at a given page. Returns [{...}]
16,284
def _swclock_to_hwclock(): res = __salt__[]([, ], python_shell=False) if res[] != 0: msg = .format(res[]) raise CommandExecutionError(msg) return True
Set hardware clock to value of software clock.
16,285
def commits(self, drop_collections=True): base_df = self._data if drop_collections is True: out_df = self._drop_collections(base_df) else: out_df = base_df return out_df
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
16,286
def get_vnetwork_portgroups_output_vnetwork_pgs_name(self, **kwargs): config = ET.Element("config") get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups") config = get_vnetwork_portgroups output = ET.SubElement(get_vnetwork_portgroups, "output") vnetwork_pgs = E...
Auto Generated Code
16,287
def replace(self, rdata, filtered=False): r rdata_ex = pexdoc.exh.addai("rdata") rows_ex = pexdoc.exh.addex( ValueError, "Number of rows mismatch between input and replacement data" ) cols_ex = pexdoc.exh.addex( ValueError, "Number of columns mism...
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 .....
16,288
def init_virtualenv(self): if not in os.environ: return if sys.executable.startswith(os.environ[]): import site sys.path.insert(0, virtual_env) site.addsitedir(virtual_env)
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, ...
16,289
def cdf(arr, pos=None): 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.cumsum(hist) if pos is None: return cdf i = np.argmax(cdf > pos) return bin_edges[i]
Return the cumulative density function of a given array or its intensity at a given position (0-1)
16,290
def basic(username, password): none() _config.username = username _config.password = password
Add basic authentication to the requests of the clients.
16,291
def _notf(ins): output = _float_oper(ins.quad[2]) output.append() output.append() REQUIRES.add() return output
Negates top of the stack (48 bits)
16,292
def short_codes(self): if self._short_codes is None: self._short_codes = ShortCodeList(self._version, account_sid=self._solution[], ) return self._short_codes
Access the short_codes :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList
16,293
def iter_values(self): yVal = self._element.yVal if yVal is None: return for idx in range(yVal.ptCount_val): yield yVal.pt_v(idx)
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).
16,294
def visit_list(self, node, *args, **kwargs): 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.
16,295
def _extract_cookies(self, response: Response): self._cookie_jar.extract_cookies( response, response.request, self._get_cookie_referrer_host() )
Load the cookie headers from the Response.
16,296
def format_price(self, price): price = api.to_float(price, default=0.0) dm = self.get_decimal_mark() cur = self.get_currency_symbol() price = "%s %.2f" % (cur, price) return price.replace(".", dm)
Formats the price with the set decimal mark and currency
16,297
def is_list(self, key): data = self.model.get_data() return isinstance(data[key], (tuple, list))
Return True if variable is a list or a tuple
16,298
def listThirdPartyLibs(self, configuration = ): interrogator = self._getUE4BuildInterrogator() return interrogator.list(self.getPlatformIdentifier(), configuration, self._getLibraryOverrides())
Lists the supported Unreal-bundled third-party libraries
16,299
def keyPressEvent(self, event): 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.