code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def full_name(first_name, last_name, username, **extra): """Return full name or username.""" name = " ".join(n for n in [first_name, last_name] if n) if not name: return username return name
Return full name or username.
def _are_scopes_sufficient(authorized_scopes, sufficient_scopes): """Check if a list of authorized scopes satisfies any set of sufficient scopes. Args: authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes sufficient_scopes: a set of sets of strings, return value from...
Check if a list of authorized scopes satisfies any set of sufficient scopes. Args: authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes sufficient_scopes: a set of sets of strings, return value from _process_scopes
def targeted_conjugate_about(tensor: np.ndarray, target: np.ndarray, indices: Sequence[int], conj_indices: Sequence[int] = None, buffer: Optional[np.ndarray] = None, out: Opti...
r"""Conjugates the given tensor about the target tensor. This method computes a target tensor conjugated by another tensor. Here conjugate is used in the sense of conjugating by a matrix, i.a. A conjugated about B is $A B A^\dagger$ where $\dagger$ represents the conjugate transpose. Abstractly th...
def extract_author_keywords(skw_db, ckw_db, fulltext): """Find out human defined keywords in a text string. Searches for the string "Keywords:" and its declinations and matches the following words. :param skw_db: list single kw object :param ckw_db: list of composite kw objects :param fulltext...
Find out human defined keywords in a text string. Searches for the string "Keywords:" and its declinations and matches the following words. :param skw_db: list single kw object :param ckw_db: list of composite kw objects :param fulltext: utf-8 string :return: dictionary of matches in a formt {...
def recommend_from_interactions( self, observed_items, k=10, exclude=None, items=None, new_user_data=None, new_item_data=None, exclude_known=True, diversity=0, random_seed=None, verbose=True): """ Recommend the ``k`` highest scored items based on the ...
Recommend the ``k`` highest scored items based on the interactions given in `observed_items.` Parameters ---------- observed_items : SArray, SFrame, or list A list/SArray of items to use to make recommendations, or an SFrame of items and optionally ratings and/or...
def boolean(self): """A mapping of this `StateVector` to a 2-D array containing all binary bits as booleans, for each time point. """ try: return self._boolean except AttributeError: nbits = len(self.bits) boolean = numpy.zeros((self.size, nbit...
A mapping of this `StateVector` to a 2-D array containing all binary bits as booleans, for each time point.
def get(cls, rkey): """Get image previously registered with key rkey. If key not exist, raise StockImageException """ if rkey in cls._cached: logger.info('Resource %s is in cache.' % rkey) return cls._cached[rkey] if rkey in cls._stock: img = ...
Get image previously registered with key rkey. If key not exist, raise StockImageException
def limit(self, keys): ''' Remove all keys other than the keys specified. ''' if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in remove_keys: self.pop(k)
Remove all keys other than the keys specified.
def extractUserStore(userAccount, extractionDestination, legacySiteAuthoritative=True): """ Move the SubStore for the given user account out of the given site store completely. Place the user store's database directory into the given destination directory. @type userAccount: C{LoginAccount} @t...
Move the SubStore for the given user account out of the given site store completely. Place the user store's database directory into the given destination directory. @type userAccount: C{LoginAccount} @type extractionDestination: C{FilePath} @type legacySiteAuthoritative: C{bool} @param legac...
def thickness_hydrostatic_from_relative_humidity(pressure, temperature, relative_humidity, **kwargs): r"""Calculate the thickness of a layer given pressure, temperature and relative humidity. Similar to ``thickness_hydrostatic``, this thickness calculation uses ...
r"""Calculate the thickness of a layer given pressure, temperature and relative humidity. Similar to ``thickness_hydrostatic``, this thickness calculation uses the pressure, temperature, and relative humidity profiles via the hypsometric equation with virtual temperature adjustment. .. math:: Z_2 - Z_...
def tamper_file(filepath, mode='e', proba=0.03, block_proba=None, blocksize=65535, burst_length=None, header=None): """ Randomly tamper a file's content """ if header and header > 0: blocksize = header tamper_count = 0 # total number of characters tampered in the file total_size = 0 # total buf...
Randomly tamper a file's content
def _permission_trees(permissions): """Get the cached permission tree, or build a new one if necessary.""" treecache = PermissionTreeCache() cached = treecache.get() if not cached: tree = PermissionTreeBuilder() for permission in permissions: tree....
Get the cached permission tree, or build a new one if necessary.
def parse_response(self, response): """ Parse XMLRPC response """ parser, unmarshaller = self.getparser() parser.feed(response.text.encode('utf-8')) parser.close() return unmarshaller.close()
Parse XMLRPC response
def update(self, state, tnow): '''update the threat state''' self.state = state self.update_time = tnow
update the threat state
def get_maxsing(self,eigthresh=1.0e-5): """ Get the number of singular components with a singular value ratio greater than or equal to eigthresh Parameters ---------- eigthresh : float the ratio of the largest to smallest singular value Returns -----...
Get the number of singular components with a singular value ratio greater than or equal to eigthresh Parameters ---------- eigthresh : float the ratio of the largest to smallest singular value Returns ------- int : int number of singular ...
def _check_params(self, *args, **kwargs): """ 检查参数信息是否匹配 """ terms = kwargs.get('terms') if not terms: raise crawler.CrawlerParamsError('Terms needed!') if not isinstance(terms, list): terms = [terms] if len(terms) != len(self.base['terms']): ...
检查参数信息是否匹配
def map_template(category, template_list): """ Given a file path and an acceptable list of templates, return the best-matching template's path relative to the configured template directory. Arguments: category -- The path to map template_list -- A template to look up (as a string), or a li...
Given a file path and an acceptable list of templates, return the best-matching template's path relative to the configured template directory. Arguments: category -- The path to map template_list -- A template to look up (as a string), or a list of templates.
def update(self, key, value): """ :param key: a string :value: a string """ if not is_string(key): raise Exception("Key must be string") # if len(key) > 32: # raise Exception("Max key length is 32") if not is_string(value): ra...
:param key: a string :value: a string
def build_search(self): """ Construct the ``Search`` object. """ s = self.search() s = self.query(s, self._query) s = self.filter(s) if self.fields: s = self.highlight(s) s = self.sort(s) self.aggregate(s) return s
Construct the ``Search`` object.
def _map_xpath_flags_to_re(expr: str, xpath_flags: str) -> Tuple[int, str]: """ Map `5.6.2 Flags <https://www.w3.org/TR/xpath-functions-31/#flags>`_ to python :param expr: match pattern :param xpath_flags: xpath flags :returns: python flags / modified match pattern """ python_flags: int = 0 ...
Map `5.6.2 Flags <https://www.w3.org/TR/xpath-functions-31/#flags>`_ to python :param expr: match pattern :param xpath_flags: xpath flags :returns: python flags / modified match pattern
def request(self, source, target): """Create or replace an entire configuration datastore with the contents of another complete configuration datastore. *source* is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuratio...
Create or replace an entire configuration datastore with the contents of another complete configuration datastore. *source* is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuration subtree to copy *target* is the nam...
def getAllNodes(self): ''' getAllNodes - Get every element @return TagCollection<AdvancedTag> ''' ret = TagCollection() for rootNode in self.getRootNodes(): ret.append(rootNode) ret += rootNode.getAllChildNodes() return ret
getAllNodes - Get every element @return TagCollection<AdvancedTag>
def copy_subtree(ret, element, msg): '''copy_subtree High-level api: Copy element as a subtree and put it as a child of ret. Parameters ---------- element : `Element` A node in a model tree. msg : `str` Message to be added. ret : `Elem...
copy_subtree High-level api: Copy element as a subtree and put it as a child of ret. Parameters ---------- element : `Element` A node in a model tree. msg : `str` Message to be added. ret : `Element` A node in self.tree. R...
def error(self): """**DEPRECATED**: Get the error if one occurred on the last operation. This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern ``w=1`` and report their errors by default. .. versionchanged:: 2.8 ...
**DEPRECATED**: Get the error if one occurred on the last operation. This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern ``w=1`` and report their errors by default. .. versionchanged:: 2.8 Deprecated.
def install(self, release_id, upgrade=False): """Install target packages into a virtual environment. If the virtual environment for the given release ID does not exist on the remote system, it will be created. The virtual environment will be created according to the standard Tunic ...
Install target packages into a virtual environment. If the virtual environment for the given release ID does not exist on the remote system, it will be created. The virtual environment will be created according to the standard Tunic directory structure (see :doc:`design`). If `...
def load_obsdata(self, idx: int) -> None: """Load the next obs sequence value (of the given index).""" if self._obs_ramflag: self.obs[0] = self._obs_array[idx] elif self._obs_diskflag: raw = self._obs_file.read(8) self.obs[0] = struct.unpack('d', raw)
Load the next obs sequence value (of the given index).
def unwrap_aliases(data_type): """ Convenience method to unwrap all Alias(es) from around a DataType. Args: data_type (DataType): The target to unwrap. Return: Tuple[DataType, bool]: The underlying data type and a bool indicating whether the input type had at least one alia...
Convenience method to unwrap all Alias(es) from around a DataType. Args: data_type (DataType): The target to unwrap. Return: Tuple[DataType, bool]: The underlying data type and a bool indicating whether the input type had at least one alias layer.
def find_closing_braces(self, query): """Find the index of the closing braces for the opening braces at the start of the query string. Note that first character of input string must be an opening braces.""" if query[0] != '(': raise Exception("Trying to find closing braces for no opening braces") ...
Find the index of the closing braces for the opening braces at the start of the query string. Note that first character of input string must be an opening braces.
def p_unitary_op_3(self, program): """ unitary_op : id '(' ')' primary_list """ program[0] = node.CustomUnitary([program[1], program[4]]) self.verify_as_gate(program[1], program[4]) self.verify_reg_list(program[4], 'qreg') self.verify_distinct([program[4]])
unitary_op : id '(' ')' primary_list
def get_default_org(self): """ retrieve the name and configuration of the default org """ for org in self.list_orgs(): org_config = self.get_org(org) if org_config.default: return org, org_config return None, None
retrieve the name and configuration of the default org
def describe_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, p...
Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key
def get_all_compiler_versions(): """Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first. """ versions=[] if is_windows: if is_win64: keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++' else: keyname = 'Soft...
Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first.
def create_window(self): """Create a QMainWindow instance containing this plugin.""" self.undocked_window = window = PluginWindow(self) window.setAttribute(Qt.WA_DeleteOnClose) icon = self.get_plugin_icon() if is_text_string(icon): icon = self.get_icon(icon) w...
Create a QMainWindow instance containing this plugin.
def BSearchFloor(a, x, lo=0, hi=None): """Returns highest i such as a[i] <= x, or -1 if x < all elements in a So, if x is in between two elements in a, this function will return the index of the lower element, hence "Floor". Arguments: a -- ordered numeric sequence x -- element to ...
Returns highest i such as a[i] <= x, or -1 if x < all elements in a So, if x is in between two elements in a, this function will return the index of the lower element, hence "Floor". Arguments: a -- ordered numeric sequence x -- element to search within a lo -- lowest index to co...
def distance(args): """ %prog distance bedfile Calculate distance between bed features. The output file is a list of distances, which can be used to plot histogram, etc. """ from jcvi.utils.iter import pairwise p = OptionParser(distance.__doc__) p.add_option("--distmode", default="ss",...
%prog distance bedfile Calculate distance between bed features. The output file is a list of distances, which can be used to plot histogram, etc.
def addSpatialNoise(self, sequence, amount): """ Add spatial noise to each pattern in the sequence. @param sequence (list) Sequence @param amount (float) Amount of spatial noise @return (list) Sequence with spatial noise """ newSequence = [] for pattern in sequence: if patter...
Add spatial noise to each pattern in the sequence. @param sequence (list) Sequence @param amount (float) Amount of spatial noise @return (list) Sequence with spatial noise
def get_md_header(header_text_line: str, header_duplicate_counter: dict, keep_header_levels: int = 3, parser: str = 'github', no_links: bool = False) -> dict: r"""Build a data structure with the elements needed to create a TOC line. :param...
r"""Build a data structure with the elements needed to create a TOC line. :parameter header_text_line: a single markdown line that needs to be transformed into a TOC line. :parameter header_duplicate_counter: a data structure that contains the number of occurrencies of each header anchor link...
def get_fields(schema, exclude_dump_only=False): """Return fields from schema :param Schema schema: A marshmallow Schema instance or a class object :param bool exclude_dump_only: whether to filter fields in Meta.dump_only :rtype: dict, of field name field object pairs """ if hasattr(schema, "fi...
Return fields from schema :param Schema schema: A marshmallow Schema instance or a class object :param bool exclude_dump_only: whether to filter fields in Meta.dump_only :rtype: dict, of field name field object pairs
def wrap_call(self, call_cmd): """ "wraps" the call_cmd so it can be executed by subprocess.call (and related flavors) as "args" argument :param call_cmd: original args like argument (string or sequence) :return: a sequence with the original command "executed" under trickle """...
"wraps" the call_cmd so it can be executed by subprocess.call (and related flavors) as "args" argument :param call_cmd: original args like argument (string or sequence) :return: a sequence with the original command "executed" under trickle
def do_label(self): """ Create label for x and y axis, title and suptitle """ outputdict = self.outputdict xlabel_options = self.kwargs.get("xlabel_options", {}) self.subplot.set_xlabel( self.kwargs.get("xlabel", "").format(**outputdict), **xlabel_...
Create label for x and y axis, title and suptitle
def hybrid_forward(self, F, a, b): """ Forward of Decomposable Attention layer """ # a.shape = [B, L1, H] # b.shape = [B, L2, H] # extract features tilde_a = self.f(a) # shape = [B, L1, H] tilde_b = self.f(b) # shape = [B, L2, H] # attention ...
Forward of Decomposable Attention layer
def main(): '''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--name', '-n', required=True, action='store', help='Name') arg_parser.add_argument('--rgname', '-g', required=True, action='store', help='Res...
Main routine.
def process_request_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence[Extension], ) -> Tuple[List[ExtensionParameter], Extension]: """ Process request parameters received from the client. ``params`` is a list of (name, value) pairs. ...
Process request parameters received from the client. ``params`` is a list of (name, value) pairs. ``accepted_extensions`` is a list of previously accepted extensions. To accept the offer, return a 2-uple containing: - response parameters: a list of (name, value) pairs - an ex...
def fix_geometry(self, isophote): """ Fix the geometry of a problematic isophote to be identical to the input isophote. This method should be called when the fitting goes berserk and delivers an isophote with bad geometry, such as ellipticity > 1 or another meaningless s...
Fix the geometry of a problematic isophote to be identical to the input isophote. This method should be called when the fitting goes berserk and delivers an isophote with bad geometry, such as ellipticity > 1 or another meaningless situation. This is not a problem in itself when...
def main(args=None): """The main routine.""" if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser( description='Makes UCL PHAS results better') parser.add_argument('--input', '-i', type=str, help="csv file to import") parser.add_argument('--f...
The main routine.
def check_arguments(args, parser): """Check arguments passed by user that are not checked by argparse itself.""" if args.asm_block not in ['auto', 'manual']: try: args.asm_block = int(args.asm_block) except ValueError: parser.error('--asm-block can only be "auto", "manual...
Check arguments passed by user that are not checked by argparse itself.
def get_chart(self, relation=None, index=0, limit=10, **kwargs): """ Get chart :returns: a list of :class:`~deezer.resources.Resource` objects. """ return self.get_object( "chart", object_id="0", relation=relation, parent="chart", **kwargs )
Get chart :returns: a list of :class:`~deezer.resources.Resource` objects.
def density_2d(self, x, y, Rs, rho0, r_core, center_x=0, center_y=0): """ projected two dimenstional NFW profile (kappa*Sigma_crit) :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization ...
projected two dimenstional NFW profile (kappa*Sigma_crit) :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :param r200: radius of (sub)hal...
def merged(self, other): """Returns a new ParseNode whose type is this node's type, and whose children are all the children from this node and the other whose length is not 0. """ children = [c for c in itertools.chain(self.children, other.children) if len(c) > 0] # NOTE: Only terminals should have ...
Returns a new ParseNode whose type is this node's type, and whose children are all the children from this node and the other whose length is not 0.
def last_bed_temp(self): """Return avg bed temperature for last session.""" try: bedtemps = self.intervals[1]['timeseries']['tempBedC'] except KeyError: return None tmp = 0 num_temps = len(bedtemps) if num_temps == 0: return None ...
Return avg bed temperature for last session.
def toggle_plain_text(self, checked): """Toggle plain text docstring""" if checked: self.docstring = checked self.switch_to_plain_text() self.force_refresh() self.set_option('rich_mode', not checked)
Toggle plain text docstring
def _outputMessages(self, warnings, node): """ Map pycodestyle results to messages in pylint, then output them. @param warnings: it should be a list of tuple including line number and message id """ if not warnings: # No warnings were found return...
Map pycodestyle results to messages in pylint, then output them. @param warnings: it should be a list of tuple including line number and message id
def init_states(batch_size, num_lstm_layer, num_hidden): """ Returns name and shape of init states of LSTM network Parameters ---------- batch_size: list of tuple of str and tuple of int and int num_lstm_layer: int num_hidden: int Returns ------- list of tuple of str and tuple ...
Returns name and shape of init states of LSTM network Parameters ---------- batch_size: list of tuple of str and tuple of int and int num_lstm_layer: int num_hidden: int Returns ------- list of tuple of str and tuple of int and int
def authenticate_external(self, auth_params): """Verify credentials using the external auth library. in auth_params of type str The auth parameters, credentials, etc. out result of type str The authentification result. """ if not isinstance(auth_params,...
Verify credentials using the external auth library. in auth_params of type str The auth parameters, credentials, etc. out result of type str The authentification result.
def download(ctx): """Download code of the current project.""" user, project_name = get_project_or_local(ctx.obj.get('project')) try: PolyaxonClient().project.download_repo(user, project_name) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.prin...
Download code of the current project.
def ProcessHuntFlowLog(flow_obj, log_msg): """Processes log message from a given hunt-induced flow.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): return hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt_id) flow_urn = hunt_urn.Add(flow_obj.flow_id) log_entry = rdf_flows.FlowLog( ...
Processes log message from a given hunt-induced flow.
def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None): """Extends a given object for API Production.""" # Cast all int_keys to int() if int_keys: for in_key in int_keys: if (in_key in in_dict) and (in_dict.get(in_key, None) is not None): in_dict[in_key] = in...
Extends a given object for API Production.
def organizations(self, organization, include=None): """ Retrieve the tickets for this organization. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param organization: Organization obje...
Retrieve the tickets for this organization. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param organization: Organization object or id
def derive_fields(self): """ Derives our fields. We first default to using our 'fields' variable if available, otherwise we figure it out from our object. """ if self.fields: return list(self.fields) else: fields = [] for field in sel...
Derives our fields. We first default to using our 'fields' variable if available, otherwise we figure it out from our object.
def _batched_op_msg_compressed( operation, command, docs, check_keys, ack, opts, ctx): """Create the next batched insert, update, or delete operation with OP_MSG, compressed. """ data, to_send = _encode_batched_op_msg( operation, command, docs, check_keys, ack, opts, ctx) request_id...
Create the next batched insert, update, or delete operation with OP_MSG, compressed.
def diff_texts(left, right, diff_options=None, formatter=None): """Takes two Unicode strings containing XML""" return _diff(etree.fromstring, left, right, diff_options=diff_options, formatter=formatter)
Takes two Unicode strings containing XML
def copy(self, copyPrimaryKey=False, copyValues=False): ''' copy - Copies this object. @param copyPrimaryKey <bool> default False - If True, any changes to the copy will save over-top the existing entry in Redis. If False, only the data is copied, and n...
copy - Copies this object. @param copyPrimaryKey <bool> default False - If True, any changes to the copy will save over-top the existing entry in Redis. If False, only the data is copied, and nothing is saved. @param copyValues <bool> default False - If True, every fi...
def getLibs(self, explicit_only=False): ''' Return a dictionary of libraries to compile: {"dirname":"libname"}, this is used when automatically generating CMakeLists. If explicit_only is not set, then in the absence of both 'lib' and 'bin' sections in the module.json file, t...
Return a dictionary of libraries to compile: {"dirname":"libname"}, this is used when automatically generating CMakeLists. If explicit_only is not set, then in the absence of both 'lib' and 'bin' sections in the module.json file, the "source" directory will be returned. ...
def object_from_json(self, object_type, object_json, parent=None): """ Given a blob of JSON representing a Zenpy object, recursively deserialize it and any nested objects it contains. This method also adds the deserialized object to the relevant cache if applicable. """ ...
Given a blob of JSON representing a Zenpy object, recursively deserialize it and any nested objects it contains. This method also adds the deserialized object to the relevant cache if applicable.
def add_hydrogen(self, num): """Adds hydrogens Args: num (int): number of hydrogens """ self.H_count = num if num > 0 and self.symbol in ("N", "O"): self.H_donor = 1 else: self.H_donor = 0
Adds hydrogens Args: num (int): number of hydrogens
def at(self, root): """Set root where PyJsonq start to prepare :@param root :@type root: string :@return self :@throws KeyError """ leafs = root.strip(" ").split('.') for leaf in leafs: if leaf: self._json_data = self.__get_va...
Set root where PyJsonq start to prepare :@param root :@type root: string :@return self :@throws KeyError
def allow_cors(func): """This is a decorator which enable CORS for the specified endpoint.""" def wrapper(*args, **kwargs): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = \ 'PUT, GET, POST, DELETE, OPTIONS' response.he...
This is a decorator which enable CORS for the specified endpoint.
def set_daily(self, interval, **kwargs): """ Set to repeat every x no. of days :param int interval: no. of days to repeat at :keyword date start: Start date of repetition (kwargs) :keyword date end: End date of repetition (kwargs) :keyword int occurrences: no of occurrences (kwa...
Set to repeat every x no. of days :param int interval: no. of days to repeat at :keyword date start: Start date of repetition (kwargs) :keyword date end: End date of repetition (kwargs) :keyword int occurrences: no of occurrences (kwargs)
def copy_current_websocket_context(func: Callable) -> Callable: """Share the current websocket context with the function decorated. The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: p...
Share the current websocket context with the function decorated. The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_websocket_context async def within...
def bgsave(host=None, port=None, db=None, password=None): ''' Asynchronously save the dataset to disk CLI Example: .. code-block:: bash salt '*' redis.bgsave ''' server = _connect(host, port, db, password) return server.bgsave()
Asynchronously save the dataset to disk CLI Example: .. code-block:: bash salt '*' redis.bgsave
def live_processes(self): """Return a list of the live processes. Returns: A list of the live processes. """ result = [] for process_type, process_infos in self.all_processes.items(): for process_info in process_infos: if process_info.proc...
Return a list of the live processes. Returns: A list of the live processes.
def basename(path, extension_marker="."): """ :param str|None path: Path to consider :param str|None extension_marker: Trim file extension based on specified character :return str: Basename part of path, without extension (if 'extension_marker' provided) """ result = os.path.basename(path or "")...
:param str|None path: Path to consider :param str|None extension_marker: Trim file extension based on specified character :return str: Basename part of path, without extension (if 'extension_marker' provided)
def register_presence_callback(self, type_, from_, cb): """ Register a callback to be called when a presence stanza is received. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard...
Register a callback to be called when a presence stanza is received. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or ...
def com_google_fonts_check_metadata_valid_name_values(style, font_metadata, font_familynames, typographic_familynames): """METADATA.pb font.name field conta...
METADATA.pb font.name field contains font name in right format?
def default(self, obj): """Encode more types.""" if isinstance(obj, UUID): return obj.hex elif isinstance(obj, datetime.datetime): return obj.isoformat() return super().default(obj)
Encode more types.
def post_run(self, outline=False, dump=False, *args, **kwargs): """Any steps that need to be taken after running the action.""" hooks = self.context.config.post_build handle_hooks( "post_build", hooks, self.provider, self.context, dump,...
Any steps that need to be taken after running the action.
def list_instances_json(self, application=None, show_only_destroyed=False): """ Get list of instances in json format converted to list""" # todo: application should not be parameter here. Application should do its own list, just in sake of code reuse q_filter = {'sortBy': 'byCreation', 'descendi...
Get list of instances in json format converted to list
def list_domains(self): """Utility method to list all the domains in the jar.""" domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains
Utility method to list all the domains in the jar.
def unpack_from(self, data, offset=0): """See :func:`~bitstruct.unpack_from_dict()`. """ return {info.name: v for info, v in self.unpack_from_any(data, offset)}
See :func:`~bitstruct.unpack_from_dict()`.
def setMinimumPixmapSize(self, size): """ Sets the minimum pixmap size that will be displayed to the user for the dock widget. :param size | <int> """ self._minimumPixmapSize = size position = self.position() self._position = None ...
Sets the minimum pixmap size that will be displayed to the user for the dock widget. :param size | <int>
def parse_end_date(self, request, start_date): """ Return period in days after the start date to show event occurrences, which is one of the following in order of priority: - `end_date` GET parameter value, if given and valid. The filtering will be *inclusive* of the end date...
Return period in days after the start date to show event occurrences, which is one of the following in order of priority: - `end_date` GET parameter value, if given and valid. The filtering will be *inclusive* of the end date: until end-of-day of this date - `days_to_show` GET param...
def CreateKey(self, prikey=None): """ Create a KeyPair and store it encrypted in the database. Args: private_key (iterable_of_ints): (optional) 32 byte private key. Returns: KeyPair: a KeyPair instance. """ account = super(UserWallet, self).Creat...
Create a KeyPair and store it encrypted in the database. Args: private_key (iterable_of_ints): (optional) 32 byte private key. Returns: KeyPair: a KeyPair instance.
def read_magic_file(self, path, sort_by_this_name, sort_by_file_type=False): """ read a magic-formatted tab-delimited file. return a dictionary of dictionaries, with this format: {'Z35.5a': {'specimen_weight': '1.000e-03', 'er_citation_names': 'This study', 'specimen_volume': '', 'er_loc...
read a magic-formatted tab-delimited file. return a dictionary of dictionaries, with this format: {'Z35.5a': {'specimen_weight': '1.000e-03', 'er_citation_names': 'This study', 'specimen_volume': '', 'er_location_name': '', 'er_site_name': 'Z35.', 'er_sample_name': 'Z35.5', 'specimen_class': '', 'er_spe...
def _calc_rms(mol1, mol2, clabel1, clabel2): """ Calculate the RMSD. Args: mol1: The first molecule. OpenBabel OBMol or pymatgen Molecule object mol2: The second molecule. OpenBabel OBMol or pymatgen Molecule object clabel1: Th...
Calculate the RMSD. Args: mol1: The first molecule. OpenBabel OBMol or pymatgen Molecule object mol2: The second molecule. OpenBabel OBMol or pymatgen Molecule object clabel1: The atom indices that can reorder the first molecule to ...
async def dump_tuple(self, elem, elem_type, params=None, obj=None): """ Dumps tuple of elements to the writer. :param elem: :param elem_type: :param params: :param obj: :return: """ if len(elem) != len(elem_type.f_specs()): raise Value...
Dumps tuple of elements to the writer. :param elem: :param elem_type: :param params: :param obj: :return:
def cross_entropy_loss(logits, one_hot_labels, label_smoothing=0, weight=1.0, scope=None): """Define a Cross Entropy loss using softmax_cross_entropy_with_logits. It can scale the loss by weight factor, and smooth the labels. Args: logits: [batch_size, num_classes] logits outputs of t...
Define a Cross Entropy loss using softmax_cross_entropy_with_logits. It can scale the loss by weight factor, and smooth the labels. Args: logits: [batch_size, num_classes] logits outputs of the network . one_hot_labels: [batch_size, num_classes] target one_hot_encoded labels. label_smoothing: if great...
def getSimpleFileData(self, fileInfo, data): """Function to initialize the simple data for file info""" result = fileInfo[fileInfo.find(data + "</td>"):] result = result[:result.find("</A></td>")] result = result[result.rfind(">") + 1:] return result
Function to initialize the simple data for file info
def transform_to_matrices(transform): """ Convert an SVG transform string to an array of matrices. > transform = "rotate(-10 50 100) translate(-36 45.5) skewX(40) scale(1 0.5)" Parameters ----------- transform : str Contains trans...
Convert an SVG transform string to an array of matrices. > transform = "rotate(-10 50 100) translate(-36 45.5) skewX(40) scale(1 0.5)" Parameters ----------- transform : str Contains transformation information in SVG form Returns ...
def rpc(self, address, rpc_id): """Call an RPC and receive the result as an integer. If the RPC does not properly return a 32 bit integer, raise a warning unless it cannot be converted into an integer at all, in which case a HardwareError is thrown. Args: address (i...
Call an RPC and receive the result as an integer. If the RPC does not properly return a 32 bit integer, raise a warning unless it cannot be converted into an integer at all, in which case a HardwareError is thrown. Args: address (int): The address of the tile we want to cal...
def build(self, grad_list, get_opt_fn): """ Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the t...
Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the training op
def check_valid_temperature(var, units): r"""Check that variable is air temperature.""" check_valid(var, 'standard_name', 'air_temperature') check_valid(var, 'units', units) assert_daily(var)
r"""Check that variable is air temperature.
def VerifyStructure(self, parser_mediator, line): """Verify that this file is a Mac AppFirewall log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. line (str): line from a text file. Returns: b...
Verify that this file is a Mac AppFirewall log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. line (str): line from a text file. Returns: bool: True if the line is in the expected format, False if...
def to_text(self, filename=None, overwrite=True): ''' Write this catalog out to a text file. ''' table = self.standardized #table = hstack([self.identifiers, # self._coordinate_table(), # self.magnitudes, # sel...
Write this catalog out to a text file.
def _get_args(self, executable, *args): """compile all the executable and the arguments, combining with common arguments to create a full batch of command args""" args = list(args) args.insert(0, executable) if self.username: args.append("--username={}".format(self.us...
compile all the executable and the arguments, combining with common arguments to create a full batch of command args
def generate(self): """Returns (ts, rvs), where ts is a list of arrays of observation times (one array for each observatory), and rvs is a corresponding list of total radial velocity measurements.""" ts=self.generate_tobs() noise=self.generate_noise(ts) rvs=[] ...
Returns (ts, rvs), where ts is a list of arrays of observation times (one array for each observatory), and rvs is a corresponding list of total radial velocity measurements.
def GetServices(self,filename): """Returns a list of service objects handling this file type""" objlist=[] for sobj in self.services: if sobj.KnowsFile(filename) : objlist.append(sobj) if len(objlist)==0: return None return objlist
Returns a list of service objects handling this file type
def GetPathInfo(self, timestamp=None): """Generates a summary about the path record. Args: timestamp: A point in time from which the data should be retrieved. Returns: A `rdf_objects.PathInfo` instance. """ path_info_timestamp = self._LastEntryTimestamp(self._path_infos, timestamp) ...
Generates a summary about the path record. Args: timestamp: A point in time from which the data should be retrieved. Returns: A `rdf_objects.PathInfo` instance.
def asynloop(self, auto_connect=False, timeout=10, detached_delay=0.2): """ Non-blocking event loop consuming messages until connection is lost, or shutdown is requested. :param int timeout: number of secs for asyncore timeout :param float detached_delay: float secs to sleep w...
Non-blocking event loop consuming messages until connection is lost, or shutdown is requested. :param int timeout: number of secs for asyncore timeout :param float detached_delay: float secs to sleep when exiting asyncore loop and execution detached queue callbacks
def system_types(): ''' List the system types that are supported by the installed version of sfdisk CLI Example: .. code-block:: bash salt '*' partition.system_types ''' ret = {} for line in __salt__['cmd.run']('sfdisk -T').splitlines(): if not line: continue ...
List the system types that are supported by the installed version of sfdisk CLI Example: .. code-block:: bash salt '*' partition.system_types
def _to_numpy(Z): """Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray; also handles converting sparse input to dense.""" if Z is None: return Z elif issparse(Z): return Z.toarray() elif isinstance(Z, np.ndarray): return Z ...
Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray; also handles converting sparse input to dense.