code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def gumbel_softmax_discrete_bottleneck(x, bottleneck_bits, beta=0.25, decay=0.999, epsilon=1e-5, temperature_warmup_steps=150...
VQ-VAE using Gumbel-Softmax. Different from `gumbel_softmax()` function as this function calculates the KL by using the discrete entropy instead of taking the argmax, and it also uses an exponential moving average to update the codebook while the `gumbel_softmax()` function includes no codebook update. Ar...
def plot_vxx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxx component of the tensor. Usage ----- x.plot_vxx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientati...
Plot the Vxx component of the tensor. Usage ----- x.plot_vxx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals...
def generate_cloudformation_args(stack_name, parameters, tags, template, capabilities=DEFAULT_CAPABILITIES, change_set_type=None, service_role=None, stack_policy=None, ...
Used to generate the args for common cloudformation API interactions. This is used for create_stack/update_stack/create_change_set calls in cloudformation. Args: stack_name (str): The fully qualified stack name in Cloudformation. parameters (list): A list of dictionaries that defines the ...
def equal_distribution_folds(y, folds=2): """Creates `folds` number of indices that has roughly balanced multi-label distribution. Args: y: The multi-label outputs. folds: The number of folds to create. Returns: `folds` number of indices that have roughly equal multi-label distribu...
Creates `folds` number of indices that has roughly balanced multi-label distribution. Args: y: The multi-label outputs. folds: The number of folds to create. Returns: `folds` number of indices that have roughly equal multi-label distributions.
def disconnect(self): """ This method disconnects an IOM session to allow for reconnecting when switching networks See the Advanced topics section of the doc for details """ if self.sascfg.mode != 'IOM': res = "This method is only available with the IOM access method"...
This method disconnects an IOM session to allow for reconnecting when switching networks See the Advanced topics section of the doc for details
def chown(hdfs_path, user=None, group=None, hdfs_user=None): """ See :meth:`fs.hdfs.chown`. """ user = user or '' group = group or '' host, port, path_ = path.split(hdfs_path, hdfs_user) with hdfs(host, port, hdfs_user) as fs: return fs.chown(path_, user=user, group=group)
See :meth:`fs.hdfs.chown`.
def delete(self, cls, rid, user='undefined'): """ Delete a record by id. `user` currently unused. Would be used with soft deletes. >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> len(s.list('tstoretest')) 1 >>> s.delete('t...
Delete a record by id. `user` currently unused. Would be used with soft deletes. >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> len(s.list('tstoretest')) 1 >>> s.delete('tstoretest', '1') >>> len(s.list('tstoretest')) 0 ...
def get_matching_multiplex_port(self,name): """ Given a name, figure out if a multiplex port prefixes this name and return it. Otherwise return none. """ # short circuit: if the attribute name already exists return none # if name in self._portnames: return None # if no...
Given a name, figure out if a multiplex port prefixes this name and return it. Otherwise return none.
def exists(self, value=None): """ Return True if the given pk value exists for the given class. If no value is given, we use the value of the current field, which is the value of the "_pk" attribute of its instance. """ try: if not value: value...
Return True if the given pk value exists for the given class. If no value is given, we use the value of the current field, which is the value of the "_pk" attribute of its instance.
def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs...
Helper function to run osquery queries
def toProtocolElement(self): """ Returns the representation of this ContinuousSet as the corresponding ProtocolElement. """ gaContinuousSet = protocol.ContinuousSet() gaContinuousSet.id = self.getId() gaContinuousSet.dataset_id = self.getParentContainer().getId() ...
Returns the representation of this ContinuousSet as the corresponding ProtocolElement.
def entropy(s): """Calculate the Entropy Impurity for a list of samples. """ return -sum( p*np.log(p) for i in range(len(s)) for p in [prop(s[i], s)] )
Calculate the Entropy Impurity for a list of samples.
def _plot_data_to_ax( data_all, ax1, e_unit=None, sed=True, ylabel=None, ulim_opts={}, errorbar_opts={}, ): """ Plots data errorbars and upper limits onto ax. X label is left to plot_data and plot_fit because they depend on whether residuals are plotted. """ if e_unit is...
Plots data errorbars and upper limits onto ax. X label is left to plot_data and plot_fit because they depend on whether residuals are plotted.
def to_python(self, value): """ B64decode and unpickle the object, optionally decompressing it. If an error is raised in de-pickling and we're sure the value is a definite pickle, the error is allowed to propogate. If we aren't sure if the value is a pickle or not, then we catch...
B64decode and unpickle the object, optionally decompressing it. If an error is raised in de-pickling and we're sure the value is a definite pickle, the error is allowed to propogate. If we aren't sure if the value is a pickle or not, then we catch the error and return the original value...
def obj2unicode(obj): """Return a unicode representation of a python object """ if isinstance(obj, unicode_type): return obj elif isinstance(obj, bytes_type): try: return unicode_type(obj, 'utf-8') except UnicodeDecodeError as strerror: sys.stderr.write("U...
Return a unicode representation of a python object
def adjoint(self): """Return the adjoint operator. The laplacian is self-adjoint, so this returns ``self``. """ return Laplacian(self.range, self.domain, pad_mode=self.pad_mode, pad_const=0)
Return the adjoint operator. The laplacian is self-adjoint, so this returns ``self``.
def update_handler(Model, name=None, **kwds): """ This factory returns an action handler that updates a new instance of the specified model when a update action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to u...
This factory returns an action handler that updates a new instance of the specified model when a update action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to update when the action received. Retur...
def check(self, dsm, **kwargs): """ Check layered architecture. Args: dsm (:class:`DesignStructureMatrix`): the DSM to check. Returns: bool, str: True if layered architecture else False, messages """ layered_architecture = True messages =...
Check layered architecture. Args: dsm (:class:`DesignStructureMatrix`): the DSM to check. Returns: bool, str: True if layered architecture else False, messages
def _call_command(self, name, *args, **kwargs): """ If a command is called for the main field, without dynamic part, an ImplementationError is raised: commands can only be applied on dynamic versions. On dynamic versions, if the command is a modifier, we add the version in ...
If a command is called for the main field, without dynamic part, an ImplementationError is raised: commands can only be applied on dynamic versions. On dynamic versions, if the command is a modifier, we add the version in the inventory.
def render(gpg_data, saltenv='base', sls='', argline='', **kwargs): ''' Create a gpg object given a gpg_keydir, and then use it to try to decrypt the data to be rendered. ''' if not _get_gpg_exec(): raise SaltRenderError('GPG unavailable') log.debug('Reading GPG keys from: %s', _get_key_...
Create a gpg object given a gpg_keydir, and then use it to try to decrypt the data to be rendered.
def flush(self): """ This only needs to be called manually from unit tests """ self.logger.debug('Flush joining') self.queue.join() self.logger.debug('Flush joining ready')
This only needs to be called manually from unit tests
def doc_inherit(parent, style="parent"): """ Returns a function/method decorator that, given `parent`, updates the docstring of the decorated function/method based on the specified style and the corresponding attribute of `parent`. Parameters ---------- parent : Union[str, Any] ...
Returns a function/method decorator that, given `parent`, updates the docstring of the decorated function/method based on the specified style and the corresponding attribute of `parent`. Parameters ---------- parent : Union[str, Any] The docstring, or object of which the doc...
def read_plain_double(file_obj, count): """Read `count` 64-bit float (double) using the plain encoding.""" return struct.unpack("<{}d".format(count).encode("utf-8"), file_obj.read(8 * count))
Read `count` 64-bit float (double) using the plain encoding.
def gen_signature(priv, pub, signature_path, auto_create=False, keysize=None): ''' Generate master public-key-signature ''' skey = get_key(__opts__) return skey.gen_keys_signature(priv, pub, signature_path, auto_create, keysize)
Generate master public-key-signature
def common_bootsrap_payload(self): """Common data always sent to the client""" messages = get_flashed_messages(with_categories=True) locale = str(get_locale()) return { 'flash_messages': messages, 'conf': {k: conf.get(k) for k in FRONTEND_CONF_KEYS}, '...
Common data always sent to the client
def get_by_id(self, symbol: str) -> SymbolMap: """ Finds the map by in-symbol """ return self.query.filter(SymbolMap.in_symbol == symbol).first()
Finds the map by in-symbol
def setup_log(name): '''Returns a logging instance for the provided name. The returned object is an instance of logging.Logger. Logged messages will be printed to stderr when running in the CLI, or forwarded to XBMC's log when running in XBMC mode. ''' _log = logging.getLogger(name) _log.set...
Returns a logging instance for the provided name. The returned object is an instance of logging.Logger. Logged messages will be printed to stderr when running in the CLI, or forwarded to XBMC's log when running in XBMC mode.
def linear_set_layer(layer_size, inputs, context=None, activation_fn=tf.nn.relu, dropout=0.0, name=None): """Basic layer type for doing funky things with sets. Applies a linear transformation to each element in...
Basic layer type for doing funky things with sets. Applies a linear transformation to each element in the input set. If a context is supplied, it is concatenated with the inputs. e.g. One can use global_pool_1d to get a representation of the set which can then be used as the context for the next layer. ...
def _create_dock(self): """Create dockwidget and tabify it with the legend.""" # Import dock here as it needs to be imported AFTER i18n is set up from safe.gui.widgets.dock import Dock self.dock_widget = Dock(self.iface) self.dock_widget.setObjectName('InaSAFE-Dock') self...
Create dockwidget and tabify it with the legend.
def insert(self, **fields): """Creates a new record in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: fields: The fields of the row t...
Creates a new record in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: fields: The fields of the row to create. Returns: ...
async def serialize_properties(inputs: 'Inputs', property_deps: Dict[str, List['Resource']], input_transformer: Optional[Callable[[str], str]] = None) -> struct_pb2.Struct: """ Serializes an arbitrary Input bag into a Protobuf structure, keeping trac...
Serializes an arbitrary Input bag into a Protobuf structure, keeping track of the list of dependent resources in the `deps` list. Serializing properties is inherently async because it awaits any futures that are contained transitively within the input bag.
def atime(self): """ Get most recent access time in timestamp. """ try: return self._stat.st_atime except: # pragma: no cover self._stat = self.stat() return self.atime
Get most recent access time in timestamp.
def read_xml(cls, url, markup, game): """ read xml object :param url: contents url :param markup: markup provider :param game: MLBAM Game object :return: pitchpx.game.players.Players object """ return Players._read_objects(MlbamUtil.find_xml("".join([url, ...
read xml object :param url: contents url :param markup: markup provider :param game: MLBAM Game object :return: pitchpx.game.players.Players object
def IsTemplateParameterList(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is the end of template<>. Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True...
Check if the token ending on (linenum, column) is the end of template<>. Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is end of a template parameter list, False otherw...
def plan(self): """ Gets the associated plan for this invoice. In order to provide a consistent view of invoices, the plan object should be taken from the first invoice item that has one, rather than using the plan associated with the subscription. Subscriptions (and their associated plan) are updated by th...
Gets the associated plan for this invoice. In order to provide a consistent view of invoices, the plan object should be taken from the first invoice item that has one, rather than using the plan associated with the subscription. Subscriptions (and their associated plan) are updated by the customer and repre...
def find_aliases(self, seq_id=None, namespace=None, alias=None, current_only=True, translate_ncbi_namespace=None): """returns iterator over alias annotation records that match criteria The arguments, all optional, restrict the records that are returned. Without arguments, all aliases a...
returns iterator over alias annotation records that match criteria The arguments, all optional, restrict the records that are returned. Without arguments, all aliases are returned. If arguments contain %, the `like` comparison operator is used. Otherwise arguments must match ...
def get_tokens(self, node, include_extra=False): """ Yields all tokens making up the given node. If include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT. """ return self.token_range(node.first_token, node.last_token, include_extra=include_extra)
Yields all tokens making up the given node. If include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT.
def update_image(self, name): # The `_image` is to avoid conflicts with MutableMapping.update. """ Update (i.e., rename) the image :param str name: the new name for the image :return: an updated `Image` object :rtype: Image :raises DOAPIError: if the API endpoint...
Update (i.e., rename) the image :param str name: the new name for the image :return: an updated `Image` object :rtype: Image :raises DOAPIError: if the API endpoint replies with an error
def WriteSignedBinaryReferences(self, binary_id, references, cursor=None): """Writes blob references for a signed binary to the DB.""" args = { "binary_type": binary_id.binary_type.Serialize...
Writes blob references for a signed binary to the DB.
def _spa_python_import(how): """Compile spa.py appropriately""" from pvlib import spa # check to see if the spa module was compiled with numba using_numba = spa.USE_NUMBA if how == 'numpy' and using_numba: # the spa module was compiled to numba code, so we need to # reload the mod...
Compile spa.py appropriately
def execute_loaders(self, env=None, silent=None, key=None, filename=None): """Execute all internal and registered loaders :param env: The environment to load :param silent: If loading erros is silenced :param key: if provided load a single key :param filename: optional custom fi...
Execute all internal and registered loaders :param env: The environment to load :param silent: If loading erros is silenced :param key: if provided load a single key :param filename: optional custom filename to load
def _easy_facetgrid(data, plotfunc, kind, x=None, y=None, row=None, col=None, col_wrap=None, sharex=True, sharey=True, aspect=None, size=None, subplot_kws=None, **kwargs): """ Convenience method to call xarray.plot.FacetGrid from 2d plotting methods kwargs are the ar...
Convenience method to call xarray.plot.FacetGrid from 2d plotting methods kwargs are the arguments to 2d plotting method
def create_module(clear_target, target): """Creates a new template HFOS plugin module""" if os.path.exists(target): if clear_target: shutil.rmtree(target) else: log("Target exists! Use --clear to delete it first.", emitter='MANAGE') sys.exit(2...
Creates a new template HFOS plugin module
def calculate_signatures(self): """Calculate the signatures for this MAR file. Returns: A list of signature tuples: [(algorithm_id, signature_data), ...] """ if not self.signing_algorithm: return [] algo_id = {'sha1': 1, 'sha384': 2}[self.signing_algori...
Calculate the signatures for this MAR file. Returns: A list of signature tuples: [(algorithm_id, signature_data), ...]
def parse_parameter_group(self, global_params, region, parameter_group): """ Parse a single Redshift parameter group and fetch all of its parameters :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param pa...
Parse a single Redshift parameter group and fetch all of its parameters :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param parameter_group: Parameter group
def set_status(self, status, msg): """ Set and return the status of the task. Args: status: Status object or string representation of the status msg: string with human-readable message used in the case of errors. """ # truncate string if it's long. msg wi...
Set and return the status of the task. Args: status: Status object or string representation of the status msg: string with human-readable message used in the case of errors.
def load_heartrate(as_series=False): """Uniform heart-rate data. A sample of heartrate data borrowed from an `MIT database <http://ecg.mit.edu/time-series/>`_. The sample consists of 150 evenly spaced (0.5 seconds) heartrate measurements. Parameters ---------- as_series : bool, optional (d...
Uniform heart-rate data. A sample of heartrate data borrowed from an `MIT database <http://ecg.mit.edu/time-series/>`_. The sample consists of 150 evenly spaced (0.5 seconds) heartrate measurements. Parameters ---------- as_series : bool, optional (default=False) Whether to return a Pa...
def hardware_connector_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") connector = ET.SubElement(hardware, "connector") name = ET.SubElement(connecto...
Auto Generated Code
def listdir_matches(match): """Returns a list of filenames contained in the named directory. Only filenames which start with `match` will be returned. Directories will have a trailing slash. """ import os last_slash = match.rfind('/') if last_slash == -1: dirname = '.' ...
Returns a list of filenames contained in the named directory. Only filenames which start with `match` will be returned. Directories will have a trailing slash.
def totext(self) ->str: """ return blob content from StorageBlobModel instance to a string. Parameters are: """ sreturn = '' if self.properties.content_settings.content_encoding is None: raise AzureStorageWrapException(self, 'can not convert blob {!s} to text because...
return blob content from StorageBlobModel instance to a string. Parameters are:
def patch_namespaced_pod_preset(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_pod_preset # noqa: E501 partially update the specified PodPreset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please...
patch_namespaced_pod_preset # noqa: E501 partially update the specified PodPreset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_pod_preset(name, namespace, body, ...
def _set_property(xml_root, name, value, properties=None): """Sets property to specified value.""" if properties is None: properties = xml_root.find("properties") for prop in properties: if prop.get("name") == name: prop.set("value", utils.get_unicode_str(value)) bre...
Sets property to specified value.
def stream(self, actor_sid=values.unset, event_type=values.unset, resource_sid=values.unset, source_ip_address=values.unset, start_date=values.unset, end_date=values.unset, limit=None, page_size=None): """ Streams EventInstance records from the API as a gener...
Streams EventInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param unicode actor_sid: Only include Events init...
def fit(self, bbox, max_zoom=MAX_ZOOM, force_zoom=None): """ Fits the projector to a BoundingBox :param bbox: BoundingBox :param max_zoom: max zoom allowed :param force_zoom: force this specific zoom value even if the whole bbox does not completely fit """ BUFFER...
Fits the projector to a BoundingBox :param bbox: BoundingBox :param max_zoom: max zoom allowed :param force_zoom: force this specific zoom value even if the whole bbox does not completely fit
def iter_links_link_element(self, element): '''Iterate a ``link`` for URLs. This function handles stylesheets and icons in addition to standard scraping rules. ''' rel = element.attrib.get('rel', '') stylesheet = 'stylesheet' in rel icon = 'icon' in rel i...
Iterate a ``link`` for URLs. This function handles stylesheets and icons in addition to standard scraping rules.
def _build_request_url(self, secure, api_method, version): """Build a URL for a API method request """ if secure: proto = ANDROID.PROTOCOL_SECURE else: proto = ANDROID.PROTOCOL_INSECURE req_url = ANDROID.API_URL.format( protocol=proto, ...
Build a URL for a API method request
def page_factory(request): """ Page factory. Config models example: .. code-block:: python models = { '': [WebPage, CatalogResource], 'catalogue': CatalogResource, 'news': NewsResource, } """ prefix = request.matchdict['prefix'] # /{prefix}/pag...
Page factory. Config models example: .. code-block:: python models = { '': [WebPage, CatalogResource], 'catalogue': CatalogResource, 'news': NewsResource, }
def get_balance(self): """ Get balance with provider. """ if not SMSGLOBAL_CHECK_BALANCE_COUNTRY: raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.') params = { 'user' : self.get_username(), 'password' ...
Get balance with provider.
def add_orbit(self, component=None, **kwargs): """ Shortcut to :meth:`add_component` but with kind='orbit' """ kwargs.setdefault('component', component) return self.add_component('orbit', **kwargs)
Shortcut to :meth:`add_component` but with kind='orbit'
def _build_word(syl, vowels): """Builds a Pinyin word re pattern from a Pinyin syllable re pattern. A word is defined as a series of consecutive valid Pinyin syllables with optional hyphens and apostrophes interspersed. Hyphens must be followed immediately by another valid Pinyin syllable. Apostrophes ...
Builds a Pinyin word re pattern from a Pinyin syllable re pattern. A word is defined as a series of consecutive valid Pinyin syllables with optional hyphens and apostrophes interspersed. Hyphens must be followed immediately by another valid Pinyin syllable. Apostrophes must be followed by another valid...
def _datalog(self, parameter, run, maxrun, det_id): "Extract data from database" values = { 'parameter_name': parameter, 'minrun': run, 'maxrun': maxrun, 'detid': det_id, } data = urlencode(values) content = self._get_content('strea...
Extract data from database
def is_contradictory(self, other): """ Returns True if the two DictCells are unmergeable. """ if not isinstance(other, DictCell): raise Exception("Incomparable") for key, val in self: if key in other.__dict__['p'] \ and val.is_contradictory(other.__di...
Returns True if the two DictCells are unmergeable.
def warn_if_detached(func): """ Warn if self / cls is detached. """ @wraps(func) def wrapped(this, *args, **kwargs): # Check for _detached in __dict__ instead of using hasattr # to avoid infinite loop in __getattr__ if '_detached' in this.__dict__ and this._detached: warn...
Warn if self / cls is detached.
def check_for_eni_source(): ''' Juju removes the source line when setting up interfaces, replace if missing ''' with open('/etc/network/interfaces', 'r') as eni: for line in eni: if line == 'source /etc/network/interfaces.d/*': return with open('/etc/network/interfac...
Juju removes the source line when setting up interfaces, replace if missing
def export_task_info(node_params, output_element): """ Adds Task node attributes to exported XML element :param node_params: dictionary with given task parameters, :param output_element: object representing BPMN XML 'task' element. """ if consts.Consts.default in node_pa...
Adds Task node attributes to exported XML element :param node_params: dictionary with given task parameters, :param output_element: object representing BPMN XML 'task' element.
def quit(self): """Remove this user from all channels and reinitialize the user's list of joined channels. """ for c in self.channels: c.users.remove(self.nick) self.channels = []
Remove this user from all channels and reinitialize the user's list of joined channels.
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit): """Exports all collections to (JSON-) files.""" export_format = export_format.upper() if pretty: indent = 4 else: indent = 0 f = None if filename: try: f = open(fil...
Exports all collections to (JSON-) files.
def grantxml2json(self, grant_xml): """Convert OpenAIRE grant XML into JSON.""" tree = etree.fromstring(grant_xml) # XML harvested from OAI-PMH has a different format/structure if tree.prefix == 'oai': ptree = self.get_subtree( tree, '/oai:record/oai:metadata/...
Convert OpenAIRE grant XML into JSON.
def r_bergomi(H,T,eta,xi,rho,S0,r,N,M,dW=None,dW_orth=None,cholesky = False,return_v=False): ''' Return M Euler-Maruyama sample paths with N time steps of (S_t,v_t), where (S_t,v_t) follows the rBergomi model of mathematical finance :rtype: M x N x d array ''' times = np.linspace(0, T, N) ...
Return M Euler-Maruyama sample paths with N time steps of (S_t,v_t), where (S_t,v_t) follows the rBergomi model of mathematical finance :rtype: M x N x d array
def transform_coords(self, width, height): """Return the current absolute (x, y) coordinates of the tablet tool event, transformed to screen coordinates and whether they have changed in this event. Note: On some devices, returned value may be negative or larger than the width of the device. See `Out-of-b...
Return the current absolute (x, y) coordinates of the tablet tool event, transformed to screen coordinates and whether they have changed in this event. Note: On some devices, returned value may be negative or larger than the width of the device. See `Out-of-bounds motion events`_ for more details. Arg...
def get_draft_url(url): """ Return the given URL with a draft mode HMAC in its querystring. """ if verify_draft_url(url): # Nothing to do. Already a valid draft URL. return url # Parse querystring and add draft mode HMAC. url = urlparse.urlparse(url) salt = get_random_string(...
Return the given URL with a draft mode HMAC in its querystring.
def run_file(name, database, query_file=None, output=None, grain=None, key=None, overwrite=True, saltenv=None, check_db_exists=True, **connection_args): ''' Execute an arbitrary query on the specified database .. versionadded:: 2017.7....
Execute an arbitrary query on the specified database .. versionadded:: 2017.7.0 name Used only as an ID database The name of the database to execute the query_file on query_file The file of mysql commands to run output grain: output in a grain other: the ...
def run(self, resources): """Sets the RTC timestamp to UTC. Args: resources (dict): A dictionary containing the required resources that we needed access to in order to perform this step. """ hwman = resources['connection'] con = hwman.hwman.controller...
Sets the RTC timestamp to UTC. Args: resources (dict): A dictionary containing the required resources that we needed access to in order to perform this step.
def get_column_metadata(gctx_file_path, convert_neg_666=True): """ Opens .gctx file and returns only column metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num...
Opens .gctx file and returns only column metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num Output: - col_meta (pandas DataFrame): a DataFrame of all col...
def users_feature(app): """ Add users feature Allows to register users and assign groups, instantiates flask login, flask principal and oauth integration """ # check we have jwt secret configures if not app.config.get('USER_JWT_SECRET', None): raise x.JwtSecretMissing('Please set US...
Add users feature Allows to register users and assign groups, instantiates flask login, flask principal and oauth integration
def covariance_matrix(self): """ Constructs the covariance matrix of input data from the singular value decomposition. Note that this is different than a covariance matrix of residuals, which is what we want for calculating fit errors. Using SVD output to compute covariance matrix X...
Constructs the covariance matrix of input data from the singular value decomposition. Note that this is different than a covariance matrix of residuals, which is what we want for calculating fit errors. Using SVD output to compute covariance matrix X=UΣV⊤ XX⊤XX⊤=(UΣV⊤)(UΣV⊤)⊤=(UΣV⊤)(VΣU...
def dispatch_request(self, *args, **kwargs): """ If validation=True perform validation """ if self.validation: specs = {} attrs = flasgger.constants.OPTIONAL_FIELDS + [ 'parameters', 'definitions', 'responses', 'summary', 'descripti...
If validation=True perform validation
def get_urls(self): """ Extend the admin urls for the CompetitionEntryAdmin model to be able to invoke a CSV export view on the admin model """ urls = super(CompetitionEntryAdmin, self).get_urls() csv_urls = patterns('', url( r'^exportcsv/$', ...
Extend the admin urls for the CompetitionEntryAdmin model to be able to invoke a CSV export view on the admin model
def getPage(url, contextFactory=None, *args, **kwargs): """Download a web page as a string. Download a page. Return a deferred, which will callback with a page (as a string) or errback with a description of the error. See HTTPClientFactory to see what extra args can be passed. """ scheme, host...
Download a web page as a string. Download a page. Return a deferred, which will callback with a page (as a string) or errback with a description of the error. See HTTPClientFactory to see what extra args can be passed.
def describe_instances(self, xml_bytes): """ Parse the reservations XML payload that is returned from an AWS describeInstances API call. Instead of returning the reservations as the "top-most" object, we return the object that most developers and their code will be inter...
Parse the reservations XML payload that is returned from an AWS describeInstances API call. Instead of returning the reservations as the "top-most" object, we return the object that most developers and their code will be interested in: the instances. In instances reservation is availabl...
def remove_hook(self, name, func): ''' Remove a callback from a hook. ''' if name in self._hooks and func in self._hooks[name]: self._hooks[name].remove(func) return True
Remove a callback from a hook.
def perform_experiment(self, engine_list): """ Performs nearest neighbour recall experiments with custom vector data for all engines in the specified list. Returns self.result contains list of (recall, precision, search_time) tuple. All are the averaged values over all request v...
Performs nearest neighbour recall experiments with custom vector data for all engines in the specified list. Returns self.result contains list of (recall, precision, search_time) tuple. All are the averaged values over all request vectors. search_time is the average retrieval/search tim...
def add_cmd_method(self, name, method, argc=None, complete=None): """Adds a command to the command line interface loop. Parameters ---------- name : string The command. method : function(args) The function to execute when this command is issued. The argu...
Adds a command to the command line interface loop. Parameters ---------- name : string The command. method : function(args) The function to execute when this command is issued. The argument of the function is a list of space separated arguments to th...
def _filter_by_zoom(element=None, conf_string=None, zoom=None): """Return element only if zoom condition matches with config string.""" for op_str, op_func in [ # order of operators is important: # prematurely return in cases of "<=" or ">=", otherwise # _strip_zoom() cannot parse config...
Return element only if zoom condition matches with config string.
def _dump(self, tag, x, lo, hi): """Generate comparison results for a same-tagged range.""" for i in xrange(lo, hi): yield '%s %s' % (tag, x[i])
Generate comparison results for a same-tagged range.
def _get_offset(cmd): """Return the offset into the cmd based upon if it's a dictionary page or a data page.""" dict_offset = cmd.dictionary_page_offset data_offset = cmd.data_page_offset if dict_offset is None or data_offset < dict_offset: return data_offset return dict_offset
Return the offset into the cmd based upon if it's a dictionary page or a data page.
def retrieveAcknowledge(): """RETRIEVE ACKNOWLEDGE Section 9.3.21""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1d) # 00011101 packet = a / b return packet
RETRIEVE ACKNOWLEDGE Section 9.3.21
def downloadFile(self, filename, ispickle=False, athome=False): """ Downloads a single file from Redunda. :param str filename: The name of the file you want to download :param bool ispickle: Optional variable which tells if the file to be downloaded is a pickle; default is False. ...
Downloads a single file from Redunda. :param str filename: The name of the file you want to download :param bool ispickle: Optional variable which tells if the file to be downloaded is a pickle; default is False. :returns: returns nothing
def get_vnetwork_hosts_output_vnetwork_hosts_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_hosts = ET.Element("get_vnetwork_hosts") config = get_vnetwork_hosts output = ET.SubElement(get_vnetwork_hosts, "output") vnetw...
Auto Generated Code
def occurrences(coll, value=None, **options): """Return the occurrences of the elements in the collection :param coll: a collection :param value: a value in the collection :param options: an optional keyword used as a criterion to filter the values in the collection :returns: the f...
Return the occurrences of the elements in the collection :param coll: a collection :param value: a value in the collection :param options: an optional keyword used as a criterion to filter the values in the collection :returns: the frequency of the values in the collection as a diction...
def url_for(**options): '''Returns the url for the specified options''' url_parts = get_url_parts(**options) image_hash = hashlib.md5(b(options['image_url'])).hexdigest() url_parts.append(image_hash) return "/".join(url_parts)
Returns the url for the specified options
def find_declared_encoding(cls, markup, is_html=False, search_entire_document=False): """Given a document, tries to find its declared encoding. An XML encoding is declared at the beginning of the document. An HTML encoding is declared in a <meta> tag, hopefully near the beginning of th...
Given a document, tries to find its declared encoding. An XML encoding is declared at the beginning of the document. An HTML encoding is declared in a <meta> tag, hopefully near the beginning of the document.
def process_match(match, fixed_text, cur, cur_end): """Processes a single match in rules""" # Set our tools # -- Initial/default value for replace replace = True # -- Set check cursor depending on match['type'] if match['type'] == 'prefix': chk = cur - 1 else: # suffix ...
Processes a single match in rules
def get_forces(self, a): """Calculate atomic forces.""" f = np.zeros( [ len(a), 3 ], dtype=float ) for c in self.calcs: f += c.get_forces(a) return f
Calculate atomic forces.
def check_pypi_exists(dependencies): """Check if the indicated dependencies actually exists in pypi.""" for dependency in dependencies.get('pypi', []): logger.debug("Checking if %r exists in PyPI", dependency) try: exists = _pypi_head_package(dependency) except Exception as e...
Check if the indicated dependencies actually exists in pypi.
def _non_blocking_wrapper(self, method, *args, **kwargs): """Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first failed task.""" exceptions = [] def task_run(task): try: getattr(task, method)(*args, **kwargs) except Exception a...
Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first failed task.
def work(options): """The work functions""" # pylint: disable=too-many-locals record = get_record(options) _, mainv, dailyv, _, _, _, safebrowsingv, bytecodev = record.split(':') versions = {'main': mainv, 'daily': dailyv, 'safebrowsing': safebrowsingv, 'bytecode': by...
The work functions
def toggle_deriv(self, evt=None, value=None): "toggle derivative of data" if value is None: self.conf.data_deriv = not self.conf.data_deriv expr = self.conf.data_expr or '' if self.conf.data_deriv: expr = "deriv(%s)" % expr self.write_mess...
toggle derivative of data
def _set_tunnel(self, v, load=False): """ Setter method for tunnel, mapped from YANG variable /interface/tunnel (list) If this variable is read-only (config: false) in the source YANG file, then _set_tunnel is considered as a private method. Backends looking to populate this variable should do s...
Setter method for tunnel, mapped from YANG variable /interface/tunnel (list) If this variable is read-only (config: false) in the source YANG file, then _set_tunnel is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_tunnel() directly.
def build(self, root, schema): """ Build the syntax tree for kubectl command line """ if schema.get("subcommands") and schema["subcommands"]: for subcmd, childSchema in schema["subcommands"].items(): child = CommandTree(node=subcmd) child = self.build(child, c...
Build the syntax tree for kubectl command line