code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def from_yaml(cls, **kwargs): """Creates a new instance of a rule in relation to the config file. This updates the dictionary of the class with the added details, which allows for flexibility in the configuation file. Only called when parsing the default configuation file. """ ...
Creates a new instance of a rule in relation to the config file. This updates the dictionary of the class with the added details, which allows for flexibility in the configuation file. Only called when parsing the default configuation file.
def prettifysql(sql): """Returns a prettified version of the SQL as a list of lines to help in creating a useful diff between two SQL statements.""" pretty = [] for line in sql.split('\n'): pretty.extend(["%s,\n" % x for x in line.split(',')]) return pretty
Returns a prettified version of the SQL as a list of lines to help in creating a useful diff between two SQL statements.
def update(self, **kwargs): '''Update the model arguments with additional arguments. Args: kwargs (dict): Optional keyword arguments to add to prior args. ''' # Backends expect numpy arrays, so make sure all numeric values are # represented as such. kwargs =...
Update the model arguments with additional arguments. Args: kwargs (dict): Optional keyword arguments to add to prior args.
def gap_proportion(sequences, gap_chars='-'): """ Generates a list with the proportion of gaps by index in a set of sequences. """ aln_len = None gaps = [] for i, sequence in enumerate(sequences): if aln_len is None: aln_len = len(sequence) gaps = [0] * aln_le...
Generates a list with the proportion of gaps by index in a set of sequences.
async def get_response(self, message=None, *, timeout=None): """ Returns a coroutine that will resolve once a response arrives. Args: message (`Message <telethon.tl.custom.message.Message>` | `int`, optional): The message (or the message ID) for which a response ...
Returns a coroutine that will resolve once a response arrives. Args: message (`Message <telethon.tl.custom.message.Message>` | `int`, optional): The message (or the message ID) for which a response is expected. By default this is the last sent message. t...
def get_inasafe_fields(self): """Return inasafe fields from the current wizard state. :returns: Dictionary of key and value from InaSAFE Fields. :rtype: dict """ inasafe_fields = {} parameters = self.parameter_container.get_parameters(True) for parameter in param...
Return inasafe fields from the current wizard state. :returns: Dictionary of key and value from InaSAFE Fields. :rtype: dict
def nonanalytical_func(x, a, b): """ This can be any pythonic function which should be fitted, typically one which is not easily written or supported as an analytical expression. """ # Do your non-trivial magic here. In this case a Piecewise, although this # could also be done symbolically. ...
This can be any pythonic function which should be fitted, typically one which is not easily written or supported as an analytical expression.
def addSkip(self, test, reason): """Catch skipped tests in Python 2.7 and above. Though ``addSkip()`` is deprecated in the nose plugin API, it is very much not deprecated as a Python 2.7 ``TestResult`` method. In Python 2.7, this will get called instead of ``addError()`` for skips. ...
Catch skipped tests in Python 2.7 and above. Though ``addSkip()`` is deprecated in the nose plugin API, it is very much not deprecated as a Python 2.7 ``TestResult`` method. In Python 2.7, this will get called instead of ``addError()`` for skips. :arg reason: Text describing why the te...
def _internal_add(self, pattern: Pattern, label, renaming) -> int: """Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. ...
Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. Args: pattern: The pattern to add. Returns: ...
def IsPayable(self): """ Flag indicating if the contract accepts payments. Returns: bool: True if supported. False otherwise. """ from neo.Core.State.ContractState import ContractPropertyState return self.ContractProperties & ContractPropertyState.Payable > 0
Flag indicating if the contract accepts payments. Returns: bool: True if supported. False otherwise.
def search_proxy_entities(self, **kwargs): # noqa: E501 """Search over a customer's non-deleted proxies # 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.search...
Search over a customer's non-deleted proxies # 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.search_proxy_entities(async_req=True) >>> result = thread.get() ...
def _get_subelements(self, node): """Gather the sub-elements attached to a node Gather rdf:Bag and and rdf:Seq into set and list respectively. For alternate languages values, take the first language only for simplicity. """ items = node.find('rdf:Alt', self.NS) i...
Gather the sub-elements attached to a node Gather rdf:Bag and and rdf:Seq into set and list respectively. For alternate languages values, take the first language only for simplicity.
def _consolidate_classpath(self, targets, classpath_products): """Convert loose directories in classpath_products into jars. """ # TODO: find a way to not process classpath entries for valid VTs. # NB: It is very expensive to call to get entries for each target one at a time. # For performance reasons ...
Convert loose directories in classpath_products into jars.
def info(self, **kwargs): """ Get the detailed information about a particular credit record. This is currently only supported with the new credit model found in TV. These ids can be found from any TV credit response as well as the tv_credits and combined_credits methods for pe...
Get the detailed information about a particular credit record. This is currently only supported with the new credit model found in TV. These ids can be found from any TV credit response as well as the tv_credits and combined_credits methods for people. The episodes object returns a l...
def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com ...
Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2
def get_render(self, context): """ Returns a `Context` object with all the necessary stuff for rendering the form :param context: `django.template.Context` variable holding the context for the node `self.form` and `self.helper` are resolved into real Python objects resolving them ...
Returns a `Context` object with all the necessary stuff for rendering the form :param context: `django.template.Context` variable holding the context for the node `self.form` and `self.helper` are resolved into real Python objects resolving them from the `context`. The `actual_form` can be a f...
def _sort_topk_votes(x, k): """ Sort a dictionary of classes and corresponding vote totals according to the votes, then truncate to the highest 'k' classes. """ y = sorted(x.items(), key=lambda x: x[1], reverse=True)[:k] return [{'class': i[0], 'votes': i[1]} for i in y]
Sort a dictionary of classes and corresponding vote totals according to the votes, then truncate to the highest 'k' classes.
def annotate_image(self, request, retry=None, timeout=None): """Run image detection and annotation for an image. Example: >>> from google.cloud.vision_v1 import ImageAnnotatorClient >>> client = ImageAnnotatorClient() >>> request = { ... 'image': { ...
Run image detection and annotation for an image. Example: >>> from google.cloud.vision_v1 import ImageAnnotatorClient >>> client = ImageAnnotatorClient() >>> request = { ... 'image': { ... 'source': {'image_uri': 'https://foo.com/image.jpg...
def clear_distribute_compositions(self): """Removes the distribution rights. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from temp...
Removes the distribution rights. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
def _handle_event(self, event, *args, **kw): """Broadcast an event to the database connections registered.""" for engine in self.engines.values(): if hasattr(engine, event): getattr(engine, event)(*args, **kw)
Broadcast an event to the database connections registered.
def _distinct(row1, row2): """ Returns a list of distinct (or none overlapping) intervals if two intervals are overlapping. Returns None if the two intervals are none overlapping. The list can have 2 or 3 intervals. :param tuple[int,int] row1: The first interval. :param tuple[in...
Returns a list of distinct (or none overlapping) intervals if two intervals are overlapping. Returns None if the two intervals are none overlapping. The list can have 2 or 3 intervals. :param tuple[int,int] row1: The first interval. :param tuple[int,int] row2: The second interval. :rty...
def proj_simplex(x, diameter=1, out=None): r"""Projection onto simplex. Projection onto:: ``{ x \in X | x_i \geq 0, \sum_i x_i = r}`` with :math:`r` being the diameter. It is computed by the formula proposed in [D+2008]. Parameters ---------- space : `LinearSpace` Space /...
r"""Projection onto simplex. Projection onto:: ``{ x \in X | x_i \geq 0, \sum_i x_i = r}`` with :math:`r` being the diameter. It is computed by the formula proposed in [D+2008]. Parameters ---------- space : `LinearSpace` Space / domain ``X``. diameter : positive float, o...
def cosine_similarity(F_a, F_b): """ Calculate `cosine similarity <http://en.wikipedia.org/wiki/Cosine_similarity>`_ for sparse feature vectors. Parameters ---------- F_a : :class:`.Feature` F_b : :class:`.Feature` Returns ------- similarity : float Cosine similarit...
Calculate `cosine similarity <http://en.wikipedia.org/wiki/Cosine_similarity>`_ for sparse feature vectors. Parameters ---------- F_a : :class:`.Feature` F_b : :class:`.Feature` Returns ------- similarity : float Cosine similarity.
def _RZEOM(y,t,pot,l2): """ NAME: _RZEOM PURPOSE: implements the EOM, i.e., the right-hand side of the differential equation INPUT: y - current phase-space position t - current time pot - (list of) Potential instance(s) l2 - angular momentum squared ...
NAME: _RZEOM PURPOSE: implements the EOM, i.e., the right-hand side of the differential equation INPUT: y - current phase-space position t - current time pot - (list of) Potential instance(s) l2 - angular momentum squared OUTPUT: dy/dt HISTORY: ...
async def request(self): '''Perform the Http request to the upstream server ''' request_headers = self.request_headers() environ = self.environ method = environ['REQUEST_METHOD'] data = None if method in ENCODE_BODY_METHODS: data = DataIterator(self) ...
Perform the Http request to the upstream server
def userlogin(self, event): """Checks if an alert is ongoing and alerts the newly connected client, if so.""" client_uuid = event.clientuuid self.log(event.user, pretty=True, lvl=verbose) self.log('Adding client') self.clients[event.clientuuid] = event.user fo...
Checks if an alert is ongoing and alerts the newly connected client, if so.
def addToCommits(self, commit: Commit, sender: str): """ Add the specified COMMIT to this replica's list of received commit requests. :param commit: the COMMIT to add to the list :param sender: the name of the node that sent the COMMIT """ # BLS multi-sig: ...
Add the specified COMMIT to this replica's list of received commit requests. :param commit: the COMMIT to add to the list :param sender: the name of the node that sent the COMMIT
def _set_updater(self, updater): """Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Exampl...
Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Examples -------- >>> def update(k...
def _expand_terms(self, terms): """ Expands partition terms to the appropriate fields. Args: terms (dict or str): Returns: dict: keys are field names, values are query strings """ ret = { 'keywords': list(), 'doc': list(), ...
Expands partition terms to the appropriate fields. Args: terms (dict or str): Returns: dict: keys are field names, values are query strings
def format_output(self, rendered_widgets): """ Render the ``icekit_events/recurrence_rule_widget/format_output.html`` template with the following context: preset A choice field for preset recurrence rules. natural An input field for natura...
Render the ``icekit_events/recurrence_rule_widget/format_output.html`` template with the following context: preset A choice field for preset recurrence rules. natural An input field for natural language recurrence rules. rfc A ...
def assignable(self): """ See the class documentation. """ if self._cached_assignable is None: self._cached_assignable = self._assignable() return self._cached_assignable
See the class documentation.
def parse_and_load_contexts(contexts, schema=None, werr=False): """ :param contexts: list of context file specs :param schema: JSON schema file in any formats anyconfig supports, to validate given context files :param werr: Exit immediately if True and any errors occurrs while loading co...
:param contexts: list of context file specs :param schema: JSON schema file in any formats anyconfig supports, to validate given context files :param werr: Exit immediately if True and any errors occurrs while loading context files
def reindex(self): """Rebuilds all indexes on this collection. .. warning:: reindex blocks all other operations (indexes are built in the foreground) and will be slow for large collections. .. versionchanged:: 3.4 Apply this collection's write concern automatic...
Rebuilds all indexes on this collection. .. warning:: reindex blocks all other operations (indexes are built in the foreground) and will be slow for large collections. .. versionchanged:: 3.4 Apply this collection's write concern automatically to this operation ...
def load_conf(): '''获取基本设定信息, 里面存放着所有可用的profiles, 以及默认的profile''' if os.path.exists(_conf_file): with open(_conf_file) as fh: return json.load(fh) else: dump_conf(_base_conf) return _base_conf
获取基本设定信息, 里面存放着所有可用的profiles, 以及默认的profile
def _utc_datetime_to_epoch(self, activity_datetime): """ Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be co...
Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be considered to be UTC). :return: Epoch timestamp. :rtype: in...
def bbox_to_dimensions(bbox, resolution): """ Calculates width and height in pixels for a given bbox of a given pixel resolution (in meters). The result is rounded to nearest integers :param bbox: bounding box :type bbox: geometry.BBox :param resolution: Resolution of desired image in meters. It ca...
Calculates width and height in pixels for a given bbox of a given pixel resolution (in meters). The result is rounded to nearest integers :param bbox: bounding box :type bbox: geometry.BBox :param resolution: Resolution of desired image in meters. It can be a single number or a tuple of two numbers - ...
def store_alias(self, seq_id, namespace, alias): """associate a namespaced alias with a sequence Alias association with sequences is idempotent: duplicate associations are discarded silently. """ if not self._writeable: raise RuntimeError("Cannot write -- opened re...
associate a namespaced alias with a sequence Alias association with sequences is idempotent: duplicate associations are discarded silently.
def delete_unused_subjects(): """Delete any unused subjects from the database. This is not strictly required as any unused subjects will automatically be reused if needed in the future. """ # This causes Django to create a single join (check with query.query) query = d1_gmn.app.models.Subject....
Delete any unused subjects from the database. This is not strictly required as any unused subjects will automatically be reused if needed in the future.
def subplots_adjust(self, **kwargs): """Adjust subplot spacing and dimensions. Adjust bottom, top, right, left, width in between plots, and height in between plots with a call to ``plt.subplots_adjust``. See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html ...
Adjust subplot spacing and dimensions. Adjust bottom, top, right, left, width in between plots, and height in between plots with a call to ``plt.subplots_adjust``. See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html for more information. Keyword Argum...
def Handle(self, unused_args, token=None): """Fetches and renders current user's settings.""" result = ApiGrrUser(username=token.username) if data_store.RelationalDBEnabled(): user_record = data_store.REL_DB.ReadGRRUser(token.username) result.InitFromDatabaseObject(user_record) else: ...
Fetches and renders current user's settings.
def feed(self, from_date=None, from_offset=None, category=None, latest_items=None, arthur_items=None, filter_classified=None): """ Feed data in Elastic from Perceval or Arthur """ if self.fetch_archive: items = self.perceval_backend.fetch_from_archive() self.feed_it...
Feed data in Elastic from Perceval or Arthur
def _init_map(self): """stub""" super(SimpleDifficultyItemFormRecord, self)._init_map() self.my_osid_object_form._my_map['texts']['difficulty'] = \ self._difficulty_metadata['default_string_values'][0]
stub
def ffPDC(self): """Full frequency partial directed coherence. .. math:: \mathrm{ffPDC}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}} """ A = self.A() return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2), ...
Full frequency partial directed coherence. .. math:: \mathrm{ffPDC}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}}
def savefits(cube, fitsname, **kwargs): """Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto(). """ ### pick up kwargs dropdeg ...
Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto().
def width(self, add_quiet_zone=False): """Return the barcodes width in modules for a given data and character set combination. :param add_quiet_zone: Whether quiet zone should be included in the width. :return: Width of barcode in modules, which for images translates to pixels. """ ...
Return the barcodes width in modules for a given data and character set combination. :param add_quiet_zone: Whether quiet zone should be included in the width. :return: Width of barcode in modules, which for images translates to pixels.
def run_inference_on_image(image): """Runs inference on an image. Args: image: Image file name. Returns: Nothing """ if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() # Creates graph from saved GraphDef. cr...
Runs inference on an image. Args: image: Image file name. Returns: Nothing
def init_dense_weight(layer): '''initilize dense layer weight. ''' units = layer.units weight = np.eye(units) bias = np.zeros(units) layer.set_weights( (add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1]))) )
initilize dense layer weight.
def _setup_cgroup_memory_limit(self, memlimit, cgroups, pid_to_kill): """Start memory-limit handler. @return None or the memory-limit handler for calling cancel() """ if memlimit is not None: try: oomThread = oomhandler.KillProcessOnOomThread( ...
Start memory-limit handler. @return None or the memory-limit handler for calling cancel()
def prt_objdesc(self, prt): """Return description of this GoSubDag object.""" txt = "INITIALIZING GoSubDag: {N:3} sources in {M:3} GOs rcnt({R}). {A} alt GO IDs\n" alt2obj = {go:o for go, o in self.go2obj.items() if go != o.id} prt.write(txt.format( N=len(self.go_sources), ...
Return description of this GoSubDag object.
def flag_based_complete(self, text: str, line: str, begidx: int, endidx: int, flag_dict: Dict[str, Union[Iterable, Callable]], all_else: Union[None, Iterable, Callable] = None) -> List[str]: """ Tab completes based on a particular flag preceding th...
Tab completes based on a particular flag preceding the token being completed :param text: the string prefix we are attempting to match (all returned matches must begin with it) :param line: the current input line with leading whitespace removed :param begidx: the beginning index of the prefix te...
def parquet(self, path): """Loads a Parquet file stream, returning the result as a :class:`DataFrame`. You can set the following Parquet-specific option(s) for reading Parquet files: * ``mergeSchema``: sets whether we should merge schemas collected from all \ Parquet part-fi...
Loads a Parquet file stream, returning the result as a :class:`DataFrame`. You can set the following Parquet-specific option(s) for reading Parquet files: * ``mergeSchema``: sets whether we should merge schemas collected from all \ Parquet part-files. This will override ``spark.sql....
def _set_pfc_threshold(self, v, load=False): """ Setter method for pfc_threshold, mapped from YANG variable /interface/port_channel/qos/flowcontrol/pfc_threshold (container) If this variable is read-only (config: false) in the source YANG file, then _set_pfc_threshold is considered as a private meth...
Setter method for pfc_threshold, mapped from YANG variable /interface/port_channel/qos/flowcontrol/pfc_threshold (container) If this variable is read-only (config: false) in the source YANG file, then _set_pfc_threshold is considered as a private method. Backends looking to populate this variable should ...
def _set_resource_monitor(self, v, load=False): """ Setter method for resource_monitor, mapped from YANG variable /resource_monitor (container) If this variable is read-only (config: false) in the source YANG file, then _set_resource_monitor is considered as a private method. Backends looking to pop...
Setter method for resource_monitor, mapped from YANG variable /resource_monitor (container) If this variable is read-only (config: false) in the source YANG file, then _set_resource_monitor is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._se...
def load_collided_alias(self): """ Load (create, if not exist) the collided alias file. """ # w+ creates the alias config file if it does not exist open_mode = 'r+' if os.path.exists(GLOBAL_COLLIDED_ALIAS_PATH) else 'w+' with open(GLOBAL_COLLIDED_ALIAS_PATH, open_mode) as...
Load (create, if not exist) the collided alias file.
def task_present(name, tick_script, task_type='stream', database=None, retention_policy='default', enable=True, dbrps=None): ''' Ensure that a task is present and up-to-date in Kapacitor. name Name...
Ensure that a task is present and up-to-date in Kapacitor. name Name of the task. tick_script Path to the TICK script for the task. Can be a salt:// source. task_type Task type. Defaults to 'stream' dbrps A list of databases and retention policies in "dbname"."rpname"...
def reshape_line_plot(df, x, y): """Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers. """ idx = list(df.columns.drop(y)) if df.duplicated(idx).any(): ...
Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers.
def closeEvent(self, e): """Qt slot when the window is closed.""" self.emit('close_widget') super(DockWidget, self).closeEvent(e)
Qt slot when the window is closed.
def clear(self, policy='all'): """ Clear all subscribers registered to this stream. The default policy of 'all' clears all subscribers. If policy is set to 'user', only subscribers defined by the user are cleared (precedence between zero and one). A policy of 'internal' clears ...
Clear all subscribers registered to this stream. The default policy of 'all' clears all subscribers. If policy is set to 'user', only subscribers defined by the user are cleared (precedence between zero and one). A policy of 'internal' clears subscribers with precedence greater than uni...
def flatten(weights, start=0, stop=2): """This methods reshapes all values in a dictionary. The indices from start to stop will be flattened into a single index. Args: weights: A dictionary mapping keys to numpy arrays. start: The starting index. stop: The ending index. """ ...
This methods reshapes all values in a dictionary. The indices from start to stop will be flattened into a single index. Args: weights: A dictionary mapping keys to numpy arrays. start: The starting index. stop: The ending index.
def tag_info(self): """Return Unicode string with class, name and unnested value.""" return self.__class__.__name__ + ( '(%r)' % self.name if self.name else "") + ": " + self.valuestr()
Return Unicode string with class, name and unnested value.
def E_CMFR_N(t, N): """Calculate a dimensionless measure of the output tracer concentration from a spike input to a series of completely mixed flow reactors. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR....
Calculate a dimensionless measure of the output tracer concentration from a spike input to a series of completely mixed flow reactors. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or nump...
def smart_search(self, *arguments): """ Perform a smart search on the given keywords or patterns. :param arguments: The keywords or patterns to search for. :returns: The matched password names (a list of strings). :raises: The following exceptions can be raised: ...
Perform a smart search on the given keywords or patterns. :param arguments: The keywords or patterns to search for. :returns: The matched password names (a list of strings). :raises: The following exceptions can be raised: - :exc:`.NoMatchingPasswordError` when no matching pas...
def _handle_struct(toks): """ Generate the correct function for a struct signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((list or tuple) -> (Struct * int)) * str """ subtrees = toks[1:-1] ...
Generate the correct function for a struct signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((list or tuple) -> (Struct * int)) * str
def build(self, output_path=""): """method that should be inherited by all vis classes""" self.output_path = self.checkOutputPath(output_path) self._buildStaticFiles() self.final_url = self._buildTemplates() printDebug("Done.", "comment") printDebug("=> %s" % (self.final...
method that should be inherited by all vis classes
def fix_timezone_separator(cls, timestr): """Replace invalid timezone separator to prevent `dateutil.parser.parse` to raise. :return: the new string if invalid separators were found, `None` otherwise """ tz_sep = cls.TIMEZONE_SEPARATOR.match(timestr) if ...
Replace invalid timezone separator to prevent `dateutil.parser.parse` to raise. :return: the new string if invalid separators were found, `None` otherwise
def leading_transpose(tensor: tf.Tensor, perm: List[Union[int, type(...)]]) -> tf.Tensor: """ Transposes tensors with leading dimensions. Leading dimensions in permutation list represented via ellipsis `...`. When leading dimensions are found, `transpose` method considers them as a single grouped e...
Transposes tensors with leading dimensions. Leading dimensions in permutation list represented via ellipsis `...`. When leading dimensions are found, `transpose` method considers them as a single grouped element indexed by 0 in `perm` list. So, passing `perm=[-2, ..., -1]`, you assume that your input t...
def get_zeropoint(expnum, ccd, prefix=None, version='p'): """Get the zeropoint for this exposure using the zeropoint.used file created during source planting.. This command expects that there is a file called #######p##.zeropoint.used which contains the zeropoint. @param expnum: exposure to get zeropoint ...
Get the zeropoint for this exposure using the zeropoint.used file created during source planting.. This command expects that there is a file called #######p##.zeropoint.used which contains the zeropoint. @param expnum: exposure to get zeropoint of @param ccd: which ccd (extension - 1) to get zp @param...
def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec): """Get a list of key_ranges.KeyRanges objects, one for each shard. This method uses scatter index to split each namespace into pieces and assign those pieces to shards. Args: app: app_id in str. namespaces: a list ...
Get a list of key_ranges.KeyRanges objects, one for each shard. This method uses scatter index to split each namespace into pieces and assign those pieces to shards. Args: app: app_id in str. namespaces: a list of namespaces in str. shard_count: number of shards to split. query_spe...
def get_distinguished(cls, account): """Gets the distinguished folder for this folder class""" if not cls.DISTINGUISHED_FOLDER_ID: raise ValueError('Class %s must have a DISTINGUISHED_FOLDER_ID value' % cls) folders = list(FolderCollection( account=account, fo...
Gets the distinguished folder for this folder class
def zlines(f = None, sep = "\0", osep = None, size = 8192): # {{{1 """File iterator that uses alternative line terminators.""" if f is None: f = sys.stdin if osep is None: osep = sep buf = "" while True: chars = f.read(size) if not chars: break buf += chars; lines = buf.split(sep); buf = lines...
File iterator that uses alternative line terminators.
def _generate_moment_matrix(self, n_vars, block_index, processed_entries, monomialsA, monomialsB, ppt=False): """Generate the moment matrix of monomials. Arguments: n_vars -- current number of variables block_index -- current block index in the SDP matrix...
Generate the moment matrix of monomials. Arguments: n_vars -- current number of variables block_index -- current block index in the SDP matrix monomials -- |W_d| set of words of length up to the relaxation level
def wrap(self, availWidth, availHeight): " This can be called more than once! Do not overwrite important data like drawWidth " availHeight = self.setMaxHeight(availHeight) # print "image wrap", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight width = min(self.drawWidth,...
This can be called more than once! Do not overwrite important data like drawWidth
def asArcPyObject(self): """ returns the Point as an ESRI arcpy.Point object """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") return arcpy.AsShape(self.asDictionary, True)
returns the Point as an ESRI arcpy.Point object
def interval_host(host, time, f, *args, **kwargs): ''' Creates an Event attached to the *host* for management that will execute the *f* function every *time* seconds. See example in :ref:`sample_inter` :param Proxy host: proxy of the host. Can be obtained from inside a class with ``self.ho...
Creates an Event attached to the *host* for management that will execute the *f* function every *time* seconds. See example in :ref:`sample_inter` :param Proxy host: proxy of the host. Can be obtained from inside a class with ``self.host``. :param int time: seconds for the intervals. :para...
def _pad_plot_frame(ax, pad=0.01): """ Provides padding on sides of frame equal to pad fraction of plot """ xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() xr = xmax - xmin yr = ymax - ymin ax.set_xlim(xmin - xr*pad, xmax + xr*pad) ax.set_ylim(ymin - yr*pad, ymax + yr*pad) ...
Provides padding on sides of frame equal to pad fraction of plot
def itemgetter(k, ellipsis=False, key=None): """ Looks up ``k`` as an index of the column's value. If ``k`` is a ``slice`` type object, then ``ellipsis`` can be given as a string to use to indicate truncation. Alternatively, ``ellipsis`` can be set to ``True`` to use a default ``'...'``. If a...
Looks up ``k`` as an index of the column's value. If ``k`` is a ``slice`` type object, then ``ellipsis`` can be given as a string to use to indicate truncation. Alternatively, ``ellipsis`` can be set to ``True`` to use a default ``'...'``. If a ``key`` is given, it may be a function which maps the ta...
def download_stories(self, userids: Optional[List[Union[int, Profile]]] = None, fast_update: bool = False, filename_target: Optional[str] = ':stories', storyitem_filter: Optional[Callable[[StoryItem], bool]] = None) -> N...
Download available stories from user followees or all stories of users whose ID are given. Does not mark stories as seen. To use this, one needs to be logged in :param userids: List of user IDs or Profiles to be processed in terms of downloading their stories :param fast_update: If true...
def percentile(p, arr=None): """Returns the pth percentile of the input array (the value that is at least as great as p% of the values in the array). If arr is not provided, percentile returns itself curried with p >>> percentile(74.9, [1, 3, 5, 9]) 5 >>> percentile(75, [1, 3, 5, 9]) 5 ...
Returns the pth percentile of the input array (the value that is at least as great as p% of the values in the array). If arr is not provided, percentile returns itself curried with p >>> percentile(74.9, [1, 3, 5, 9]) 5 >>> percentile(75, [1, 3, 5, 9]) 5 >>> percentile(75.1, [1, 3, 5, 9]) ...
def calculate_ef(ef_structure, fpf, diff = None, include_intervals = None): """ TO DO: Add logit bounds Determine ROC enrichment factor (EF) and 95% confidence intervals (CI) at input false positive fraction (fpf) None is returned if fpf is undefined given the total no. of decoys :param ef_structure...
TO DO: Add logit bounds Determine ROC enrichment factor (EF) and 95% confidence intervals (CI) at input false positive fraction (fpf) None is returned if fpf is undefined given the total no. of decoys :param ef_structure: list [(id, best_score, best_query, status, gamma), ..., ] gamma is 1 if the score ...
def imdct(y, L): """Inverse Modified Discrete Cosine Transform (MDCT) Returns the Inverse Modified Discrete Cosine Transform with fixed window size L of the vector of coefficients y. The window is based on a sine window. Parameters ---------- y : ndarray, shape (L/2, 2 * N / L) Th...
Inverse Modified Discrete Cosine Transform (MDCT) Returns the Inverse Modified Discrete Cosine Transform with fixed window size L of the vector of coefficients y. The window is based on a sine window. Parameters ---------- y : ndarray, shape (L/2, 2 * N / L) The MDCT coefficients ...
def _is_mergable_statement_list(cls, stmsA, stmsB): """ Walk statements and compare if they can be merged into one statement list """ if stmsA is None and stmsB is None: return True elif stmsA is None or stmsB is None: return False a_it = iter(st...
Walk statements and compare if they can be merged into one statement list
def validate(self): """Validates this distribution against its configured constraints. Raises Distribution.Error if this distribution is not valid according to the configured constraints. """ if self._validated_binaries: return with self._valid_executable('java') as java: if self._...
Validates this distribution against its configured constraints. Raises Distribution.Error if this distribution is not valid according to the configured constraints.
def _datetime_to_pb_timestamp(when): """Convert a datetime object to a Timestamp protobuf. :type when: :class:`datetime.datetime` :param when: the datetime to convert :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp` :returns: A timestamp protobuf corresponding to the object. """ ms...
Convert a datetime object to a Timestamp protobuf. :type when: :class:`datetime.datetime` :param when: the datetime to convert :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp` :returns: A timestamp protobuf corresponding to the object.
def threaded( # noqa: F811 name: typing.Optional[typing.Union[str, typing.Callable[..., typing.Any]]] = None, daemon: bool = False, started: bool = False, ) -> typing.Union[Threaded, typing.Callable[..., threading.Thread]]: """Run function in separate thread. :param name: New thread name. ...
Run function in separate thread. :param name: New thread name. If callable: use as wrapped function. If none: use wrapped function name. :type name: typing.Union[None, str, typing.Callable] :param daemon: Daemonize thread. :type daemon: bool :param started: Return ...
def upload_celery_conf(command='celeryd', app_name=None, template_name=None, context=None): """Upload Supervisor configuration for a celery command.""" app_name = app_name or command default = {'app_name': app_name, 'command': command} context = context or {} default.update(context) template_na...
Upload Supervisor configuration for a celery command.
def create_missing_features( dataframe, unique_keys={}, extra_columns={}, missing_value=None): """ Helper function used to construct a missing feature such as 'transcript' or 'gene'. Some GTF files only have 'exon' and 'CDS' entries, but have transcript_id and gene_id ann...
Helper function used to construct a missing feature such as 'transcript' or 'gene'. Some GTF files only have 'exon' and 'CDS' entries, but have transcript_id and gene_id annotations which allow us to construct those missing features. Parameters ---------- dataframe : pandas.DataFrame Sh...
def _setup_logging(self, log_level: str): """Setup logging for the application and aiohttp.""" level = getattr(logging, log_level) names = ( 'aiohttp.access', 'aiohttp.internal', 'aiohttp.server', 'aiohttp.web', self.name) for name in names: setup_logg...
Setup logging for the application and aiohttp.
def _check_source(cls, source_file_hash, source): """Checks if a pre-trained token embedding source name is valid. Parameters ---------- source : str The pre-trained token embedding source. """ embedding_name = cls.__name__.lower() if source not in s...
Checks if a pre-trained token embedding source name is valid. Parameters ---------- source : str The pre-trained token embedding source.
def GetClassesByArtifact(cls, artifact_name): """Get the classes that support parsing a given artifact.""" return [ cls.classes[c] for c in cls.classes if artifact_name in cls.classes[c].supported_artifacts ]
Get the classes that support parsing a given artifact.
def _makeBaseDir(basedir, quiet): """ Make worker base directory if needed. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making base directory """ if os.path.exists(basedir): if not quiet: ...
Make worker base directory if needed. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making base directory
def get_flights(self, search_key): """Get the flights for a particular airline. Given a full or partial flight number string, this method returns the first 100 flights matching that string. Please note this method was different in earlier versions. The older versions took an airline code and r...
Get the flights for a particular airline. Given a full or partial flight number string, this method returns the first 100 flights matching that string. Please note this method was different in earlier versions. The older versions took an airline code and returned all scheduled flights for that airline...
def save_binary(self, fname, silent=True): """Save DMatrix to an XGBoost buffer. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the output is suppressed. """ _check_call...
Save DMatrix to an XGBoost buffer. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the output is suppressed.
def render_to_response(self, context, *args, **kwargs): """ Build dictionary of content """ preview_outputs = [] file_outputs = [] bast_ctx = context added = set() for output_group, output_files in context['job_info']['file_groups'].items(): f...
Build dictionary of content
def check_version(): """ Compares the local version against the latest official version on PyPI and displays a warning message if a newer release is available. This check can be disabled by setting the environment variable BURLAP_CHECK_VERSION=0. """ global CHECK_VERSION if not CHECK_VERSION: ...
Compares the local version against the latest official version on PyPI and displays a warning message if a newer release is available. This check can be disabled by setting the environment variable BURLAP_CHECK_VERSION=0.
def add_key_binding(self): """ Shortcut for adding new key bindings. (Mostly useful for a .ptpython/config.py file, that receives a PythonInput/Repl instance as input.) :: @python_input.add_key_binding(Keys.ControlX, filter=...) def handler(event): ...
Shortcut for adding new key bindings. (Mostly useful for a .ptpython/config.py file, that receives a PythonInput/Repl instance as input.) :: @python_input.add_key_binding(Keys.ControlX, filter=...) def handler(event): ...
def init_default(self): """Overriden to take default database and save locally The issue was that init_default() sets self.filename to None; however there can be no SQLite database without a corresponding file (not using *memory* here) Should not keep default file open either (as it is...
Overriden to take default database and save locally The issue was that init_default() sets self.filename to None; however there can be no SQLite database without a corresponding file (not using *memory* here) Should not keep default file open either (as it is in the API directory and shouldn't...
def rdl_decomposition_nrev(T, k, norm='standard', ncv=None): r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : sparse matrix Transition matrix k : int Number of eigenvector/eigenvalue pairs norm: {'standard', 'reversible'} standard...
r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : sparse matrix Transition matrix k : int Number of eigenvector/eigenvalue pairs norm: {'standard', 'reversible'} standard: (L'R) = Id, L[:,0] is a probability distribution, t...
def _set_multicast(self, v, load=False): """ Setter method for multicast, mapped from YANG variable /qos/queue/multicast (container) If this variable is read-only (config: false) in the source YANG file, then _set_multicast is considered as a private method. Backends looking to populate this variabl...
Setter method for multicast, mapped from YANG variable /qos/queue/multicast (container) If this variable is read-only (config: false) in the source YANG file, then _set_multicast is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_multicast...
def set_meta(self, instance): """ Set django-meta stuff from LandingPageModel instance. """ self.use_title_tag = True self.title = instance.title
Set django-meta stuff from LandingPageModel instance.
def onecodex(ctx, api_key, no_pprint, verbose, telemetry): """One Codex v1 API command line interface""" # set up the context for sub commands click.Context.get_usage = click.Context.get_help ctx.obj = {} ctx.obj["API_KEY"] = api_key ctx.obj["NOPPRINT"] = no_pprint ctx.obj["TELEMETRY"] = tel...
One Codex v1 API command line interface