Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
343,700
def iterate(self, func, args=None, filter=[]): def blag(node, args)node return self._root.iterate(func, args, filter)
Call a function on the root node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value of @ref...
343,701
def whois(ip_address): whois_ip = str(ip_address) try: query = socket.gethostbyname(whois_ip) except Exception: query = whois_ip s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.ripe.net", 43)) s.send(query.encode("utf8") + b"\r\n") answer = b"" ...
Whois client for Python
343,702
def height(poly): num = len(poly) hgt = 0.0 for i in range(num): hgt += (poly[i][2]) return hgt/num
height
343,703
def main(args): try: import __main__ parser = argparse.ArgumentParser( usage= + str(__version__), formatter_class=argparse.RawTextHelpFormatter) parser.add_argument(, action=, version= + str(__version__)) build_subc...
Main Entry Point
343,704
def waitToFinish(self, timeout=None, pollInterval=.1): if timeout is None: while self.isFinished is False: time.sleep(pollInterval) else: sleptFor = 0 while self.isFinished is False and sleptFor < timeout: time.sleep(pollInterv...
waitToFinish - Wait (Block current thread), optionally with a timeout, until background task completes. @param timeout <None/float> - None to wait forever, otherwise max number of seconds to wait @param pollInterval <float> - Seconds between each poll. Keep high if interactivity is not importan...
343,705
def insert(self, index, value): self.check(value) self._user_list.insert(index, value)
Insert an instance of User into the collection.
343,706
def receivables_account(self) -> Account: row = AccountEntry.objects.filter(source_invoice=self).order_by().first() return row.account if row else None
Returns receivables account. Receivables account is assumed to be the one were invoice rows were recorded. :return: Account or None
343,707
def _construct_error_handling(self): self._app.register_error_handler(404, ServiceErrorResponses.route_not_found) self._app.register_error_handler(405, ServiceErrorResponses.route_not_found) self._app.register_error_handler(500, ServiceErrorResponses.lambda_fa...
Updates the Flask app with Error Handlers for different Error Codes
343,708
async def play(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_NONE, ponder: bool = False, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> PlayResult:
Play a position. :param board: The position. The entire move stack will be sent to the engine. :param limit: An instance of :class:`chess.engine.Limit` that determines when to stop thinking. :param game: Optional. An arbitrary object that identifies the game. ...
343,709
def files(self, paths, access=None, extensions=None, minsize=None, recursion=False): self.__init__() self.access = access self.filetype = self.extensions = extensions self.minsize = minsize self.paths = paths self.recursion = recursion ...
Iterates over `paths` (which may consist of files and/or directories). Removes duplicates and returns list of valid files meeting access, extension, and minimum size criteria.
343,710
def taskCompleted(self, *args, **kwargs): ref = { : , : , : [ { : , : False, : , }, { : False, : , }, ...
Task Completed Messages When a task is successfully completed by a worker a message is posted this exchange. This message is routed using the `runId`, `workerGroup` and `workerId` that completed the task. But information about additional runs is also available from the task stat...
343,711
def setFullscreen(self, fullscreen): if not fullscreen: self.ckBox_fullscreen.setChecked(False) self.parent().showNormal() else: self.ckBox_fullscreen.setChecked(True) self.parent().showFullScreen()
toggle between fullscreen and normal window
343,712
def watermark(im, mark, position, opacity=1): if opacity < 1: mark = reduce_opacity(mark, opacity) if im.mode != : im = im.convert() layer = Image.new(, im.size, (0, 0, 0, 0)) if position == : for y in range(0, im.size[1], mark.size[1]): for x in range(...
Adds a watermark to an image.
343,713
def compute_volume(sizes, centers, normals): normal_mags = np.linalg.norm(normals, axis=1) return np.sum(sizes*((centers*normals).sum(axis=1)/normal_mags)/3)
Compute the numerical volume of a convex mesh :parameter array sizes: array of sizes of triangles :parameter array centers: array of centers of triangles (x,y,z) :parameter array normals: array of normals of triangles (will normalize if not already) :return: the volume (float)
343,714
def _medianindex(self,v): assert self.prevlayer()!=None N = self._neighbors(v) g=self.layout.grx pos = [g[x].pos for x in N] lp = len(pos) if lp==0: return [] pos.sort() pos = pos[::self.layout.dirh] i,j = divmod(lp-1,2) return [po...
find new position of vertex v according to adjacency in layer l+dir. position is given by the median value of adjacent positions. median heuristic is proven to achieve at most 3 times the minimum of crossings (while barycenter achieve in theory the order of |V|)
343,715
def _get_metadata(self, data_type, key, timeout=5): endpoint_url = self.METADATA_ENDPOINT.format( data_type=data_type, key=key) try: rsp = requests.get( endpoint_url, headers={: }, timeout=timeout) rsp.raise_for...
Get host instance metadata (only works on GCP hosts). More details about instance metadata: https://cloud.google.com/compute/docs/storing-retrieving-metadata Args: data_type (str): Type of metadata to fetch. Eg. project, instance key (str): Key of metada...
343,716
def loud(self, lang=): lang_method = getattr(self, lang, None) if lang_method: return lang_method().upper() else: return self.english().upper()
Speak loudly! FIVE! Use upper case!
343,717
def find_file(name, path=os.getcwd(), deep=False, partial=False): paths = path.split(os.pathsep) if type(path) is str else path for p in paths: ret = __find_file(name, p, deep, partial) if ret: return ret
Searches for a file and returns its path upon finding it. Searches for a file with the given `name` in the list of directories mentioned in `path`. It also supports `deep` search (recursive) and `partial` search (searching for files having filename matching partially with the query) through the respect...
343,718
def _add_return_site(self, return_site): self._register_nodes(True, return_site) self._ret_sites.add(return_site) self._add_endpoint(return_site, )
Registers a basic block as a site for control flow to return from this function. :param CodeNode return_site: The block node that ends with a return.
343,719
def close(self): print("PGPooledTransaction - shutting down connection pool") for name, conn in self.pool.iteritems(): conn.close() print("PGPooledTransaction - connection %s closed" % name)
close all pooled connections
343,720
def covariance_ellipse(P, deviations=1): U, s, _ = linalg.svd(P) orientation = math.atan2(U[1, 0], U[0, 0]) width = deviations * math.sqrt(s[0]) height = deviations * math.sqrt(s[1]) if height > width: raise ValueError() return (orientation, width, height)
Returns a tuple defining the ellipse representing the 2 dimensional covariance matrix P. Parameters ---------- P : nd.array shape (2,2) covariance matrix deviations : int (optional, default = 1) # of standard deviations. Default is 1. Returns (angle_radians, width_radius, heigh...
343,721
def add_traffic_handler(self, netlink, netlink_gw=None, network=None): routing_node_gateway = RoutingNodeGateway(netlink, destinations=[] if not netlink_gw else netlink_gw) return self._add_gateway_node(, routing_node_gateway, network)
Add a traffic handler to a routing node. A traffic handler can be either a static netlink or a multilink traffic handler. If ``network`` is not specified and the interface has multiple IP addresses, the traffic handler will be added to all ipv4 addresses. Add a pre-defined netl...
343,722
def _i2c_write_bytes(self, data): for byte in data: self._command.append(str(bytearray((0x11, 0x00, 0x00, byte)))) self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False) self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DE...
Write the specified number of bytes to the chip.
343,723
def brentq(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, disp=True): if xtol <= 0: raise ValueError("xtol is too small (<= 0)") if maxiter < 1: raise ValueError("maxiter must be greater than 0") xpre = a * 1.0 xcur = b * 1.0 fpre = f(xpre, *args) ...
Find a root of a function in a bracketing interval using Brent's method adapted from Scipy's brentq. Uses the classic Brent's method to find a zero of the function `f` on the sign changing interval [a , b]. `f` must be jitted via numba. Parameters ---------- f : jitted and callable ...
343,724
def _preprocess_sqlite_index(asql_query, library, backend, connection): new_query = None if asql_query.strip().lower().startswith(): logger.debug( .format(asql_query)) index = parse_index(asql_query) partition = library.partition(index.source) ta...
Creates materialized view for each indexed partition found in the query. Args: asql_query (str): asql query library (ambry.Library): backend (SQLiteBackend): connection (apsw.Connection): Returns: str: converted asql if it contains index query. If not, returns asql_quer...
343,725
def dpt(adata, n_dcs=10, n_branchings=0, min_group_size=0.01, allow_kendall_tau_shift=True, copy=False): adata = adata.copy() if copy else adata if not in adata.uns: raise ValueError( ) if not in adata.uns and not in adata.var: logg.warn( ...
Infer progression of cells through geodesic distance along the graph [Haghverdi16]_ [Wolf19]_. Reconstruct the progression of a biological process from snapshot data. `Diffusion Pseudotime` has been introduced by [Haghverdi16]_ and implemented within Scanpy [Wolf18]_. Here, we use a further developed v...
343,726
def __params_order_descriptor(self, message_type, path, is_params_class=False): path_params = [] query_params = [] path_parameter_dict = self.__get_path_parameters(path) for field in sorted(message_type.all_fields(), key=lambda f: f.number): matched_path_parameters = path_parameter_dict.get(...
Describe the order of path parameters. Args: message_type: messages.Message class, Message with parameters to describe. path: string, HTTP path to method. is_params_class: boolean, Whether the message represents URL parameters. Returns: Descriptor list for the parameter order.
343,727
def update(self, dt): if self.win_status != : return if self.force_fps > 0: dt = 1 / self.force_fps self.player.update_rotation(dt, self.buttons) newVel = self.player.do_move(dt, self.buttons) oldRe...
Updates game engine each tick
343,728
def to_dict(self): return { "state_size": self.state_size, "chain": self.chain.to_json(), "parsed_sentences": self.parsed_sentences if self.retain_original else None }
Returns the underlying data as a Python dict.
343,729
def setup(cls, cron_cfg="cron"): random.seed() logging_cfg = cls.LOGGING_CFG if "%s" in logging_cfg: logging_cfg = logging_cfg % (cron_cfg if "--cron" in sys.argv[1:] else "scripts",) logging_cfg = os.path.expanduser(logging_cfg) if os.path.exists(logging_cf...
Set up the runtime environment.
343,730
def get_integers(bitwidth, unsigned, limit=0): if unsigned: start, stop = 0, ((1 << bitwidth) - 1) else: start, stop = (-(1 << bitwidth-1)), (1 << (bitwidth-1)-1) for num in _fuzzdb_integers(limit): if num >= start and num <= stop: yield num
Get integers from fuzzdb database bitwidth - The bitwidth that has to contain the integer unsigned - Whether the type is unsigned limit - Limit to |limit| results
343,731
def summarize(self, sentences=0, chars=0): query_params = {"prop": "extracts", "explaintext": "", "titles": self.title} if sentences: query_params["exsentences"] = 10 if sentences > 10 else sentences elif chars: query_params["exchars"] = 1 if chars < 1 else chars...
Summarize page either by number of sentences, chars, or first section (**default**) Args: sentences (int): Number of sentences to use in summary \ (first `x` sentences) chars (int): Number of characters to use in summary \ ...
343,732
def learn(self, inputPattern, inputCategory, partitionId=None, isSparse=0, rowID=None): if self.verbosity >= 1: print "%s learn:" % g_debugPrefix print " category:", int(inputCategory) print " active inputs:", _labeledInput(inputPattern, ...
Train the classifier to associate specified input pattern with a particular category. :param inputPattern: (list) The pattern to be assigned a category. If isSparse is 0, this should be a dense array (both ON and OFF bits present). Otherwise, if isSparse > 0, this should be a list of the ...
343,733
def unset_quota_volume(name, path): * cmd = .format(name) if path: cmd += .format(path) if not _gluster(cmd): return False return True
Unset quota on glusterfs volume name Name of the gluster volume path Folder path for restriction in volume CLI Example: .. code-block:: bash salt '*' glusterfs.unset_quota_volume <volume> <path>
343,734
def file_to_list(in_file): lines = [] for line in in_file: line = line.strip() if line != : if line[0] != : lines.append(line) return lines
Reads file into list
343,735
def picard_fastq_to_bam(picard, fastq_one, fastq_two, out_dir, names, order="queryname"): out_bam = os.path.join(out_dir, "%s-fastq.bam" % os.path.splitext(os.path.basename(fastq_one))[0]) if not file_exists(out_bam): with tx_tmpdir(picard._config) as tmp_dir: ...
Convert fastq file(s) to BAM, adding sample, run group and platform information.
343,736
def get_block(self, config_only=False): mib = TBBlock() for cid, config in self.configs.items(): mib.add_config(cid, config) if not config_only: for key, val in self.commands.items(): mib.add_command(key, val) if not self.valid: ...
Create a TileBus Block based on the information in this descriptor
343,737
def run_cmsearch(fastas, threads, cm): out = [] for fasta in fastas: cmsearch = % (fasta.name.rsplit(, 1)[0]) if os.path.exists(cmsearch) is False: p = Popen( \ % (threads, cmsearch, cm, fasta.name), shell = True) p.communicate() else: ...
run cmsearch: comapre 23S sequences to ssu-align's CM
343,738
def encrypt(**kwargs): with StreamEncryptor(**kwargs) as encryptor: ciphertext = encryptor.read() return ciphertext, encryptor.header
Encrypts and serializes provided plaintext. .. note:: When using this function, the entire ciphertext message is encrypted into memory before returning any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`. .. code:: python >>> import aws_encryption_sdk >>...
343,739
def validation_epoch(self, epoch_info, source: ): self.eval() iterator = tqdm.tqdm(source.val_loader(), desc="Validation", unit="iter", file=sys.stdout) with torch.no_grad(): for batch_idx, (data, target) in enumerate(iterator): batch_info = BatchInfo(epoch...
Run a single evaluation epoch
343,740
def _HasExpired(self, key): self.logger.debug(, key) try: schema, json_str = key.split(None, 3)[2:] except (ValueError, AttributeError): self.logger.debug() return False if schema != : self.logger.debug(, schema) return False try: json_obj = json.loads(jso...
Check whether an SSH key has expired. Uses Google-specific semantics of the OpenSSH public key format's comment field to determine if an SSH key is past its expiration timestamp, and therefore no longer to be trusted. This format is still subject to change. Reliance on it in any way is at your own risk...
343,741
def _validate_bn_layer(self, layer): if (not isinstance(layer, tf.keras.layers.BatchNormalization) and not isinstance(layer, tf.compat.v1.layers.BatchNormalization)): raise ValueError( "batchnorm_layer must be an instance of BatchNormalization layer.") if layer.renorm: raise V...
Check for valid BatchNormalization layer. Args: layer: Instance of `tf.layers.BatchNormalization`. Raises: ValueError: If batchnorm_layer argument is not an instance of `tf.layers.BatchNormalization`, or if `batchnorm_layer.renorm=True` or if `batchnorm_layer.virtual_batch_size` is spec...
343,742
def _ReadUUIDDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): return self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.UUIDDefinition, definition_name, self._SUPPORTED_ATTRIBUTES_FI...
Reads an UUID data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data type ...
343,743
def _find_recorder(recorder, tokens, index): if recorder is None: for recorder_factory in _RECORDERS: recorder = recorder_factory.maybe_start_recording(tokens, index) if recorder is not None: ...
Given a current recorder and a token index, try to find a recorder.
343,744
def _get_events_data(object_key: str) -> List[dict]: events_data = [] key = _keys.events_data(object_key) for event_id in _get_events_list(object_key): event_dict = literal_eval(DB.get_hash_value(key, event_id)) events_data.append(event_dict) return events_data
Get the list of event data for the object with the specified key. Args: object_key (str): Key of an object in the database.
343,745
def bios_mappings(self): return BIOSMappings( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "Mappings"]), redfish_version=self.redfish_version)
Property to provide reference to bios mappings instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
343,746
def linspace_pix(self, start=None, stop=None, pixel_step=1, y_vs_x=False): return CCDLine.linspace_pix(self, start=start, stop=stop, pixel_step=pixel_step, y_vs_x=y_vs_x)
Return x,y values evaluated with a given pixel step.
343,747
def take_quality_screenshot(self, screenshot_name): self.info_log("Taking a quality screenshot...") if self.test_instance._runner_dir: _screenshot_name = % string_to_filename(screenshot_name) relative_path = os.path.join( self.test_instance._quality...
Take a quality screenshot Use the screenshot_name args when you want to take a screenshot for reference Args: screenshot_name (str) the name of the screenshot
343,748
def _get_stddevs(self, C, stddev_types, stddev_shape): stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(C["sigtot"] + np.zeros(stddev_shape))...
Returns the standard deviations given in Table 2
343,749
def load(self, base_settings): is_valid_key = lambda k: k.isupper() and not k.startswith() valid_keys = (k for k in base_settings if is_valid_key(k)) base_settings = DottedAccessDict((k, base_settings[k]) for k in valid_keys) settings_from_file = sel...
Merge local settings from file with ``base_settings``. Returns a new settings dict containing the base settings and the loaded settings. Includes: - base settings - settings from extended file(s), if any - settings from file
343,750
def render(self, **kwargs): super(VisVoxel, self).render(**kwargs) legend_proxy = [] legend_names = [] fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi) ax = Axes3D(fig) for plot in self._plots: ...
Displays the voxels and the control points.
343,751
def close(self): if not self._closed: self._closed = True self._stop_multi_pools() if self._http_pool is not None: self._http_pool.clear() self._http_pool = None if self._tcp_pool is not None: self._tcp_pool...
Iterate through all of the connections and close each one.
343,752
def plot_signal_power_colorplot(ax, params, fname, transient=200, Df=None, mlab=True, NFFT=1000, window=plt.mlab.window_hanning, noverlap=0, cmap = plt.cm.get_cmap(, 21), ...
on axes plot the LFP power spectral density The whole signal duration is used. args: :: ax : matplotlib.axes.AxesSubplot object fancy : bool,
343,753
def remove_user_from_groups(self, user_id, body, **kwargs): kwargs[] = True if kwargs.get(): return self.remove_user_from_groups_with_http_info(user_id, body, **kwargs) else: (data) = self.remove_user_from_groups_with_http_info(user_id, body, **kwargs) ...
Remove user from groups. # noqa: E501 An endpoint for removing user from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f30242590700000000]' -H 'content-type: application/json' -H 'Authorization: Be...
343,754
def determine_ip_address(): addrs = [ x.address for k, v in psutil.net_if_addrs().items() if k[0] == "e" for x in v if x.family == AddressFamily.AF_INET ] return addrs[0]
Return the first IP address for an ethernet interface on the system.
343,755
def _set_tzdata(self, tzobj): for attr in _tzfile.attrs: setattr(self, + attr, getattr(tzobj, attr))
Set the time zone data of this object from a _tzfile object
343,756
def showPopup(self): as_dialog = QApplication.keyboardModifiers() anchor = self.defaultAnchor() if anchor: self.popupWidget().setAnchor(anchor) else: anchor = self.popupWidget().anchor() if ( anchor & (XPopupWidget.Anch...
Shows the popup for this button.
343,757
def Pool(pool=, **kwargs): AnyPool if pool == : return MPIPool(**kwargs) elif pool == : return MultiPool(**kwargs) elif pool == : return SerialPool(**kwargs) elif pool == : if MPIPool.enabled(): return MPIPool(**kwargs) elif MultiPool.enabled(): ...
Chooses between the different pools. If ``pool == 'AnyPool'``, chooses based on availability.
343,758
def render_next_step(self, form, **kwargs): next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) self.storage.current_step = next_step...
THis method gets called when the next step/form should be rendered. `form` contains the last/current form.
343,759
def decompress(f): r = meta(f.read(60)) return r, decomprest(f, r[4])
Decompress a Plan 9 image file. Assumes f is already cued past the initial 'compressed\n' string.
343,760
def _watch(self, path, current_level, max_level): stat = self._client.exists(path) if stat is None or stat.ephemeralOwner != 0: return try: children = self._client.get_children(path, self._watcher) except NoNodeError: children = [] ...
we need to catch ZNONODE because children might be removed whilst we are iterating (specially ephemeral znodes)
343,761
def decrement(self, key, value=1): return self._redis.decr(self._prefix + key, value)
Decrement the value of an item in the cache. :param key: The cache key :type key: str :param value: The decrement value :type value: int :rtype: int or bool
343,762
def as_dict(self): d = super(ObjectValidationResults, self).as_dict() if self.errors: d[] = [x.as_dict() for x in self.errors] return d
A dictionary representation of the :class:`.ObjectValidationResults` instance. Keys: * ``'result'``: The validation results (``True`` or ``False``) * ``'errors'``: A list of validation errors. Returns: A dictionary representation of an instance of this class...
343,763
def read_body(payload, content_type=JSON_CONTENT_TYPE): if content_type not in _READABLE_CONTENT_TYPES: msg = ( % (content_type, _READABLE_CONTENT_TYPES)) raise exceptions.UnsupportedContentTypeException(msg) try: content = payload.read() if not content: ...
Reads HTTP payload according to given content_type. Function is capable of reading from payload stream. Read data is then processed according to content_type. Note: Content-Type is validated. It means that if read_body body is not capable of reading data in requested type, it will ...
343,764
def text_opener(path, pattern=, verbose=False): source = path if is_url(path) else os.path.abspath(path) filename = os.path.basename(path) if pattern and not re.match(pattern, filename): logger.verbose(.format(os.path.abspath(path), pattern)) return filehandle = urlopen(path) if i...
Opener that opens single text file. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s).
343,765
def delete(self, *args, **kwargs): self.before_delete(args, kwargs) self.delete_object(kwargs) result = {: {: }} final_result = self.after_delete(result) return final_result
Delete an object
343,766
def get_related_entry_admin_url(entry): namespaces = { Document: , Link: , Page: , } for cls, url in namespaces.iteritems(): if issubclass(entry.content_type.model_class(), cls): return urlresolvers.reverse(url, args=(entry.object_id,)) re...
Returns admin URL for specified entry instance. :param entry: the entry instance. :return: str.
343,767
def plot_kdes(self, mnemonic, alias=None, uwi_regex=None, return_fig=False): wells = self.find_wells_with_curve(mnemonic, alias=alias) fig, axs = plt.subplots(len(self), 1, figsize=(10, 1.5*len(self))) curves = [w.get_curve(mnemonic, alias=alias) for w in wells] all_data = np.h...
Plot KDEs for all curves with the given name. Args: menmonic (str): the name of the curve to look for. alias (dict): a welly alias dictionary. uwi_regex (str): a regex pattern. Only this part of the UWI will be displayed on the plot of KDEs. retur...
343,768
def run_check(self, check, argument_names): arguments = [] for name in argument_names: arguments.append(getattr(self, name)) return check(*arguments)
Run a check plugin.
343,769
def diff_supplied(self, results_filenames, labels, tokenizer, output_fh): self._add_temporary_results_sets(results_filenames, labels) query = constants.SELECT_DIFF_SUPPLIED_SQL self._logger.info() self._logger.debug(.format(query)) self._log_query_plan(query, []) ...
Returns `output_fh` populated with CSV results giving the n-grams that are unique to the witnesses in each set of works in `results_sets`, using the labels in `labels`. Note that this is not the same as the symmetric difference of these sets, except in the case where there are only two ...
343,770
def gradients_X(self, dL_dK, X, X2=None): target = np.zeros(X.shape) [target.__iadd__(p.gradients_X(dL_dK, X, X2)) for p in self.parts] return target
Compute the gradient of the objective function with respect to X. :param dL_dK: An array of gradients of the objective function with respect to the covariance function. :type dL_dK: np.ndarray (num_samples x num_inducing) :param X: Observed data inputs :type X: np.ndarray (num_samples x...
343,771
def calcparams_pvsyst(self, effective_irradiance, temp_cell): kwargs = _build_kwargs([, , , , , , , , , , , , ], self.module_parameters) ...
Use the :py:func:`calcparams_pvsyst` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance : numeric The irradiance (W/m2) that is converted to photocurrent. ...
343,772
def get_fwhm_tag(expnum, ccd, prefix=None, version=): uri = get_uri(expnum, ccd, version, ext=, prefix=prefix) if uri not in fwhm: key = "fwhm_{:1s}{:02d}".format(version, int(ccd)) fwhm[uri] = get_tag(expnum, key) return fwhm[uri]
Get the FWHM from the VOSpace annotation. @param expnum: @param ccd: @param prefix: @param version: @return:
343,773
def update(self, other, inplace=True): return self.append(other, inplace=inplace, resize=False)
Update this series by appending new data from an other and dropping the same amount of data off the start. This is a convenience method that just calls `~Series.append` with `resize=False`.
343,774
def diff_boolean(self, df, column_name=None, uuid=None, duration=True, min_event_filter=): if uuid == None: uuid = data_gaps = df[(df.diff() == 1) | (df.diff() == -1)].dropna() data_gaps["duration"] = abs(data_gaps.index.to_series().diff(periods=-1)) data_gaps[uu...
takes the dataframe of missing values, and returns a dataframe that indicates the length of each event where data was continuously missing Parameters ---------- df : pd.DataFrame() Dataframe to check for missing data (must be in boolean format where 1 indic...
343,775
def sample_orbit(self, Npts=100, primary=None, trailing=True, timespan=None, useTrueAnomaly=True): pts = [] if primary is None: primary = self.jacobi_com o = self.calculate_orbit(primary=primary) if timespan is None: if o.a < 0.: timespa...
Returns a nested list of xyz positions along the osculating orbit of the particle. If primary is not passed, returns xyz positions along the Jacobi osculating orbit (with mu = G*Minc, where Minc is the total mass from index 0 to the particle's index, inclusive). Parameters ---------- ...
343,776
def _CreateStyle(self, doc, style_id, style_dict): def CreateElements(current_element, current_dict): for (key, value) in current_dict.iteritems(): element = ET.SubElement(current_element, key) if isinstance(value,dict): CreateElements(element, value) else: el...
Helper method to create a <Style/> element in a KML document. Args: doc: the parent KML document. style_id: the style id to include for the <Style/> element. style_dict: a dict of sub-elements and values to add to the <Style/>. Returns: The newly created <Style/> element. Each key...
343,777
def obtain_content_ranges(rangetext, filesize): listReturn = [] seqRanges = rangetext.split(",") for subrange in seqRanges: matched = False if not matched: mObj = reByteRangeSpecifier.search(subrange) if mObj: firstpos = int(mObj.group(2)) ...
returns tuple (list, value) list content ranges as values to their parsed components in the tuple (seek_position/abs position of first byte, abs position of last byte, num_of_bytes_to_read) value total length for Content-Length
343,778
def run_from_argv(self, argv): parser = self.create_parser(argv[0], argv[1]) options = parser.parse_args(argv[2:]) cmd_options = vars(options) args = cmd_options.pop(, ()) self.handle(*args, **cmd_options)
Called by the system when executing the command from the command line. This should not be overridden. :param argv: Arguments from command line
343,779
def start(name=, user=None, conf_file=None, bin_env=None): ** if name.endswith(): name = name[:-1] ret = __salt__[]( _ctl_cmd(, name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
Start the named service. Process group names should not include a trailing asterisk. user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. co...
343,780
def _get_spot_history(ctx, instance_type): one_week_ago = datetime.datetime.now() - datetime.timedelta(days=7) spot_data = ctx.ec2.get_spot_price_history(start_time=one_week_ago.isoformat(), instance_type=instance_type, ...
Returns list of 1,000 most recent spot market data points represented as SpotPriceHistory objects. Note: The most recent object/data point will be first in the list. :rtype: list[SpotPriceHistory]
343,781
def qos_map_cos_mutation_cos7(self, **kwargs): config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") cos_mutation = ET.SubElement(map, "cos-mutation") name_key = ET.SubElement(cos_mutati...
Auto Generated Code
343,782
def merge_config( config: Mapping[str, Any], override_config: Mapping[str, Any] = None, override_config_fn: str = None, ) -> Mapping[str, Any]: if override_config_fn: with open(override_config_fn, "r") as f: override_config = yaml.load(f, Loader=yaml.SafeLoader) if not ove...
Override config with additional configuration in override_config or override_config_fn Used in script to merge CLI options with Config Args: config: original configuration override_config: new configuration to override/extend current config override_config_fn: new configuration filenam...
343,783
def attowiki_distro_path(): attowiki_path = os.path.abspath(__file__) if attowiki_path[-1] != : attowiki_path = attowiki_path[:attowiki_path.rfind()] else: attowiki_path = attowiki_path[:attowiki_path[:-1].rfind()] return attowiki_path
return the absolute complete path where attowiki is located .. todo:: use pkg_resources ?
343,784
def move_group(self, group, parent, index=None): if not isinstance(group, Group): raise TypeError("group param must be of type Group") if parent is not None and not isinstance(parent, Group): raise TypeError("parent param must be of type Group") ...
Move group to be a child of new parent. :param group: The group to move. :type group: :class:`keepassdb.model.Group` :param parent: The new parent for the group. :type parent: :class:`keepassdb.model.Group` :param index: The 0-based index within the parent (defaults to a...
343,785
def clearLoggers(self, logger): for logger in self._loggers: if logger == : logger = logging.getLogger() else: logger = logging.getLogger(logger) logger.removeHandler(self.handler()) self._loggers = set()
Removes the inputed logger from the set for this widget. :param logger | <str> || <logging.Logger>
343,786
def _GetPredicate(self, pred_str, test_attr=False): predicate, args, func_type = self.predicates.LookupWithType(pred_str) if predicate: pred = predicate, args, func_type else: if test_attr: assert pred_str.en...
The user's predicates are consulted first, then the default predicates.
343,787
def do_fullscreen(self, widget): self.fullscreen() self.is_fullscreen = True while Gtk.events_pending(): Gtk.main_iteration() self.bot._screen_width = Gdk.Screen.width() self.bot._screen_height = Gdk.Screen.height() self.bot...
Widget Action to Make the window fullscreen and update the bot.
343,788
def save(self): pri_hdu = fits.PrimaryHDU(data=self.thmap) date_fmt = date_beg = self.start_time.strftime(date_fmt) date_end = self.end_time.strftime(date_fmt) date_now = datetime.utcnow().strftime(date_fmt) self.set_fits_header("TIMESYS", self.ref_hdr...
modified from suvi code by vhsu
343,789
def get_browser_locale(self): locale_id = self.get_cookie() if locale_id: return tornado.locale.get(locale_id) else: return tornado.locale.get()
Override the function, to control the UI language.
343,790
def get_object(self, dn, filter, attributes, _connection=None): connection = _connection if not connection: connection = self._make_connection( bind_user=self.config.get(), bind_password=self.config.get() ) connection.bind() ...
Gets an object at the specified dn and returns it. Args: dn (str): The dn of the object to find. filter (str): The LDAP syntax search filter. attributes (list): A list of LDAP attributes to get when searching. _connection (ldap3.Connection): A connection object t...
343,791
def get_xray_daemon(): env_value = os.environ.get() if env_value is None: raise XRayDaemonNotFoundError() xray_ip, xray_port = env_value.split() return XRayDaemon(ip_address=xray_ip, port=int(xray_port))
Parse X-Ray Daemon address environment variable. If the environment variable is not set, raise an exception to signal that we're unable to send data to X-Ray.
343,792
def sort_by(self, fieldName, reverse=False): return self.__class__( sorted(self, key = lambda item : self._get_item_value(item, fieldName), reverse=reverse) )
sort_by - Return a copy of this collection, sorted by the given fieldName. The fieldName is accessed the same way as other filtering, so it supports custom properties, etc. @param fieldName <str> - The name of the field on which to sort by @param reverse <bool> Default False...
343,793
def read(self): with open(self.version_file) as fp: version = fp.read().strip() if is_valid(version): return version return None
Read the project version from .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and read the version string.
343,794
def new_user(yaml_path): s home directory. Retrieve API Key from https://www.shirts.io/accounts/api_console/Shirts.io API Key: api_keyw+') yaml.dump(tokens, yaml_file, indent=2) yaml_file.close() return tokens
Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory.
343,795
def _ini_format(stream, options): for optname, optdict, value in options: value = _format_option_value(optdict, value) help_opt = optdict.get("help") if help_opt: help_opt = normalize_text(help_opt, line_len=79, indent=" print(file=stream) print(help_...
format options using the INI format
343,796
def data_in_label(intvl_in, dtype_in_time, dtype_in_vert=False): intvl_lbl = intvl_in time_lbl = dtype_in_time lbl = .join([, intvl_lbl, time_lbl]).replace(, ) vert_lbl = dtype_in_vert if dtype_in_vert else False if vert_lbl: lbl = .join([lbl, vert_lbl]).replace(, ) return lbl
Create string label specifying the input data of a calculation.
343,797
def from_stream(cls, stream): markers = _JfifMarkers.from_stream(stream) px_width = markers.sof.px_width px_height = markers.sof.px_height horz_dpi = markers.app1.horz_dpi vert_dpi = markers.app1.vert_dpi return cls(px_width, px_height, horz_dpi, vert_...
Return |Exif| instance having header properties parsed from Exif image in *stream*.
343,798
def insert( self, index: int, moment_or_operation_tree: Union[ops.Moment, ops.OP_TREE], strategy: InsertStrategy = InsertStrategy.EARLIEST) -> int: moments_and_operations = list(ops.flatten_op_tree( ops.transform_op_tree(moment_or_operation_tr...
Inserts operations into the circuit. Operations are inserted into the moment specified by the index and 'InsertStrategy'. Moments within the operation tree are inserted intact. Args: index: The index to insert all of the operations at. moment_or_opera...
343,799
def is_valid_address_for_coinsymbol(b58_address, coin_symbol): assert is_valid_coin_symbol(coin_symbol) if b58_address[0] in COIN_SYMBOL_MAPPINGS[coin_symbol][]: if is_valid_address(b58_address): return True return False
Is an address both valid *and* start with the correct character for its coin symbol (chain/network)