positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _ls_print_listing(dir_: str, recursive: bool, all_: bool, long: bool) -> List[Tuple[str, dict, TrainingTrace]]: """ Print names of the train dirs contained in the given dir. :param dir_: dir to be listed :param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option) ...
Print names of the train dirs contained in the given dir. :param dir_: dir to be listed :param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option) :param all_: include train dirs with no epochs done (--all option) :param long: list more details including model name, ...
def to_float(*args): """ cast numpy arrays to float32 if there's more than one, return an array """ floats = [np.array(a, dtype=np.float32) for a in args] return floats[0] if len(floats) == 1 else floats
cast numpy arrays to float32 if there's more than one, return an array
def call(self, tag_name: str, *args, **kwargs): """Convenience method for calling methods with walker.""" if hasattr(self, tag_name): getattr(self, tag_name)(*args, **kwargs)
Convenience method for calling methods with walker.
def reformat_schema(model): """ Reformat schema to be in a more displayable format. """ if not hasattr(model, 'schema'): return "Model '{}' does not have a schema".format(model) if 'properties' not in model.schema: return "Schema in unexpected format." ret = copy.deepcopy(model.schema[...
Reformat schema to be in a more displayable format.
def get_by_symbol(self, symbol: str) -> Commodity: """ Returns the commodity with the given symbol. If more are found, an exception will be thrown. """ # handle namespace. Accept GnuCash and Yahoo-style symbols. full_symbol = self.__parse_gc_symbol(symbol) query ...
Returns the commodity with the given symbol. If more are found, an exception will be thrown.
def copy_folder(self, to_folder): """ Copy this folder and it's contents to into another folder :param to_folder: the destination Folder/folder_id to copy into :type to_folder: mailbox.Folder or str :return: The new folder after copying :rtype: mailbox.Folder or None """...
Copy this folder and it's contents to into another folder :param to_folder: the destination Folder/folder_id to copy into :type to_folder: mailbox.Folder or str :return: The new folder after copying :rtype: mailbox.Folder or None
def spawn(func, *args, **kwargs): """Spawn a new fiber. A new :class:`Fiber` is created with main function *func* and positional arguments *args*. The keyword arguments are passed to the :class:`Fiber` constructor, not to the main function. The fiber is then scheduled to start by calling its :meth:...
Spawn a new fiber. A new :class:`Fiber` is created with main function *func* and positional arguments *args*. The keyword arguments are passed to the :class:`Fiber` constructor, not to the main function. The fiber is then scheduled to start by calling its :meth:`~Fiber.start` method. The fiber ins...
def get_products(self, product_ids): """ This function (and backend API) is being obsoleted. Don't use it anymore. """ if self.product_set_id is None: raise ValueError('product_set_id must be specified') data = {'ids': product_ids} return self.client.get(self....
This function (and backend API) is being obsoleted. Don't use it anymore.
def make_reddit_blueprint( client_id=None, client_secret=None, scope="identity", permanent=False, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, user_agent=None, ): """ Make a blueprint for authenticating wi...
Make a blueprint for authenticating with Reddit using OAuth 2. This requires a client ID and client secret from Reddit. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`REDDIT_OAUTH_CLIENT_ID` and :envvar:`REDDIT_...
def nested_get(dictionary, keys): """ Get value in dictionary for dictionary[keys[0]][keys[1]][keys[..n]] :param dictionary: An input dictionary :param keys: Keys where to store data :return: """ return reduce(lambda d, k: d[k], keys, dictionary)
Get value in dictionary for dictionary[keys[0]][keys[1]][keys[..n]] :param dictionary: An input dictionary :param keys: Keys where to store data :return:
def package_node(root=None, name=None): '''package node aims to package a (present working node) for a user into a container. This assumes that the node is a single partition. :param root: the root of the node to package, default is / :param name: the name for the image. If not specified, will use ma...
package node aims to package a (present working node) for a user into a container. This assumes that the node is a single partition. :param root: the root of the node to package, default is / :param name: the name for the image. If not specified, will use machine's psutil.disk_partitions()
def _update_stage(awsclient, api_id, stage_name, method_settings): """Helper to apply method_settings to stage :param awsclient: :param api_id: :param stage_name: :param method_settings: :return: """ # settings docs in response: https://botocore.readthedocs.io/en/latest/reference/servic...
Helper to apply method_settings to stage :param awsclient: :param api_id: :param stage_name: :param method_settings: :return:
def amplitude_by_fft(self, data_frame): """ This methods extract the fft components and sum the ones from lower to upper freq as per \ :cite:`Kassavetis2015` :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ampl: the ampl ...
This methods extract the fft components and sum the ones from lower to upper freq as per \ :cite:`Kassavetis2015` :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ampl: the ampl :rtype ampl: float :return freq: the freq...
def required_fields(self): """The normal required fields (eg, no magic fields like _id are included)""" return {f:v for f, v in self.normal_fields.items() if v.required}
The normal required fields (eg, no magic fields like _id are included)
def dhcp_options_present(name, dhcp_options_id=None, vpc_name=None, vpc_id=None, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, tags=None, region=None, key=None, keyid=None, profi...
Ensure a set of DHCP options with the given settings exist. Note that the current implementation only SETS values during option set creation. It is unable to update option sets in place, and thus merely verifies the set exists via the given name and/or dhcp_options_id param. name (string) ...
def bind(self, fn: Callable[[Any], 'Observable']) -> 'Observable': r"""Chain continuation passing functions. Haskell: m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c """ source = self return Observable(lambda on_next: source.subscribe(lambda a: fn(a).subscribe(on_next))...
r"""Chain continuation passing functions. Haskell: m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c
def ext_import(soname, module_subpath=""): """ Loads a turicreate toolkit module (a shared library) into the tc.extensions namespace. Toolkit module created via SDK can either be directly imported, e.g. ``import example`` or via this function, e.g. ``turicreate.ext_import("example.so")``. Use `...
Loads a turicreate toolkit module (a shared library) into the tc.extensions namespace. Toolkit module created via SDK can either be directly imported, e.g. ``import example`` or via this function, e.g. ``turicreate.ext_import("example.so")``. Use ``ext_import`` when you need more namespace control, or ...
def generate_anstar_3d_lattice(maxv1, minv1, maxv2, minv2, maxv3, minv3, \ mindist): """ This function calls into LAL routines to generate a 3-dimensional array of points using the An^* lattice. Parameters ----------- maxv1 : float Largest value in the 1st...
This function calls into LAL routines to generate a 3-dimensional array of points using the An^* lattice. Parameters ----------- maxv1 : float Largest value in the 1st dimension to cover minv1 : float Smallest value in the 1st dimension to cover maxv2 : float Largest val...
def clear_cognitive_process(self): """Clears the cognitive process. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resourc...
Clears the cognitive process. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
def get_channels(self): """Get all tv channels.""" self.request(EP_GET_TV_CHANNELS) return {} if self.last_response is None else self.last_response.get('payload').get('channelList')
Get all tv channels.
def point_to_line(point, segment_start, segment_end): """Given a point and a line segment, return the vector from the point to the closest point on the segment. """ # TODO: Needs unittests. segment_vec = segment_end - segment_start # t is distance along line t = -(segment_start - point).dot...
Given a point and a line segment, return the vector from the point to the closest point on the segment.
def icmp(a, b): "Like cmp(), but for any iterator." for xa in a: try: xb = next(b) d = cmp(xa, xb) if d: return d except StopIteration: return 1 try: next(b) return -1 except StopIteration: return 0
Like cmp(), but for any iterator.
def batch_size(self, batch_size): """Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer. .. note:: batch_size can not override MongoDB's internal limits on the ...
Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer. .. note:: batch_size can not override MongoDB's internal limits on the amount of data it will return to the client...
def remove_allocated_node_name(self, name): """ Removes an allocated node name :param name: allocated node name """ if name in self._allocated_node_names: self._allocated_node_names.remove(name)
Removes an allocated node name :param name: allocated node name
def prepare_mongod_server(server): """ Contains post start server operations """ log_info("Preparing server '%s' for use as configured..." % server.id) cluster = server.get_cluster() # setup the local users if server supports that if server.supports_local_users(): user...
Contains post start server operations
def classes_and_not_datetimelike(*klasses): """ evaluate if the tipo is a subclass of the klasses and not a datetimelike """ return lambda tipo: (issubclass(tipo, klasses) and not issubclass(tipo, (np.datetime64, np.timedelta64)))
evaluate if the tipo is a subclass of the klasses and not a datetimelike
def get_reference_results(self): """Return a mapping of Analysis Service -> Reference Results """ referenceresults = self.context.getReferenceResults() return dict(map(lambda rr: (rr.get("uid"), rr), referenceresults))
Return a mapping of Analysis Service -> Reference Results
def count(self, with_limit_and_skip=False): """**DEPRECATED** - Get the size of the results set for this query. The :meth:`count` method is deprecated and **not** supported in a transaction. Please use :meth:`~pymongo.collection.Collection.count_documents` instead. Returns the ...
**DEPRECATED** - Get the size of the results set for this query. The :meth:`count` method is deprecated and **not** supported in a transaction. Please use :meth:`~pymongo.collection.Collection.count_documents` instead. Returns the number of documents in the results set for this query. ...
def st_atime(self): """Return the access time in seconds.""" atime = self._st_atime_ns / 1e9 return atime if self.use_float else int(atime)
Return the access time in seconds.
def fill(self, paths): """ Initialise the tree. paths is a list of strings where each string is the relative path to some file. """ for path in paths: tree = self.tree parts = tuple(path.split('/')) dir_parts = parts[:-1] b...
Initialise the tree. paths is a list of strings where each string is the relative path to some file.
def exponweib_like(x, alpha, k, loc=0, scale=1): R""" Exponentiated Weibull log-likelihood. The exponentiated Weibull distribution is a generalization of the Weibull family. Its value lies in being able to model monotone and non-monotone failure rates. .. math:: f(x \mid \alpha,k,loc,s...
R""" Exponentiated Weibull log-likelihood. The exponentiated Weibull distribution is a generalization of the Weibull family. Its value lies in being able to model monotone and non-monotone failure rates. .. math:: f(x \mid \alpha,k,loc,scale) & = \frac{\alpha k}{scale} (1-e^{-z^k})^{\alph...
def format_file(filename, args, standard_out): """Run format_code() on a file. Returns `True` if any changes are needed and they are not being done in-place. """ encoding = detect_encoding(filename) with open_with_encoding(filename, encoding=encoding) as input_file: source = input_file...
Run format_code() on a file. Returns `True` if any changes are needed and they are not being done in-place.
def load(self): """ Loads the children for this item. """ if self._loaded: return self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless) self._loaded = True column = self.schemaColumn() if not column.isRe...
Loads the children for this item.
def deprecated(func): '''This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.''' import warnings @functools.wraps(func) def new_func(*args, **kwargs): if is_python_3: code = func.__code__...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
def set(self, key, value): """Set the value of `key` preference to `value`.""" if key in self.callbacks: self.callbacks[key](value) else: self.prefs[key] = value
Set the value of `key` preference to `value`.
def close(self, idempotency_key=None): """Return a deferred.""" url = self.instance_url() + '/close' headers = populate_headers(idempotency_key) d = self.request('post', url, {}, headers) return d.addCallback(self.refresh_from).addCallback(lambda _: self)
Return a deferred.
def contains_exclusive(self, x, y): """ Return True if the given point is contained within the bounding box, where the bottom and right boundaries are considered exclusive. """ left, bottom, right, top = self._aarect.lbrt() return (left <= x < right) and (bottom <...
Return True if the given point is contained within the bounding box, where the bottom and right boundaries are considered exclusive.
def cache(self, name, cache_class=Cache, identity_generator_class=IdentityGenerator, compressor_class=Compressor, serializer_class=Serializer, *args, **kwargs): """ Return a cache object using default identity generator, serializer and compressor. ...
Return a cache object using default identity generator, serializer and compressor. ``name`` is used to identify the series of your cache ``cache_class`` Cache is for normal use and HerdCache is used in case of Thundering Herd Problem ``identity_generator_class`` is the class use...
def append(self, item): """ Try to add an item to this element. If the item is of the wrong type, and if this element has a sub-type, then try to create such a sub-type and insert the item into that, instead. This happens recursively, so (in python-markup): L ...
Try to add an item to this element. If the item is of the wrong type, and if this element has a sub-type, then try to create such a sub-type and insert the item into that, instead. This happens recursively, so (in python-markup): L [ u'Foo' ] actually creates: ...
def get_version_info(self, key_name='ver_sw_release'): """ get the (major, minor, patch, type) version information as tuple. Returns None if not found definition of type is: >= 0: development >= 64: alpha version >= 128: beta version >= 192: RC version...
get the (major, minor, patch, type) version information as tuple. Returns None if not found definition of type is: >= 0: development >= 64: alpha version >= 128: beta version >= 192: RC version == 255: release version
def extract_named_entities(text_blocks): """ Return a list of named entities extracted from provided text blocks (list of text strings). """ sentences = [] for text in text_blocks: sentences.extend(nltk.sent_tokenize(text)) tokenized_sentences = [nltk.word_tokenize(sentence) for sentenc...
Return a list of named entities extracted from provided text blocks (list of text strings).
def _from_dict(cls, _dict): """Initialize a VoiceModel object from a json dictionary.""" args = {} if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: raise ValueError( 'Required property \'customization_i...
Initialize a VoiceModel object from a json dictionary.
def has_rotational(self): """Return true if any of the drive is HDD""" for member in self._drives_list(): if member.media_type == constants.MEDIA_TYPE_HDD: return True return False
Return true if any of the drive is HDD
def get(self, key, default=None): """ Retrieve the given configuration option. Configuration options that can be queried this way are those that are specified without prefix in the paste.ini file, or which are specified in the '[turnstile]' section of the configuration f...
Retrieve the given configuration option. Configuration options that can be queried this way are those that are specified without prefix in the paste.ini file, or which are specified in the '[turnstile]' section of the configuration file. Returns the default value (None if not specified...
def write_sub_file(self): """ Write a submit file for this Condor job. """ if not self.__log_file: raise CondorSubmitError, "Log file not specified." if not self.__err_file: raise CondorSubmitError, "Error file not specified." if not self.__out_file: raise CondorSubmitError, "O...
Write a submit file for this Condor job.
def save_json(obj, outfile, allow_nan=True, compression=False): """Save an ssbio object as a JSON file using json_tricks""" if compression: with open(outfile, 'wb') as f: dump(obj, f, allow_nan=allow_nan, compression=compression) else: with open(outfile, 'w') as f: du...
Save an ssbio object as a JSON file using json_tricks
def server_enabled(s_name, **connection_args): ''' Check if a server is enabled globally CLI Example: .. code-block:: bash salt '*' netscaler.server_enabled 'serverName' ''' server = _server_get(s_name, **connection_args) return server is not None and server.get_state() == 'ENABLE...
Check if a server is enabled globally CLI Example: .. code-block:: bash salt '*' netscaler.server_enabled 'serverName'
def is_natural(x): """A non-negative integer.""" try: is_integer = int(x) == x except (TypeError, ValueError): return False return is_integer and x >= 0
A non-negative integer.
def set_fd_value(tag, value): """ Setters for data that also work with implicit transfersyntax :param value: the value to set on the tag :param tag: the tag to read """ if tag.VR == 'OB' or tag.VR == 'UN': value = struct.pack('d', value) tag.value = value
Setters for data that also work with implicit transfersyntax :param value: the value to set on the tag :param tag: the tag to read
def set_bn_eval(m:nn.Module)->None: "Set bn layers in eval mode for all recursive children of `m`." for l in m.children(): if isinstance(l, bn_types) and not next(l.parameters()).requires_grad: l.eval() set_bn_eval(l)
Set bn layers in eval mode for all recursive children of `m`.
def has_file_url(self): """stub""" return bool(self._get_asset_content( Id(self.my_osid_object._my_map['fileId']['assetId']), self.my_osid_object._my_map['fileId']['assetContentTypeId']).has_url())
stub
def _render(self, contexts, partials): """render variable""" value = self._lookup(self.value, contexts) # lambda if callable(value): value = inner_render(str(value()), contexts, partials) return self._escape(value)
render variable
def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resn...
Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resnet_size: The number of convolutional lay...
def update_fallbackserver(self, serverid, data): """Update Fallback server""" return self.api_call( ENDPOINTS['fallbackservers']['update'], dict(serverid=serverid), body=data)
Update Fallback server
def changeLocalUserPassword(self, login, user, password): """ Parameters: - login - user - password """ self.send_changeLocalUserPassword(login, user, password) self.recv_changeLocalUserPassword()
Parameters: - login - user - password
def exceptions(error_is_fatal=True, error_messages=None): """ Handle SQLAlchemy exceptions in a sane way. Args: func: An arbitrary function to wrap. error_is_fatal: Should we exit the program on exception? reraise: Should we reraise the exception, after logging? Only makes sense ...
Handle SQLAlchemy exceptions in a sane way. Args: func: An arbitrary function to wrap. error_is_fatal: Should we exit the program on exception? reraise: Should we reraise the exception, after logging? Only makes sense if error_is_fatal is False. error_messages: A diction...
def select_nodes_by_attribute(docgraph, attribute=None, value=None, data=False): """ Get all nodes with the given attribute (and attribute value). Parameters ---------- docgraph : DiscourseDocumentGraph document graph from which the nodes will be extracted attribute : str or None ...
Get all nodes with the given attribute (and attribute value). Parameters ---------- docgraph : DiscourseDocumentGraph document graph from which the nodes will be extracted attribute : str or None Name of the node attribute that all nodes must posess. If None, returns all nodes. ...
def get_deposit_address(self, currency): """Get deposit address for a currency https://docs.kucoin.com/#get-deposit-address :param currency: Name of currency :type currency: string .. code:: python address = client.get_deposit_address('NEO') :returns: Api...
Get deposit address for a currency https://docs.kucoin.com/#get-deposit-address :param currency: Name of currency :type currency: string .. code:: python address = client.get_deposit_address('NEO') :returns: ApiResponse .. code:: python { ...
def get_version_fields(self): """ Get field that are tracked in object history versions. """ options = reversion._get_options(self) return options.fields or [f.name for f in self._meta.fields if f not in options.exclude]
Get field that are tracked in object history versions.
def corrdfs(df1,df2,method): """ df1 in columns df2 in rows """ dcorr=pd.DataFrame(columns=df1.columns,index=df2.columns) dpval=pd.DataFrame(columns=df1.columns,index=df2.columns) for c1 in df1: for c2 in df2: if method=='spearman': dcorr.loc[c2,c1],dp...
df1 in columns df2 in rows
def create_token(self, *, holder_name, card_number, credit_card_cvv, expiration_date, token_type='credit_card', identity_document=None, billing_address=None, additional_details=None): """ When creating a Token, remember to use the public-key header instead of the private-key header,...
When creating a Token, remember to use the public-key header instead of the private-key header, and do not include the app-id header. Args: holder_name: Name of the credit card holder. card_number: Credit card number. credit_card_cvv: The CVV number on the card (3 or...
def base_query(cls, db_session=None): """ returns base query for specific service :param db_session: :return: query """ db_session = get_db_session(db_session) return db_session.query(cls.model)
returns base query for specific service :param db_session: :return: query
def mbar_gradient(u_kn, N_k, f_k): """Gradient of MBAR objective function. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The num...
Gradient of MBAR objective function. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of samples in each state f_k : np....
def large_size(self, as_string=True): """Returns a thumbnail's large size.""" size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150)) if as_string: return u'{}x{}'.format(size[0], size[1]) return size
Returns a thumbnail's large size.
def get_color_cycle(n, cmap="rainbow", rotations=3): """Get a list of RGBA colors following a colormap. Useful for plotting lots of elements, keeping the color of each unique. Parameters ---------- n : integer The number of colors to return. cmap : string (optional) The colorma...
Get a list of RGBA colors following a colormap. Useful for plotting lots of elements, keeping the color of each unique. Parameters ---------- n : integer The number of colors to return. cmap : string (optional) The colormap to use in the cycle. Default is rainbow. rotations : i...
def check_status_code(response, codes=None): """ Checks response.status_code is in codes. :param requests.request response: Requests response :param list codes: List of accepted codes or callable :raises: StatusCodeError if code invalid """ codes = codes or [200] if response.status_code...
Checks response.status_code is in codes. :param requests.request response: Requests response :param list codes: List of accepted codes or callable :raises: StatusCodeError if code invalid
def eval_js(self, expr): """Evaluate a Javascript expression.""" if not self.is_built(): self._pending_js_eval.append(expr) return logger.log(5, "Evaluate Javascript: `%s`.", expr) out = self.page().mainFrame().evaluateJavaScript(expr) return _to_py(out)
Evaluate a Javascript expression.
def _resolve_objects(self, new_objects, superclass_objects, new_class, superclass, classrepo, qualifier_repo, type_str, verbose=None): """ Resolve a dictionary of objects where the objects can be CIMProperty, CIMMethod, or CIMParameter. This met...
Resolve a dictionary of objects where the objects can be CIMProperty, CIMMethod, or CIMParameter. This method resolves each of the objects in the dictionary, using the superclass if it is defined.
def groups(self): """Method returns a list of all goup paths Examples -------- >>> for group in h5f.groups(): print(group) '/' '/dataset1' '/dataset1/data1' '/dataset1/data2' """ HiisiHDF._clear_cach...
Method returns a list of all goup paths Examples -------- >>> for group in h5f.groups(): print(group) '/' '/dataset1' '/dataset1/data1' '/dataset1/data2'
async def home_plunger(self, mount: top_types.Mount): """ Home the plunger motor for a mount, and then return it to the 'bottom' position. :param mount: the mount associated with the target plunger :type mount: :py:class:`.top_types.Mount` """ instr = self._attac...
Home the plunger motor for a mount, and then return it to the 'bottom' position. :param mount: the mount associated with the target plunger :type mount: :py:class:`.top_types.Mount`
def get_leads_lists(self, offset=None, limit=None): """ Gives back all the leads lists saved on your account. :param offset: Number of lists to skip. :param limit: Maximum number of lists to return. :return: Leads lists found as a dict. """ params = self.base_p...
Gives back all the leads lists saved on your account. :param offset: Number of lists to skip. :param limit: Maximum number of lists to return. :return: Leads lists found as a dict.
def export(group, bucket, prefix, start, end, role, poll_period=120, session=None, name="", region=None): """export a given log group to s3""" start = start and isinstance(start, six.string_types) and parse(start) or start end = (end and isinstance(start, six.string_types) and parse(en...
export a given log group to s3
def load(self, df, centerings): """ A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures. Parameters ---------- proj : geoplot.crs object instance A disguised reference to ``self``. df : GeoDataFrame ...
A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures. Parameters ---------- proj : geoplot.crs object instance A disguised reference to ``self``. df : GeoDataFrame The GeoDataFrame which has been passed as i...
def delay_1(year): '''Test for delay of start of new year and to avoid''' # Sunday, Wednesday, and Friday as start of the new year. months = trunc(((235 * year) - 234) / 19) parts = 12084 + (13753 * months) day = trunc((months * 29) + parts / 25920) if ((3 * (day + 1)) % 7) < 3: day += ...
Test for delay of start of new year and to avoid
def usages_list(location, **kwargs): ''' .. versionadded:: 2019.2.0 List subscription network usage for a location. :param location: The Azure location to query for network usage. CLI Example: .. code-block:: bash salt-call azurearm_network.usages_list westus ''' netconn = ...
.. versionadded:: 2019.2.0 List subscription network usage for a location. :param location: The Azure location to query for network usage. CLI Example: .. code-block:: bash salt-call azurearm_network.usages_list westus
def parse_content(self, content): """ Use all the defined scanners to search the log file, setting the properties defined in the scanner. """ self.lines = content for scanner in self.scanners: scanner(self)
Use all the defined scanners to search the log file, setting the properties defined in the scanner.
def _do_for(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name): """ Implements @for """ var, _, name = name.partition('from') frm, _, through = name.partition('through') if not through: frm, _, through = ...
Implements @for
def get_serial_number(device): """Decode (if needed) and return the ICS device serial string :param device: ics device :return: ics device serial string :rtype: str """ a0000 = 604661760 if device.SerialNumber >= a0000: return ics.base36enc(device.Ser...
Decode (if needed) and return the ICS device serial string :param device: ics device :return: ics device serial string :rtype: str
def add(self, intervention, id=None): """ Add an intervention to intervention/human section. intervention is either ElementTree or xml snippet """ if self.et is None: return assert isinstance(intervention, six.string_types) et = ElementTree.fromstring...
Add an intervention to intervention/human section. intervention is either ElementTree or xml snippet
def clear(self): """ Remove all content from this paragraph. Paragraph properties are preserved. Content includes runs, line breaks, and fields. """ for elm in self._element.content_children: self._element.remove(elm) return self
Remove all content from this paragraph. Paragraph properties are preserved. Content includes runs, line breaks, and fields.
def chat(self): """ Access the Chat Twilio Domain :returns: Chat Twilio Domain :rtype: twilio.rest.chat.Chat """ if self._chat is None: from twilio.rest.chat import Chat self._chat = Chat(self) return self._chat
Access the Chat Twilio Domain :returns: Chat Twilio Domain :rtype: twilio.rest.chat.Chat
def one_to_max(array_in): """Alter a vector of cluster labels to a dense mapping. Given that this function is herein always called after passing a vector to the function checkcl, one_to_max relies on the assumption that cluster_run does not contain any NaN entries. Parameters ---...
Alter a vector of cluster labels to a dense mapping. Given that this function is herein always called after passing a vector to the function checkcl, one_to_max relies on the assumption that cluster_run does not contain any NaN entries. Parameters ---------- array_in : a list or ...
def activate(self, title, switchDesktop=False, matchClass=False): """ Activate the specified window, giving it input focus Usage: C{window.activate(title, switchDesktop=False, matchClass=False)} If switchDesktop is False (default), the window will be moved to the current deskto...
Activate the specified window, giving it input focus Usage: C{window.activate(title, switchDesktop=False, matchClass=False)} If switchDesktop is False (default), the window will be moved to the current desktop and activated. Otherwise, switch to the window's current desktop and activat...
def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if is...
:param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix.
def getch(): """Request a single character input from the user.""" if sys.platform in ['darwin', 'linux']: import termios import tty file_descriptor = sys.stdin.fileno() settings = termios.tcgetattr(file_descriptor) try: tty.setraw(file_descriptor) ...
Request a single character input from the user.
def check(text): """Check the text.""" err = "misc.currency" msg = u"Incorrect use of symbols in {}." symbols = [ "\$[\d]* ?(?:dollars|usd|us dollars)" ] return existence_check(text, symbols, err, msg)
Check the text.
def to_csv(self, filename=None, *, fields=None, append=False, header=True, header_prefix='', sep=',', newline='\n'): """ Parameters ---------- filename: str or None The file to which output will be written. By default, any existing content is overwritten. Use `app...
Parameters ---------- filename: str or None The file to which output will be written. By default, any existing content is overwritten. Use `append=True` to open the file in append mode instead. If filename is None, the generated CSV output is returned instead of writt...
def incrby(self, name, amount=1): """ increment the value for key by value: int :param name: str the name of the redis key :param amount: int :return: Future() """ with self.pipe as pipe: return pipe.incrby(self.redis_key(name), amount=amount)
increment the value for key by value: int :param name: str the name of the redis key :param amount: int :return: Future()
def compare(self, range_comparison, range_objs): """ Compares this type against comparison filters """ range_values = [obj.value for obj in range_objs] comparison_func = get_comparison_func(range_comparison) return comparison_func(self.value, *range_values)
Compares this type against comparison filters
def show(self): """ Print with a pretty display the MapList object """ bytecode._Print("MAP_LIST SIZE", self.size) for i in self.map_item: if i.item != self: # FIXME this does not work for CodeItems! # as we do not have the method analy...
Print with a pretty display the MapList object
def disconnect_node(node, target_obj_result, graph, debug): """ Disconnects `node` from `target_obj` Args ---- node: LVLoadAreaCentreDing0, i.e. Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0) target_obj_result: LVLoadAreaCentreDing0, i.e. Origin node - Ding0 graph obj...
Disconnects `node` from `target_obj` Args ---- node: LVLoadAreaCentreDing0, i.e. Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0) target_obj_result: LVLoadAreaCentreDing0, i.e. Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0) graph: :networkx:`NetworkX Grap...
def delta(feat, N): """Compute delta features from a feature vector sequence. :param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector. :param N: For each frame, calculate delta features based on preceding and following N frames :returns:...
Compute delta features from a feature vector sequence. :param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector. :param N: For each frame, calculate delta features based on preceding and following N frames :returns: A numpy array of size (NUM...
def subkeys(self, path): """ A generalized form that can return multiple subkeys. """ for _ in subpaths_for_path_range(path, hardening_chars="'pH"): yield self.subkey_for_path(_)
A generalized form that can return multiple subkeys.
def render_pictures(context, selection='recent', amount=3): """Template tag to render a list of pictures.""" pictures = Image.objects.filter( folder__id__in=Gallery.objects.filter(is_published=True).values_list( 'folder__pk', flat=True)) if selection == 'recent': context.update({...
Template tag to render a list of pictures.
def __nt_relpath(path, start=os.curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = os.path.abspath(start).split(os.sep) path_list = os.path.abspath(path).split(os.sep) if start_list[0].lower() != path_list[0].lower(): unc_path...
Return a relative version of a path
def convert(self, type_from, type_to, data): """Parsers data from with one format and composes with another. :param type_from: The unique name of the format to parse with :param type_to: The unique name of the format to compose with :param data: The text to convert """ t...
Parsers data from with one format and composes with another. :param type_from: The unique name of the format to parse with :param type_to: The unique name of the format to compose with :param data: The text to convert
def to_match(self): """Return a unicode object with the MATCH representation of this BinaryComposition.""" self.validate() # The MATCH versions of some operators require an inverted order of arguments. # pylint: disable=unused-variable regular_operator_format = '(%(left)s %(oper...
Return a unicode object with the MATCH representation of this BinaryComposition.
def parser(subparsers): "Build an argparse argument parser to parse the command line." # create the parser for the version subcommand. parser_version = subparsers.add_parser( 'version', help="Output the version of %(prog)s to the console.") parser_version.set_defaults(func=command_versi...
Build an argparse argument parser to parse the command line.
def addNamespace(self, namespace, **context): """ Creates a new namespace within this database. :param namespace: <str> """ self.connection().addNamespace(namespace, orb.Context(**context))
Creates a new namespace within this database. :param namespace: <str>
def _render_op( self, identifier, hs=None, dagger=False, args=None, superop=False): """Render an operator Args: identifier (str or SymbolicLabelBase): The identifier (name/symbol) of the operator. May include a subscript, denoted by '_'. hs (qnet.alge...
Render an operator Args: identifier (str or SymbolicLabelBase): The identifier (name/symbol) of the operator. May include a subscript, denoted by '_'. hs (qnet.algebra.hilbert_space_algebra.HilbertSpace): The Hilbert space in which the operator is defined...