code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def diff_ft(self, xt, yt): """First and second derivatives (wrt x_t) of log-density of Y_t|X_t=xt """ a, b = self.a, self.b ex = np.exp(a + np.matmul(b, xt)) # shape = (dy,) grad = (-np.sum(ex[:, np.newaxis] * b, axis=0) + np.sum(yt.flatten()[:, np.newaxis] * b,...
First and second derivatives (wrt x_t) of log-density of Y_t|X_t=xt
def direct_normal_radiation(self, value=9999.0): """Corresponds to IDD Field `direct_normal_radiation` Args: value (float): value for IDD Field `direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value`...
Corresponds to IDD Field `direct_normal_radiation` Args: value (float): value for IDD Field `direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the ...
def update(self, catalog=None, dependencies=None, allow_overwrite=False): ''' Convenience method to update this Di instance with the specified contents. :param catalog: ICatalog supporting class or mapping :type catalog: ICatalog or collections.Mapping :param dependencies: Mappi...
Convenience method to update this Di instance with the specified contents. :param catalog: ICatalog supporting class or mapping :type catalog: ICatalog or collections.Mapping :param dependencies: Mapping of dependencies :type dependencies: collections.Mapping :param allow_overwr...
def set_password(name, password): ''' Set the password for a named user (insecure, the password will be in the process list while the command is running) :param str name: The name of the local user, which is assumed to be in the local directory service :param str password: The plaintext pa...
Set the password for a named user (insecure, the password will be in the process list while the command is running) :param str name: The name of the local user, which is assumed to be in the local directory service :param str password: The plaintext password to set :return: True if successful...
def _skw_matches_comparator(kw0, kw1): """Compare 2 single keywords objects. First by the number of their spans (ie. how many times they were found), if it is equal it compares them by lenghts of their labels. """ def compare(a, b): return (a > b) - (a < b) list_comparison = compare(le...
Compare 2 single keywords objects. First by the number of their spans (ie. how many times they were found), if it is equal it compares them by lenghts of their labels.
def setDeclaration(self, declaration): """ Set the declaration this model will use for rendering the the headers. """ assert isinstance(declaration.proxy, ProxyAbstractItemView), \ "The model declaration must be a QtAbstractItemView subclass. " \ "Got {]...
Set the declaration this model will use for rendering the the headers.
def break_array(a, threshold=numpy.pi, other=None): """Create a array which masks jumps >= threshold. Extra points are inserted between two subsequent values whose absolute difference differs by more than threshold (default is pi). Other can be a secondary array which is also masked according to ...
Create a array which masks jumps >= threshold. Extra points are inserted between two subsequent values whose absolute difference differs by more than threshold (default is pi). Other can be a secondary array which is also masked according to *a*. Returns (*a_masked*, *other_masked*) (where *o...
def can_ignore_error(self, reqhnd=None): """Tests if the error is worth reporting. """ value = sys.exc_info()[1] try: if isinstance(value, BrokenPipeError) or \ isinstance(value, ConnectionResetError): return True except NameError: ...
Tests if the error is worth reporting.
def image_search(auth=None, **kwargs): ''' Search for images CLI Example: .. code-block:: bash salt '*' glanceng.image_search name=image1 salt '*' glanceng.image_search ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.search_images(**k...
Search for images CLI Example: .. code-block:: bash salt '*' glanceng.image_search name=image1 salt '*' glanceng.image_search
def aghmean(nums): """Return arithmetic-geometric-harmonic mean. Iterates over arithmetic, geometric, & harmonic means until they converge to a single value (rounded to 12 digits), following the method described in :cite:`Raissouli:2009`. Parameters ---------- nums : list A series ...
Return arithmetic-geometric-harmonic mean. Iterates over arithmetic, geometric, & harmonic means until they converge to a single value (rounded to 12 digits), following the method described in :cite:`Raissouli:2009`. Parameters ---------- nums : list A series of numbers Returns ...
def bulk_docs(self, docs): """ Performs multiple document inserts and/or updates through a single request. Each document must either be or extend a dict as is the case with Document and DesignDocument objects. A document must contain the ``_id`` and ``_rev`` fields if the docum...
Performs multiple document inserts and/or updates through a single request. Each document must either be or extend a dict as is the case with Document and DesignDocument objects. A document must contain the ``_id`` and ``_rev`` fields if the document is meant to be updated. :p...
def _compute_mean_on_rock(self, C, mag, rrup, F, HW): """ Compute mean value on rock (that is eq.1, page 105 with S = 0) """ f1 = self._compute_f1(C, mag, rrup) f3 = self._compute_f3(C, mag) f4 = self._compute_f4(C, mag, rrup) return f1 + F * f3 + HW * f4
Compute mean value on rock (that is eq.1, page 105 with S = 0)
def setdict(self, D): """Set dictionary array.""" self.D = np.asarray(D, dtype=self.dtype) self.DTS = self.D.T.dot(self.S) # Factorise dictionary for efficient solves self.lu, self.piv = sl.cho_factor(self.D, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
Set dictionary array.
def _read_para_notification(self, code, cbit, clen, *, desc, length, version): """Read HIP NOTIFICATION parameter. Structure of HIP NOTIFICATION parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 ...
Read HIP NOTIFICATION parameter. Structure of HIP NOTIFICATION parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
def Close(self): """ Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is not None: try: self.connection.commit() self.connection.close() self.connection = None except Exception, e: pass
Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008
def rotateTo(self, angle): """rotates the image to a given angle Parameters: | angle - the angle that you want the image rotated to. | Positive numbers are clockwise, negative numbers are counter-clockwise """ self._transmogrophy(angle, self.p...
rotates the image to a given angle Parameters: | angle - the angle that you want the image rotated to. | Positive numbers are clockwise, negative numbers are counter-clockwise
def remove_instance(self, instance): """Request to cleanly remove the given instance. If instance is external also shutdown it cleanly :param instance: instance to remove :type instance: object :return: None """ # External instances need to be close before (proce...
Request to cleanly remove the given instance. If instance is external also shutdown it cleanly :param instance: instance to remove :type instance: object :return: None
def absent(name, driver=None): ''' Ensure that a volume is absent. .. versionadded:: 2015.8.4 .. versionchanged:: 2017.7.0 This state was renamed from **docker.volume_absent** to **docker_volume.absent** name Name of the volume Usage Examples: .. code-block:: yaml ...
Ensure that a volume is absent. .. versionadded:: 2015.8.4 .. versionchanged:: 2017.7.0 This state was renamed from **docker.volume_absent** to **docker_volume.absent** name Name of the volume Usage Examples: .. code-block:: yaml volume_foo: docker_volume.absen...
def _get_stream_schema(fields): """Returns a StreamSchema protobuf message""" stream_schema = topology_pb2.StreamSchema() for field in fields: key = stream_schema.keys.add() key.key = field key.type = topology_pb2.Type.Value("OBJECT") return stream_schema
Returns a StreamSchema protobuf message
def get_arctic_version(self, symbol, as_of=None): """ Return the numerical representation of the arctic version used to write the last (or as_of) version for the given symbol. Parameters ---------- symbol : `str` symbol name for the item as_of : `str`...
Return the numerical representation of the arctic version used to write the last (or as_of) version for the given symbol. Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `datetime.datetime` Return the data as it was a...
def validateOpfJsonValue(value, opfJsonSchemaFilename): """ Validate a python object against an OPF json schema file :param value: target python object to validate (typically a dictionary) :param opfJsonSchemaFilename: (string) OPF json schema filename containing the json schema object. (e.g., opfTask...
Validate a python object against an OPF json schema file :param value: target python object to validate (typically a dictionary) :param opfJsonSchemaFilename: (string) OPF json schema filename containing the json schema object. (e.g., opfTaskControlSchema.json) :raises: jsonhelpers.ValidationError when ...
def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): """Ensure the token is valid and belongs to the client This method is used by the authorization code grant indirectly by issuing refresh tokens, resource owner password credentials ...
Ensure the token is valid and belongs to the client This method is used by the authorization code grant indirectly by issuing refresh tokens, resource owner password credentials grant (also indirectly) and the refresh token grant.
def buggy_div(request): """ A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or either a or b are not float. :param request: request object :return: """ a = float(request.GET.get('a', '0')) b = float(request.GET.get('b', '0')) re...
A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or either a or b are not float. :param request: request object :return:
def _check_suffix(self, w_string, access_string, index): """ Checks if access string suffix matches with the examined string suffix Args: w_string (str): The examined string to be consumed access_string (str): The access string for the state index (int): The i...
Checks if access string suffix matches with the examined string suffix Args: w_string (str): The examined string to be consumed access_string (str): The access string for the state index (int): The index value for selecting the prefix of w Returns: bool: A...
def set_brightness(host, did, value, token=None): """Set brightness of a bulb or fixture.""" urllib3.disable_warnings() if token: scheme = "https" if not token: scheme = "http" token = "1234567890" url = ( scheme + '://' + host + '/gwr/gop.php?cmd=DeviceSendComman...
Set brightness of a bulb or fixture.
def cumsum(self, axis=0, *args, **kwargs): """ Cumulative sum of non-NA/null values. When performing the cumulative summation, any non-NA/null values will be skipped. The resulting SparseSeries will preserve the locations of NaN values, but the fill value will be `np.nan` regard...
Cumulative sum of non-NA/null values. When performing the cumulative summation, any non-NA/null values will be skipped. The resulting SparseSeries will preserve the locations of NaN values, but the fill value will be `np.nan` regardless. Parameters ---------- axis : {0}...
def fdf(self, x): """Calculate the value of the functional for the specified arguments, and the derivatives with respect to the parameters (taking any specified mask into account). :param x: the value(s) to evaluate at """ x = self._flatten(x) n = 1 if has...
Calculate the value of the functional for the specified arguments, and the derivatives with respect to the parameters (taking any specified mask into account). :param x: the value(s) to evaluate at
def _CheckCacheFileForMatch(self, cache_filename, scopes): """Checks the cache file to see if it matches the given credentials. Args: cache_filename: Cache filename to check. scopes: Scopes for the desired credentials. Returns: List of scopes (if cache matches) or...
Checks the cache file to see if it matches the given credentials. Args: cache_filename: Cache filename to check. scopes: Scopes for the desired credentials. Returns: List of scopes (if cache matches) or None.
def get_ip_addr(self) -> str: '''Show IP Address.''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'ip', '-f', 'inet', 'addr', 'show', 'wlan0') ip_addr = re.findall( r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\...
Show IP Address.
def get_guest_connection_status(self, userid): '''Get guest vm connection status.''' rd = ' '.join(('getvm', userid, 'isreachable')) results = self._request(rd) if results['rs'] == 1: return True else: return False
Get guest vm connection status.
def load_handgeometry(): """Hand Geometry Dataset. The data of this dataset is a 3d numpy array vector with shape (224, 224, 3) containing 112 224x224 RGB photos of hands, and the target is a 1d numpy float array containing the width of the wrist in centimeters. """ dataset_path = _load('handge...
Hand Geometry Dataset. The data of this dataset is a 3d numpy array vector with shape (224, 224, 3) containing 112 224x224 RGB photos of hands, and the target is a 1d numpy float array containing the width of the wrist in centimeters.
def is_zone_running(self, zone): """ Returns the state of the specified zone. :param zone: The zone to check. :type zone: int :returns: Returns True if the zone is currently running, otherwise returns False if the zone is not running. :rtype: boolean ...
Returns the state of the specified zone. :param zone: The zone to check. :type zone: int :returns: Returns True if the zone is currently running, otherwise returns False if the zone is not running. :rtype: boolean
def Disconnect(self): '''Disconnect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] ...
Disconnect a device
def is_build_dir(self, folder_name): """Return whether or not the given dir contains a build.""" # Cannot move up to base scraper due to parser.entries call in # get_build_info_for_date (see below) url = '%s/' % urljoin(self.base_url, self.monthly_build_list_regex, folder_name) ...
Return whether or not the given dir contains a build.
def log(self, logger=None, label=None, eager=False): ''' Log query result consumption details to a logger. Args: logger: Any object which supports a debug() method which accepts a str, such as a Python standard library logger object from the logging m...
Log query result consumption details to a logger. Args: logger: Any object which supports a debug() method which accepts a str, such as a Python standard library logger object from the logging module. If logger is not provided or is None, this method...
def aesCCM(key, key_handle, nonce, data, decrypt=False): """ Function implementing YubiHSM AEAD encrypt/decrypt in software. """ if decrypt: (data, saved_mac) = _split_data(data, len(data) - pyhsm.defines.YSM_AEAD_MAC_SIZE) nonce = pyhsm.util.input_validate_nonce(nonce, pad = True) mac ...
Function implementing YubiHSM AEAD encrypt/decrypt in software.
def _write_single_sample(self, sample): """ :type sample: Sample """ bytes = sample.extras.get("responseHeadersSize", 0) + 2 + sample.extras.get("responseBodySize", 0) message = sample.error_msg if not message: message = sample.extras.get("responseMessage") ...
:type sample: Sample
def get_uids(self, filename=None): """Return a list of UIDs filename -- unused, for API compatibility only """ self._update() return [Abook._gen_uid(self._book[entry]) for entry in self._book.sections()]
Return a list of UIDs filename -- unused, for API compatibility only
async def _get_smallest_env(self): """Get address of the slave environment manager with the smallest number of agents. """ async def slave_task(mgr_addr): r_manager = await self.env.connect(mgr_addr, timeout=TIMEOUT) ret = await r_manager.get_agents(addr=True) ...
Get address of the slave environment manager with the smallest number of agents.
def debug_sync(self, conn_id, cmd_name, cmd_args, progress_callback): """Asynchronously complete a named debug command. The command name and arguments are passed to the underlying device adapter and interpreted there. If the command is long running, progress_callback may be used to pro...
Asynchronously complete a named debug command. The command name and arguments are passed to the underlying device adapter and interpreted there. If the command is long running, progress_callback may be used to provide status updates. Callback is called when the command has finished. ...
def print_token(self, token_node_index): """returns the string representation of a token.""" err_msg = "The given node is not a token node." assert isinstance(self.nodes[token_node_index], TokenNode), err_msg onset = self.nodes[token_node_index].onset offset = self.nodes[token_no...
returns the string representation of a token.
def resolve_data_objects(objects, project=None, folder=None, batchsize=1000): """ :param objects: Data object specifications, each with fields "name" (required), "folder", and "project" :type objects: list of dictionaries :param project: ID of project context; a data object's project...
:param objects: Data object specifications, each with fields "name" (required), "folder", and "project" :type objects: list of dictionaries :param project: ID of project context; a data object's project defaults to this if not specified for that object :type project: ...
def lookup(self, path, is_committed=True, with_proof=False) -> (str, int): """ Queries state for data on specified path :param path: path to data :param is_committed: queries the committed state root if True else the uncommitted root :param with_proof: creates proof if True ...
Queries state for data on specified path :param path: path to data :param is_committed: queries the committed state root if True else the uncommitted root :param with_proof: creates proof if True :return: data
def download_file_with_progress_bar(url): """Downloads a file from the given url, displays a progress bar. Returns a io.BytesIO object """ request = requests.get(url, stream=True) if request.status_code == 404: msg = ('there was a 404 error trying to reach {} \nThis probably ' ...
Downloads a file from the given url, displays a progress bar. Returns a io.BytesIO object
def _correct_build_location(self): # type: () -> None """Move self._temp_build_dir to self._ideal_build_dir/self.req.name For some requirements (e.g. a path to a directory), the name of the package is not available until we run egg_info, so the build_location will return a tempo...
Move self._temp_build_dir to self._ideal_build_dir/self.req.name For some requirements (e.g. a path to a directory), the name of the package is not available until we run egg_info, so the build_location will return a temporary directory and store the _ideal_build_dir. This is only call...
def fav_songs(self): """ FIXME: 支持获取所有的收藏歌曲 """ if self._fav_songs is None: songs_data = self._api.user_favorite_songs(self.identifier) self._fav_songs = [] if not songs_data: return for song_data in songs_data: ...
FIXME: 支持获取所有的收藏歌曲
def extension_counts(container=None, file_list=None, return_counts=True): '''extension counts will return a dictionary with counts of file extensions for an image. :param container: if provided, will use container as image. Can also provide :param image_package: if provided, can be used instead of conta...
extension counts will return a dictionary with counts of file extensions for an image. :param container: if provided, will use container as image. Can also provide :param image_package: if provided, can be used instead of container :param file_list: the complete list of files :param return_counts: r...
def connections_of(self, target): ''' generate tuples containing (relation, object_that_applies) ''' return gen.chain( ((r,i) for i in self.find(target,r)) for r in self.relations_of(target) )
generate tuples containing (relation, object_that_applies)
def fast_forward(self, start_dt): """ Fast-forward file to given start_dt datetime obj using binary search. Only fast for files. Streams need to be forwarded manually, and it will miss the first line that would otherwise match (as it consumes the log line). """ i...
Fast-forward file to given start_dt datetime obj using binary search. Only fast for files. Streams need to be forwarded manually, and it will miss the first line that would otherwise match (as it consumes the log line).
def map_ids(queries,frm='ACC',to='ENSEMBL_PRO_ID', organism_taxid=9606,test=False): """ https://www.uniprot.org/help/api_idmapping """ url = 'https://www.uniprot.org/uploadlists/' params = { 'from':frm, 'to':to, 'format':'tab', 'organism':organism_taxid, 'query':'...
https://www.uniprot.org/help/api_idmapping
def upload_file(self, metadata, filename, signer=None, sign_password=None, filetype='sdist', pyversion='source', keystore=None): """ Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and versio...
Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the file to be uploaded. :param filename: The pathname of the file to be uploaded. :param signer: The identifier of the signer of the file. ...
def create(cls, csr, duration, package, altnames=None, dcv_method=None): """ Create a new certificate. """ params = {'csr': csr, 'package': package, 'duration': duration} if altnames: params['altnames'] = altnames if dcv_method: params['dcv_method'] = dcv_method ...
Create a new certificate.
def create_tablefn_map(fns, pqdb, poolnames): """Stores protein/peptide table names in DB, returns a map with their respective DB IDs""" poolmap = {name: pid for (name, pid) in pqdb.get_all_poolnames()} pqdb.store_table_files([(poolmap[pool], os.path.basename(fn)) for fn, poo...
Stores protein/peptide table names in DB, returns a map with their respective DB IDs
def drag_sphere(Re, Method=None, AvailableMethods=False): r'''This function handles calculation of drag coefficient on spheres. Twenty methods are available, all requiring only the Reynolds number of the sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will be automatically selected...
r'''This function handles calculation of drag coefficient on spheres. Twenty methods are available, all requiring only the Reynolds number of the sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will be automatically selected if none is specified. The full list of correlations valid...
def WriteHashBlobReferences(self, references_by_hash, cursor): """Writes blob references for a given set of hashes.""" values = [] for hash_id, blob_refs in iteritems(references_by_hash): refs = rdf_objects.BlobReferences(items=blob_refs).SerializeToString() values.append({ "hash_id": ...
Writes blob references for a given set of hashes.
def fit(self, X, y): """Fit the model using X as training data and y as target values""" self._data = X self._classes = np.unique(y) self._labels = y self._is_fitted = True
Fit the model using X as training data and y as target values
def _variable(lexer): """Return a variable expression.""" names = _names(lexer) tok = next(lexer) # NAMES '[' ... ']' if isinstance(tok, LBRACK): indices = _indices(lexer) _expect_token(lexer, {RBRACK}) # NAMES else: lexer.unpop_token(tok) indices = tuple() ...
Return a variable expression.
def splitStis(stisfile, sci_count): """ Split a STIS association file into multiple imset MEF files. Split the corresponding spt file if present into single spt files. If an spt file can't be split or is missing a Warning is printed. Returns ------- names: list a list with the name...
Split a STIS association file into multiple imset MEF files. Split the corresponding spt file if present into single spt files. If an spt file can't be split or is missing a Warning is printed. Returns ------- names: list a list with the names of the new flt files.
def set_lines( lines, target_level, indent_string=" ", indent_empty_lines=False ): """ Sets indentation for the given set of :lines:. """ first_non_empty_line_index = _get_first_non_empty_line_index( lines ) first_line_original_level = get_line_level( lines[first_non_empty_line_index], indent_strin...
Sets indentation for the given set of :lines:.
def mutualInformation(sp, activeColumnsCurrentEpoch, column_1, column_2): """ Computes the mutual information of the binary variables that represent the activation probabilities of two columns. The mutual information I(X,Y) of two random variables is given by \[ I (X,Y) = \sum_{x,y} p(x,y) log( p(x,...
Computes the mutual information of the binary variables that represent the activation probabilities of two columns. The mutual information I(X,Y) of two random variables is given by \[ I (X,Y) = \sum_{x,y} p(x,y) log( p(x,y) / ( p(x) p(y) ) ). \] (https://en.wikipedia.org/wiki/Mutual_information)
def connect(self, hostname=None, port=None): """ Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host or IP address. :type port: int :param port: The remote TCP port number. """ if hostname is no...
Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host or IP address. :type port: int :param port: The remote TCP port number.
def guess_settings(self, major, minor): """Gives a guess about the encoder settings used. Returns an empty string if unknown. The guess is mostly correct in case the file was encoded with the default options (-V --preset --alt-preset --abr -b etc) and no other fancy options. ...
Gives a guess about the encoder settings used. Returns an empty string if unknown. The guess is mostly correct in case the file was encoded with the default options (-V --preset --alt-preset --abr -b etc) and no other fancy options. Args: major (int) min...
def dump(new_data): ''' Replace the entire datastore with a passed data structure CLI Example: .. code-block:: bash salt '*' data.dump '{'eggs': 'spam'}' ''' if not isinstance(new_data, dict): if isinstance(ast.literal_eval(new_data), dict): new_data = ast.literal_...
Replace the entire datastore with a passed data structure CLI Example: .. code-block:: bash salt '*' data.dump '{'eggs': 'spam'}'
def maps_get_default_rules_output_rules_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_default_rules = ET.Element("maps_get_default_rules") config = maps_get_default_rules output = ET.SubElement(maps_get_default_rules, "output") ...
Auto Generated Code
def _work_request(self, worker, md5=None): """Wrapper for a work_request to workbench""" # I'm sure there's a better way to do this if not md5 and not self.session.md5: return 'Must call worker with an md5 argument...' elif not md5: md5 = self.session.md5 ...
Wrapper for a work_request to workbench
def set_payload_format(self, payload_format): """Set the payload format for messages sent to and from the VI. Returns True if the command was successful. """ request = { "command": "payload_format", "format": payload_format } status = self._check_...
Set the payload format for messages sent to and from the VI. Returns True if the command was successful.
def replace(self, photo_file, **kwds): """ Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace this photo. """ result = self._client.photo.replace(self, photo_file, **kwds) self._replace_fields(result.get_fields())
Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace this photo.
def pca_to_mapping(pca,**extra_props): """ A helper to return a mapping of a PCA result set suitable for reconstructing a planar error surface in other software packages kwargs: method (defaults to sampling axes) """ from .axes import sampling_axes method = extra_props.pop('method',sampling...
A helper to return a mapping of a PCA result set suitable for reconstructing a planar error surface in other software packages kwargs: method (defaults to sampling axes)
def get_subprocess_output(cls, command, ignore_stderr=True, **kwargs): """Get the output of an executed command. :param command: An iterable representing the command to execute (e.g. ['ls', '-al']). :param ignore_stderr: Whether or not to ignore stderr output vs interleave it with stdout. :raises: `Pro...
Get the output of an executed command. :param command: An iterable representing the command to execute (e.g. ['ls', '-al']). :param ignore_stderr: Whether or not to ignore stderr output vs interleave it with stdout. :raises: `ProcessManager.ExecutionError` on `OSError` or `CalledProcessError`. :returns...
def pack(chunks, r=32): """Return integer concatenating integer chunks of r > 0 bit-length. >>> pack([0, 1, 0, 1, 0, 1], 1) 42 >>> pack([0, 1], 8) 256 >>> pack([0, 1], 0) Traceback (most recent call last): ... ValueError: pack needs r > 0 """ if r < 1: raise Va...
Return integer concatenating integer chunks of r > 0 bit-length. >>> pack([0, 1, 0, 1, 0, 1], 1) 42 >>> pack([0, 1], 8) 256 >>> pack([0, 1], 0) Traceback (most recent call last): ... ValueError: pack needs r > 0
def map_exp_ids(self, exp): """Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight) """ names = self.exp_feature_names if self.discretized_feature_names is not None: ...
Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight)
def nvmlDeviceGetMemoryInfo(handle): r""" /** * Retrieves the amount of used, free and total memory available on the device, in bytes. * * For all products. * * Enabling ECC reduces the amount of total available memory, due to the extra required parity bits. * Under WDDM most devic...
r""" /** * Retrieves the amount of used, free and total memory available on the device, in bytes. * * For all products. * * Enabling ECC reduces the amount of total available memory, due to the extra required parity bits. * Under WDDM most device memory is allocated and managed on star...
def connected_subgraph(self, node): """Returns the subgraph containing the given node, its ancestors, and its descendants. Parameters ---------- node : str We want to create the subgraph containing this node. Returns ------- subgraph : networ...
Returns the subgraph containing the given node, its ancestors, and its descendants. Parameters ---------- node : str We want to create the subgraph containing this node. Returns ------- subgraph : networkx.DiGraph The subgraph containing ...
def coin_toss(self): """Gets information relating to the opening coin toss. Keys are: * wonToss - contains the ID of the team that won the toss * deferred - bool whether the team that won the toss deferred it :returns: Dictionary of coin toss-related info. """ d...
Gets information relating to the opening coin toss. Keys are: * wonToss - contains the ID of the team that won the toss * deferred - bool whether the team that won the toss deferred it :returns: Dictionary of coin toss-related info.
def ping_directories(self, request, queryset, messages=True): """ Ping web directories for selected entries. """ for directory in settings.PING_DIRECTORIES: pinger = DirectoryPinger(directory, queryset) pinger.join() if messages: succes...
Ping web directories for selected entries.
def _read(self): """ Reads a single event from the joystick, blocking until one is available. Returns `None` if a non-key event was read, or an `InputEvent` tuple describing the event otherwise. """ event = self._stick_file.read(self.EVENT_SIZE) (tv_sec, tv_usec, ...
Reads a single event from the joystick, blocking until one is available. Returns `None` if a non-key event was read, or an `InputEvent` tuple describing the event otherwise.
def reload_class_methods(self, class_, verbose=True): """ rebinds all class methods Args: self (object): class instance to reload class_ (type): type to reload as Example: >>> # DISABLE_DOCTEST >>> from utool.util_class import * # NOQA >>> self = '?' >>...
rebinds all class methods Args: self (object): class instance to reload class_ (type): type to reload as Example: >>> # DISABLE_DOCTEST >>> from utool.util_class import * # NOQA >>> self = '?' >>> class_ = '?' >>> result = reload_class_methods(self, cla...
def headers(self): """ Returns a list of the last HTTP response headers. Header keys are normalized to capitalized form, as in `User-Agent`. """ headers = self.conn.issue_command("Headers") res = [] for header in headers.split("\r"): key, value = header.split(": ", 1) for line in val...
Returns a list of the last HTTP response headers. Header keys are normalized to capitalized form, as in `User-Agent`.
def GC_partial(portion): """Manually compute GC content percentage in a DNA string, taking ambiguous values into account (according to standard IUPAC notation). """ sequence_count = collections.Counter(portion) gc = ((sum([sequence_count[i] for i in 'gGcCsS']) + sum([sequence_count[i] for...
Manually compute GC content percentage in a DNA string, taking ambiguous values into account (according to standard IUPAC notation).
def _par_write(self, dirname): """ Internal write function to write a formatted parameter file. :type dirname: str :param dirname: Directory to write the parameter file to. """ filename = dirname + '/' + 'template_parameters.csv' with open(filename, 'w') as parfi...
Internal write function to write a formatted parameter file. :type dirname: str :param dirname: Directory to write the parameter file to.
def put_intent(name=None, description=None, slots=None, sampleUtterances=None, confirmationPrompt=None, rejectionStatement=None, followUpPrompt=None, conclusionStatement=None, dialogCodeHook=None, fulfillmentActivity=None, parentIntentSignature=None, checksum=None): """ Creates an intent or replaces an existing...
Creates an intent or replaces an existing intent. To define the interaction between the user and your bot, you use one or more intents. For a pizza ordering bot, for example, you would create an OrderPizza intent. To create an intent or replace an existing intent, you must provide the following: You can spe...
def create_branch_and_checkout(self, branch_name: str): """ Creates a new branch if it doesn't exist Args: branch_name: branch name """ self.create_branch(branch_name) self.checkout(branch_name)
Creates a new branch if it doesn't exist Args: branch_name: branch name
def remove(self, address): """ Remove an address from the connection pool, if present, closing all connections to that address. """ with self.lock: for connection in self.connections.pop(address, ()): try: connection.close() ...
Remove an address from the connection pool, if present, closing all connections to that address.
def run(cmd, capture=False, shell=True, env=None, exit_on_error=None, never_pretend=False): # type: (str, bool, bool, Dict[str, str], bool) -> ExecResult """ Run a shell command. Args: cmd (str): The shell command to execute. shell (bool):...
Run a shell command. Args: cmd (str): The shell command to execute. shell (bool): Same as in `subprocess.Popen`. capture (bool): If set to True, it will capture the standard input/error instead of just piping it to the caller stdout/stderr. ...
def clean_email(self): """ ensure email is in the database """ if EMAIL_CONFIRMATION: from .models import EmailAddress condition = EmailAddress.objects.filter( email__iexact=self.cleaned_data["email"], verified=True ).count() == 0 ...
ensure email is in the database
def GetProp(self, prop): """ get attribute """ if prop == 'id': return self.id elif prop == 'status': return self.status elif prop == 'bm': return self.bm elif prop == 'graph': return self.graph else: return...
get attribute
def selection(self): """Returns items in selection as a QItemSelection object""" sel = QtGui.QItemSelection() for index in self.selectedIndexes(): sel.select(index, index) return sel
Returns items in selection as a QItemSelection object
def search(request, abbr): ''' Context: - search_text - abbr - metadata - found_by_id - bill_results - more_bills_available - legislators_list - nav_active Tempaltes: - billy/web/public/search_results_no_query.html - billy/web/...
Context: - search_text - abbr - metadata - found_by_id - bill_results - more_bills_available - legislators_list - nav_active Tempaltes: - billy/web/public/search_results_no_query.html - billy/web/public/search_results_bills_legislators...
def predict(self, data, initial_args=None): """Return the inference from the specified endpoint. Args: data (object): Input data for which you want the model to provide inference. If a serializer was specified when creating the RealTimePredictor, the result of the ...
Return the inference from the specified endpoint. Args: data (object): Input data for which you want the model to provide inference. If a serializer was specified when creating the RealTimePredictor, the result of the serializer is sent as input data. Otherwise the d...
def remove_parenthesis_around_tz(cls, timestr): """get rid of parenthesis around timezone: (GMT) => GMT :return: the new string if parenthesis were found, `None` otherwise """ parenthesis = cls.TIMEZONE_PARENTHESIS.match(timestr) if parenthesis is not None: return pa...
get rid of parenthesis around timezone: (GMT) => GMT :return: the new string if parenthesis were found, `None` otherwise
def create(epsilon: typing.Union[Schedule, float]): """ Vel factory function """ return GenericFactory(EpsGreedy, arguments={'epsilon': epsilon})
Vel factory function
def _divide_and_round(a, b): """divide a by b and round result to the nearest integer When the ratio is exactly half-way between two integers, the even integer is returned. """ # Based on the reference implementation for divmod_near # in Objects/longobject.c. q, r = divmod(a, b) # round...
divide a by b and round result to the nearest integer When the ratio is exactly half-way between two integers, the even integer is returned.
def __get_resource_entry_data(self, bundleId, languageId, resourceKey, fallback=False): """``GET /{serviceInstanceId}/v2/bundles/{bundleId}/{languageId} /{resourceKey}`` Gets the resource entry information. """ url = self.__get_base_bundl...
``GET /{serviceInstanceId}/v2/bundles/{bundleId}/{languageId} /{resourceKey}`` Gets the resource entry information.
def check_ellipsis(text): """Use an ellipsis instead of three dots.""" err = "typography.symbols.ellipsis" msg = u"'...' is an approximation, use the ellipsis symbol '…'." regex = "\.\.\." return existence_check(text, [regex], err, msg, max_errors=3, require_padding=False...
Use an ellipsis instead of three dots.
def __get_merged_api_info(self, services): """Builds a description of an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: The _ApiInfo object to use for the API that the given services implement. """ base_paths = sorted(set(s....
Builds a description of an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: The _ApiInfo object to use for the API that the given services implement.
def text_search(self, anchor, byte=False): """ Search the substring in response body. :param anchor: string to search :param byte: if False then `anchor` should be the unicode string, and search will be performed in `response.unicode_body()` else `anchor` should ...
Search the substring in response body. :param anchor: string to search :param byte: if False then `anchor` should be the unicode string, and search will be performed in `response.unicode_body()` else `anchor` should be the byte-string and search will be performed in ...
def do_loop_turn(self): """Receiver daemon main loop :return: None """ # Begin to clean modules self.check_and_del_zombie_modules() # Maybe the arbiter pushed a new configuration... if self.watch_for_new_conf(timeout=0.05): logger.info("I got a new ...
Receiver daemon main loop :return: None
def find(self, obj, forced_type=None, cls=anyconfig.models.processor.Processor): """ :param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find ...
:param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find :param cls: A class object to compare with 'ptype' :return: an instance of processor class to proce...
def _prepare_connection(**nxos_api_kwargs): ''' Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init. ''' nxos_api_kwargs = clean_kwargs(**nxos_api_kwargs) init_kwargs = {} # Clean up any arguments that are no...
Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init.
def total_statements(self, filename=None): """ Return the total number of statements for the file `filename`. If `filename` is not given, return the total number of statements for all files. """ if filename is not None: statements = self._get_lines_by_filename...
Return the total number of statements for the file `filename`. If `filename` is not given, return the total number of statements for all files.