code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def prepare_data(fm, max_back, dur_cap=700): ''' Computes angle and length differences up to given order and deletes suspiciously long fixations. Input fm: Fixmat Fixmat for which to comput angle and length differences max_back: Int Computes delta angle and ampli...
Computes angle and length differences up to given order and deletes suspiciously long fixations. Input fm: Fixmat Fixmat for which to comput angle and length differences max_back: Int Computes delta angle and amplitude up to order max_back. dur_cap: Int ...
def register_on_message(self, msg_builder): """Registers protobuf message builders that this client wants to receive :param msg_builder: callable to create a protobuf message that this client wants to receive """ message = msg_builder() Log.debug("In register_on_message(): %s" % message.DESCRIPTOR....
Registers protobuf message builders that this client wants to receive :param msg_builder: callable to create a protobuf message that this client wants to receive
def data(self): """return stored data Returns: unpickled data """ try: bytestream = super(MimeData, self).data(self._mimeType).data() return pickle.loads(bytestream) except: raise
return stored data Returns: unpickled data
def angToPix(nside, lon, lat, nest=False): """ Input (lon, lat) in degrees instead of (theta, phi) in radians """ theta = np.radians(90. - lat) phi = np.radians(lon) return hp.ang2pix(nside, theta, phi, nest=nest)
Input (lon, lat) in degrees instead of (theta, phi) in radians
def run(data): """Proxy function to run the tool""" sample = data[0][0] work_dir = dd.get_work_dir(sample) out_dir = os.path.join(work_dir, "mirge") lib = _find_lib(sample) mirge = _find_mirge(sample) bowtie = _find_bowtie(sample) sps = dd.get_species(sample) species = SPS.get(sps, "...
Proxy function to run the tool
def reset(self): """Skip the next iteration and reset timer. """ if self._self_thread is not None: # Cancel currently scheduled call self._self_thread.cancel() self._self_thread = None # Schedule a new call self._self_thread = hub.spawn_after(s...
Skip the next iteration and reset timer.
def dKd_dVar(self, X, X2=None): """ Derivative of Kernel function wrt variance applied on inputs X and X2. In the stationary case there is an inner function depending on the distances from X to X2, called r. dKd_dVar(X, X2) = dKdVar_of_r((X-X2)**2) """ r = self._scaled_dist(X, X2) return self.dKdVar_of...
Derivative of Kernel function wrt variance applied on inputs X and X2. In the stationary case there is an inner function depending on the distances from X to X2, called r. dKd_dVar(X, X2) = dKdVar_of_r((X-X2)**2)
def destroy_volume(agent, role): """ Deletes the volumes on the specific agent for the role """ volumes = [] agent_id = agent['id'] reserved_resources_full = agent.get('reserved_resources_full', None) if not reserved_resources_full: # doesn't exist return True reserved_reso...
Deletes the volumes on the specific agent for the role
def _get_elements(self, source): """ Returns the list of HtmlElements for the source :param source: The source list to parse :type source: list :returns: A list of HtmlElements :rtype: list """ return list(chain(*[self.tree.xpath(xpath) for xpath in sourc...
Returns the list of HtmlElements for the source :param source: The source list to parse :type source: list :returns: A list of HtmlElements :rtype: list
def setItemData(self, treeItem, column, value, role=Qt.EditRole): """ Sets the role data for the item at index to value. """ if role == Qt.CheckStateRole: if column != self.COL_VALUE: return False else: logger.debug("Setting check state (co...
Sets the role data for the item at index to value.
def make_alias(self, entry): """ Make this variable an alias of another one """ entry.add_alias(self) self.alias = entry self.scope = entry.scope # Local aliases can be "global" (static) self.byref = entry.byref self.offset = entry.offset self.addr = entr...
Make this variable an alias of another one
def selected_subcategory(self): """Obtain the subcategory selected by user. :returns: Metadata of the selected subcategory. :rtype: dict, None """ item = self.lstSubcategories.currentItem() try: return definition(item.data(QtCore.Qt.UserRole)) except ...
Obtain the subcategory selected by user. :returns: Metadata of the selected subcategory. :rtype: dict, None
def packages(ciprcfg, env, opts, console): """ List installed packages for this project """ for name, source in ciprcfg.packages.items(): console.normal('- %s' % name) if opts.long_details: console.normal(' - directory: %s' % path.join(env.package_dir, name)) co...
List installed packages for this project
def get_serializer_fields(self, path, method, view, version=None, method_func=None): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method in ('PUT', 'PATCH', 'POST'): location = 'f...
Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class.
def lambdafan(func): """simple decorator that will auto fan out async style in lambda. outside of lambda, this will invoke synchrously. """ if 'AWS_LAMBDA_FUNCTION_NAME' not in os.environ: return func @functools.wraps(func) def scaleout(*args, **kw): client = boto3.client('lamb...
simple decorator that will auto fan out async style in lambda. outside of lambda, this will invoke synchrously.
def backends(): '''List available backends''' log.info('Available backends:') for backend in actions.list_backends(): log.info('%s (%s)', backend.name, backend.display_name or backend.name)
List available backends
def on(self, image): """ Project keypoints from one image to a new one. Parameters ---------- image : ndarray or tuple of int New image onto which the keypoints are to be projected. May also simply be that new image's shape tuple. Returns ...
Project keypoints from one image to a new one. Parameters ---------- image : ndarray or tuple of int New image onto which the keypoints are to be projected. May also simply be that new image's shape tuple. Returns ------- keypoints : imgaug.Keypo...
def save(self, logMessage=None): """Save to Fedora any parts of this object that have been modified (including object profile attributes such as :attr:`label`, :attr:`owner`, or :attr:`state`, and any changes to datastream content or datastream properties). If a failure occurs a...
Save to Fedora any parts of this object that have been modified (including object profile attributes such as :attr:`label`, :attr:`owner`, or :attr:`state`, and any changes to datastream content or datastream properties). If a failure occurs at any point on saving any of the parts of th...
def get_array(self): """Returns the array arguments for the job; usually a string.""" # In python 2, the command line is unicode, which needs to be converted to string before pickling; # In python 3, the command line is bytes, which can be pickled directly return loads(self.array_string) if isinstance(s...
Returns the array arguments for the job; usually a string.
def get_x(): ''' Get current X keyboard setting CLI Example: .. code-block:: bash salt '*' keyboard.get_x ''' cmd = 'setxkbmap -query | grep layout' out = __salt__['cmd.run'](cmd, python_shell=True).split(':') return out[1].strip()
Get current X keyboard setting CLI Example: .. code-block:: bash salt '*' keyboard.get_x
def collect_variables(self, selections) -> None: """Apply method |ChangeItem.collect_variables| of the base class |ChangeItem| and also apply method |ExchangeItem.insert_variables| of class |ExchangeItem| to collect the relevant base variables handled by the devices of the given |Selecti...
Apply method |ChangeItem.collect_variables| of the base class |ChangeItem| and also apply method |ExchangeItem.insert_variables| of class |ExchangeItem| to collect the relevant base variables handled by the devices of the given |Selections| object. >>> from hydpy.core.examples import pr...
def _acl_changes(name, id=None, type=None, rules=None, consul_url=None, token=None): ''' return True if the acl need to be update, False if it doesn't need to be update ''' info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url) if info['res'] and info['data'][0]['Name'] !=...
return True if the acl need to be update, False if it doesn't need to be update
def contract(self): '''Contract this ``Node`` by directly connecting its children to its parent''' if self.is_root(): return for c in self.children: if self.edge_length is not None and c.edge_length is not None: c.edge_length += self.edge_length ...
Contract this ``Node`` by directly connecting its children to its parent
def remove_entry(self, fs_entry): """Removes an FSEntry object from this METS document. Any children of this FSEntry will also be removed. This will be removed as a child of it's parent, if any. :param metsrw.mets.FSEntry fs_entry: FSEntry to remove from the METS """ tr...
Removes an FSEntry object from this METS document. Any children of this FSEntry will also be removed. This will be removed as a child of it's parent, if any. :param metsrw.mets.FSEntry fs_entry: FSEntry to remove from the METS
def quote_header_value(value, extra_chars='', allow_token=True): """Quote a header value if necessary. :param value: the value to quote. :param extra_chars: a list of extra characters to skip quoting. :param allow_token: if this is enabled token values are returned unchanged. """ value ...
Quote a header value if necessary. :param value: the value to quote. :param extra_chars: a list of extra characters to skip quoting. :param allow_token: if this is enabled token values are returned unchanged.
def js_divergence(p, q): """Compute the Jensen-Shannon Divergence between two discrete distributions. Parameters ---------- p : np.array probability mass array (sums to 1) q : np.array probability mass array (sums to 1) Returns ------- js_div : float js divergen...
Compute the Jensen-Shannon Divergence between two discrete distributions. Parameters ---------- p : np.array probability mass array (sums to 1) q : np.array probability mass array (sums to 1) Returns ------- js_div : float js divergence between the two distrubtions
def collinear(p1, p2, p3=None, tolerance=0.25): """ Checks if the three points p1, p2 and p3 are collinear or not within a given tolerance. The collinearity is checked by computing the area of the triangle defined by the three points p1, p2 and p3. If the area of this triangle is less than (tolerance x ...
Checks if the three points p1, p2 and p3 are collinear or not within a given tolerance. The collinearity is checked by computing the area of the triangle defined by the three points p1, p2 and p3. If the area of this triangle is less than (tolerance x largest_triangle), then the three points are considered coll...
def smooth_fwhm(self, fwhm): """ Set a smoothing Gaussian kernel given its FWHM in mm. """ if fwhm != self._smooth_fwhm: self._is_data_smooth = False self._smooth_fwhm = fwhm
Set a smoothing Gaussian kernel given its FWHM in mm.
def _auth_stage1(self): """Do the first stage (<iq type='get'/>) of legacy ("plain" or "digest") authentication. [client only]""" iq=Iq(stanza_type="get") q=iq.new_query("jabber:iq:auth") q.newTextChild(None,"username",to_utf8(self.my_jid.node)) q.newTextChild(No...
Do the first stage (<iq type='get'/>) of legacy ("plain" or "digest") authentication. [client only]
def get_by_flat_key(i): """ Input: { dict - dictionary key - flat key } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 value - v...
Input: { dict - dictionary key - flat key } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 value - value or None, if doesn't exist ...
async def _reload_message(self): """ Re-fetches this message to reload the sender and chat entities, along with their input versions. """ try: chat = await self.get_input_chat() if self.is_channel else None msg = await self._client.get_messages(chat, ids=s...
Re-fetches this message to reload the sender and chat entities, along with their input versions.
def localDeformationVsBPS(dnaRef, bpRef, dnaProbe, bpProbe, parameter, err_type='std', bp_range=True, merge_bp=1, merge_method='mean', masked=False, tool='gmx analyze'): """To calculate deformation of local parameters in probe DNA with respect to a reference DNA as a function of the bp/s. ...
To calculate deformation of local parameters in probe DNA with respect to a reference DNA as a function of the bp/s. .. note:: Deformation = Reference_DNA(parameter) - Probe_DNA(parameter) .. warning:: Number of segments/bp/bps should match between probe and reference DNA. .. warning:: To cal...
def runcp_producer_loop( lightcurve_list, input_queue, input_bucket, result_queue, result_bucket, pfresult_list=None, runcp_kwargs=None, process_list_slice=None, purge_queues_when_done=False, delete_queues_when_done=False, download_...
This sends checkplot making tasks to the input queue and monitors the result queue for task completion. Parameters ---------- lightcurve_list : str or list of str This is either a string pointing to a file containing a list of light curves filenames to process or the list itself. The n...
def urlencode(query): """Encode string to be used in urls (percent encoding). :param query: string to be encoded :type query: str :return: urlencoded string :rtype: str :Example: >>> urlencode('pekná líščička') 'pekn%C3%A1%20l%C3%AD%C5%A1%C4%8Di%C4%8Dka' """ if hasattr(...
Encode string to be used in urls (percent encoding). :param query: string to be encoded :type query: str :return: urlencoded string :rtype: str :Example: >>> urlencode('pekná líščička') 'pekn%C3%A1%20l%C3%AD%C5%A1%C4%8Di%C4%8Dka'
def post_id_backpage_groups(): """ Get a dictionary of Backpage city names mapped to their posting ID group (ex: groups['buffalo']: 'upstateny') Returns: dictionary of Backpage city names mapped to their posting ID group """ city_bp_groups = {} with open('dataFiles/city_bp_groups.csv', 'rU') as csvfile...
Get a dictionary of Backpage city names mapped to their posting ID group (ex: groups['buffalo']: 'upstateny') Returns: dictionary of Backpage city names mapped to their posting ID group
def wrap(cls, public_key, algorithm): """ Wraps a public key in a PublicKeyInfo structure :param public_key: A byte string or Asn1Value object of the public key :param algorithm: A unicode string of "rsa" :return: A PublicKeyInfo object ...
Wraps a public key in a PublicKeyInfo structure :param public_key: A byte string or Asn1Value object of the public key :param algorithm: A unicode string of "rsa" :return: A PublicKeyInfo object
def decompile(ast, indentation=4, line_length=100, starting_indentation=0): """Decompiles an AST into Python code. Arguments: - ast: code to decompile, using AST objects as generated by the standard library ast module - indentation: indentation level of lines - line_length: if lines become longer t...
Decompiles an AST into Python code. Arguments: - ast: code to decompile, using AST objects as generated by the standard library ast module - indentation: indentation level of lines - line_length: if lines become longer than this length, ast_decompiler will try to break them up (but it will not ne...
def page(self, end=values.unset, start=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of DataSessionInstance records from the API. Request is executed immediately :param datetime end: The end :par...
Retrieve a single page of DataSessionInstance records from the API. Request is executed immediately :param datetime end: The end :param datetime start: The start :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for cl...
def enrichr(gene_list, gene_sets, organism='human', description='', outdir='Enrichr', background='hsapiens_gene_ensembl', cutoff=0.05, format='pdf', figsize=(8,6), top_term=10, no_plot=False, verbose=False): """Enrichr API. :param gene_list: Flat file with list of genes, one gene id per...
Enrichr API. :param gene_list: Flat file with list of genes, one gene id per row, or a python list object :param gene_sets: Enrichr Library to query. Required enrichr library name(s). Separate each name by comma. :param organism: Enrichr supported organism. Select from (human, mouse, yeast, fly, fish, worm...
def comp_pipe_info(op): """Returns (direction, star) where direction is 'forwards' or 'backwards'.""" if op == "..>": return "forwards", False elif op == "<..": return "backwards", False elif op == "..*>": return "forwards", True elif op == "<*..": return "backwards",...
Returns (direction, star) where direction is 'forwards' or 'backwards'.
def validate_answer(self, value): """ Check that the answer is JSON-serializable and not too long. """ # Check that the answer is JSON-serializable try: serialized = json.dumps(value) except (ValueError, TypeError): raise serializers.ValidationErro...
Check that the answer is JSON-serializable and not too long.
def page_templates_loading_check(app_configs, **kwargs): """ Check if any page template can't be loaded. """ errors = [] for page_template in settings.get_page_templates(): try: loader.get_template(page_template[0]) except template.TemplateDoesNotExist: errors.append...
Check if any page template can't be loaded.
def get_path(src): # pragma: no cover """ Prompts the user to input a local path. :param src: github repository name :return: Absolute local path """ res = None while not res: if res is False: print(colored('You must provide a path to an existing directory!', 'red')) ...
Prompts the user to input a local path. :param src: github repository name :return: Absolute local path
def psychrometrics (Tdb_in, w_in, P): """ Modified version of Psychometrics by Tea Zakula MIT Building Technology Lab Input: Tdb_in, w_in, P Output: Tdb, w, phi, h, Tdp, v where: Tdb_in = [K] dry bulb temperature w_in = [kgv/kgda] Humidity Ratio P = [P] Atmospheric Station Pressure ...
Modified version of Psychometrics by Tea Zakula MIT Building Technology Lab Input: Tdb_in, w_in, P Output: Tdb, w, phi, h, Tdp, v where: Tdb_in = [K] dry bulb temperature w_in = [kgv/kgda] Humidity Ratio P = [P] Atmospheric Station Pressure Tdb: [C] dry bulb temperature w: [kgv/kgd...
def parse_job_id(self, output): """Take the output of the submit command and return the job id.""" m = self.job_id_regexp.search(output) if m is not None: job_id = m.group() else: raise LauncherError("Job id couldn't be determined: %s" % output) self.job_i...
Take the output of the submit command and return the job id.
def solid(name=None, inputs=None, outputs=None, config_field=None, description=None): '''(decorator) Create a solid with specified parameters. This shortcut simplifies the core solid API by exploding arguments into kwargs of the transform function and omitting additional parameters when they are not needed...
(decorator) Create a solid with specified parameters. This shortcut simplifies the core solid API by exploding arguments into kwargs of the transform function and omitting additional parameters when they are not needed. Parameters are otherwise as in the core API, :py:class:`SolidDefinition`. The deco...
def wait_for_zone_op(access_token, project, zone, name, interval=1.0): """Wait until a zone operation is finished. TODO: docstring""" assert isinstance(interval, (int, float)) assert interval >= 0.1 status = 'RUNNING' progress = 0 LOGGER.info('Waiting for zone operation "%s" to finis...
Wait until a zone operation is finished. TODO: docstring
def build(self, update=True): """ Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page number is part of the query string and not the URL path """ query_str = "?page={}".format(self.page) if s...
Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page number is part of the query string and not the URL path
def find_types(self, site=None, match=r'^(?!lastfile|spectro|\.).*'): """Return the list of known data types. This is just the basename of each FFL file found in the FFL directory (minus the ``.ffl`` extension) """ self._find_paths() types = [tag for (site_, tag) in self...
Return the list of known data types. This is just the basename of each FFL file found in the FFL directory (minus the ``.ffl`` extension)
def read(path='', mode='r', record_size=None, record_seperator=None, offset=0, autostrip=False): ''' instead of writing open('file').read(), this is much more efficient and has some extra goodies ''' assert isinstance(path, str), 'path needs to be a string, not: {}'.format(repr(path)) assert isinstance(mode...
instead of writing open('file').read(), this is much more efficient and has some extra goodies
def open_channel(self): """ Open a new channel on this connection. This method is a :ref:`coroutine <coroutine>`. :return: The new :class:`Channel` object. """ if self._closing: raise ConnectionClosed("Closed by application") if self.closed.done(): ...
Open a new channel on this connection. This method is a :ref:`coroutine <coroutine>`. :return: The new :class:`Channel` object.
def result(self, timeout=None): """Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. Returns: The result of th...
Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. Returns: The result of the call that the future represents. ...
def clear(self): """Reset this PeerGroup. This closes all connections to all known peers and forgets about these peers. :returns: A Future that resolves with a value of None when the operation has finished """ try: for peer in self._p...
Reset this PeerGroup. This closes all connections to all known peers and forgets about these peers. :returns: A Future that resolves with a value of None when the operation has finished
def _run(self, device_url, code): """ Thanks: https://gist.github.com/mosquito/e638dded87291d313717 """ try: print("DEBUG: run code\n%s" % code) env = os.environ.copy() env['UIAUTOMATOR_DEBUG'] = 'true' if device_url and device_url != 'def...
Thanks: https://gist.github.com/mosquito/e638dded87291d313717
def get(self, bug_number): """ Get a bug from Bugzilla. If there is a login token created during object initialisation it will be part of the query string passed to Bugzilla :param bug_number: Bug Number that will be searched. If found will ...
Get a bug from Bugzilla. If there is a login token created during object initialisation it will be part of the query string passed to Bugzilla :param bug_number: Bug Number that will be searched. If found will return a Bug object. >>> bugz...
def add_partition(self, p): """Add a partition identity as a child of a dataset identity.""" if not self.partitions: self.partitions = {} self.partitions[p.vid] = p
Add a partition identity as a child of a dataset identity.
def dot(self, other): """ Compute the dot product of two Vectors. We support (Numpy array, list, SparseVector, or SciPy sparse) and a target NumPy array that is either 1- or 2-dimensional. Equivalent to calling numpy.dot of the two vectors. >>> dense = DenseVector(array....
Compute the dot product of two Vectors. We support (Numpy array, list, SparseVector, or SciPy sparse) and a target NumPy array that is either 1- or 2-dimensional. Equivalent to calling numpy.dot of the two vectors. >>> dense = DenseVector(array.array('d', [1., 2.])) >>> dense.do...
def _restore_seq_field_pickle(checked_class, item_type, data): """Unpickling function for auto-generated PVec/PSet field types.""" type_ = _seq_field_types[checked_class, item_type] return _restore_pickle(type_, data)
Unpickling function for auto-generated PVec/PSet field types.
def _get_exceptions_db(self): """Return a list of dictionaries suitable to be used with ptrie module.""" template = "{extype} ({exmsg}){raised}" if not self._full_cname: # When full callable name is not used the calling path is # irrelevant and there is no function associ...
Return a list of dictionaries suitable to be used with ptrie module.
def is_open_now(location=None, attr=None): """ Returns False if the location is closed, or the OpeningHours object to show the location is currently open. Same as `is_open` but passes `now` to `utils.is_open` to bypass `get_now()`. """ obj = utils.is_open(location, now=datetime.datetime.now()) ...
Returns False if the location is closed, or the OpeningHours object to show the location is currently open. Same as `is_open` but passes `now` to `utils.is_open` to bypass `get_now()`.
def split_page_artid(page_artid): """Split page_artid into page_start/end and artid.""" page_start = None page_end = None artid = None if not page_artid: return None, None, None # normalize unicode dashes page_artid = unidecode(six.text_type(page_artid)) if '-' in page_artid: ...
Split page_artid into page_start/end and artid.
def handle_market_open(self, session_label, data_portal): """Handles the start of each session. Parameters ---------- session_label : Timestamp The label of the session that is about to begin. data_portal : DataPortal The current data portal. """ ...
Handles the start of each session. Parameters ---------- session_label : Timestamp The label of the session that is about to begin. data_portal : DataPortal The current data portal.
def distance_to_point(self, p): '''Returns the distance from the point to the interval. Zero if the point lies inside the interval.''' if self.start <= p <= self.end: return 0 else: return min(abs(self.start - p), abs(self.end - p))
Returns the distance from the point to the interval. Zero if the point lies inside the interval.
def scale_in(self, blocks=0, machines=0, strategy=None): ''' Scale in resources ''' count = 0 instances = self.client.servers.list() for instance in instances[0:machines]: print("Deleting : ", instance) instance.delete() count += 1 ret...
Scale in resources
def grant_qualification(self, qualification_request_id, integer_value=1): """TODO: Document.""" params = {'QualificationRequestId' : qualification_request_id, 'IntegerValue' : integer_value} return self._process_request('GrantQualification', params)
TODO: Document.
def get_api_key(client, username, secret): """Attempts API-Key and password auth to get an API key. This will also generate an API key if one doesn't exist """ # Try to use a client with username/api key if len(secret) == 64: try: client['Account'].getCurrentUser() ...
Attempts API-Key and password auth to get an API key. This will also generate an API key if one doesn't exist
def divide_chain(self, chain=0): """ Returns a ChainConsumer instance containing all the walks of a given chain as individual chains themselves. This method might be useful if, for example, your chain was made using MCMC with 4 walkers. To check the sampling of all 4 walkers agr...
Returns a ChainConsumer instance containing all the walks of a given chain as individual chains themselves. This method might be useful if, for example, your chain was made using MCMC with 4 walkers. To check the sampling of all 4 walkers agree, you could call this to get a ChainConsume...
def _generate_doxygen(doxygen_input): ''' This method executes doxygen based off of the specified input. By the time this method is executed, it is assumed that Doxygen is intended to be run in the **current working directory**. Search for ``returnPath`` in the implementation of :func:`~exhale.con...
This method executes doxygen based off of the specified input. By the time this method is executed, it is assumed that Doxygen is intended to be run in the **current working directory**. Search for ``returnPath`` in the implementation of :func:`~exhale.configs.apply_sphinx_configurations` for handling of ...
def _polar_to_cartesian(cx, cy, r, theta): """ :param cx: X coord of circle :param cy: Y coord of circle :param r: Radius of circle :param theta: Degrees from vertical, clockwise, in radians :return: (x, y) """ return cx - r * math.sin(theta), cy - r * mat...
:param cx: X coord of circle :param cy: Y coord of circle :param r: Radius of circle :param theta: Degrees from vertical, clockwise, in radians :return: (x, y)
def format_cmd_output(cmd, output, name): """format command output for docs""" formatted = '.. code-block:: console\n\n' formatted += ' (venv)$ {c}\n'.format(c=cmd) lines = output.split("\n") if name != 'help': for idx, line in enumerate(lines): if len(line) > 100: ...
format command output for docs
def vote(cls): """Cast a public vote for this comic.""" url = configuration.VoteUrl + 'count/' uid = get_system_uid() data = {"name": cls.getName().replace('/', '_'), "uid": uid} page = urlopen(url, cls.session, data=data) return page.text
Cast a public vote for this comic.
def nonlinear_optimization_uniform( X, cells, tol, max_num_steps, verbose=False, step_filename_format=None, callback=None, ): """Optimal Delaunay Triangulation smoothing. This method minimizes the energy E = int_Omega |u_l(x) - u(x)| rho(x) dx where u(x) = ||x||^2, u_l...
Optimal Delaunay Triangulation smoothing. This method minimizes the energy E = int_Omega |u_l(x) - u(x)| rho(x) dx where u(x) = ||x||^2, u_l is its piecewise linear nodal interpolation and rho is the density. Since u(x) is convex, u_l >= u everywhere and u_l(x) = sum_i phi_i(x) u(x_i) ...
def workflow_before_validate(self): """This function transposes values from the provided file into the ARImport object's fields, and checks for invalid values. If errors are found: - Validation transition is aborted. - Errors are stored on object and displayed to user. ...
This function transposes values from the provided file into the ARImport object's fields, and checks for invalid values. If errors are found: - Validation transition is aborted. - Errors are stored on object and displayed to user.
def export_cmd_options(self, options_override=None, standalone=False): """ Override! :return: """ cmd_options = super(MongodServer, self).export_cmd_options( options_override=options_override) # reset some props to exporting vals cmd_options['dbpa...
Override! :return:
def shift(self, x=0, y=0): """ Move the keypoints around on an image. Parameters ---------- x : number, optional Move each keypoint by this value on the x axis. y : number, optional Move each keypoint by this value on the y axis. Returns...
Move the keypoints around on an image. Parameters ---------- x : number, optional Move each keypoint by this value on the x axis. y : number, optional Move each keypoint by this value on the y axis. Returns ------- out : KeypointsOnImage...
def send_agent_report(self, report, context): """Send the agent report via RPC.""" try: self.state_rpc.report_state(context, report, self.use_call) report.pop('start_flag', None) self.use_call = False LOG.debug("Send agent report successfully completed") ...
Send the agent report via RPC.
def get_system_per_cpu_times(): """Return a list of namedtuple representing the CPU times for every CPU available on the system. """ cpus = [] f = open('/proc/stat', 'r') # get rid of the first line who refers to system wide CPU stats try: f.readline() for line in f.readlines...
Return a list of namedtuple representing the CPU times for every CPU available on the system.
def delete(self, endpoint='', url='', params=None, data=None): """Perform a get for a json API endpoint. :param string endpoint: Target endpoint. (Optional). :param string url: Override the endpoint and provide the full url (eg for pagination). (Optional). :param dict params: Provide pa...
Perform a get for a json API endpoint. :param string endpoint: Target endpoint. (Optional). :param string url: Override the endpoint and provide the full url (eg for pagination). (Optional). :param dict params: Provide parameters to pass to the request. (Optional). :param dict data: Dat...
def pairs(self): """ Convert an object into a list of `[key, value]` pairs. """ keys = self._clean.keys() pairs = [] for key in keys: pairs.append([key, self.obj[key]]) return self._wrap(pairs)
Convert an object into a list of `[key, value]` pairs.
def list_group_members(self, name): """ Get the members of a group. Args: name (string): Name of group to query. Returns: (list[string]): List of member names. Raises: requests.HTTPError on failure. """ self.project_service.s...
Get the members of a group. Args: name (string): Name of group to query. Returns: (list[string]): List of member names. Raises: requests.HTTPError on failure.
def total_power(self): """Total power used. """ power = self.average_current * self.voltage return round(power, self.sr)
Total power used.
def stop(name, lbn, target, profile='default', tgt_type='glob'): ''' .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Stop the named worker from the lbn load balancers at the targeted minions The worker wo...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Stop the named worker from the lbn load balancers at the targeted minions The worker won't get any traffic from the lbn Example: .. code-block:: yaml ...
def _port_scan_tcp(self, port): """Scan the (TCP) port structure (dict) and update the status key.""" ret = None # Create and configure the scanning socket try: socket.setdefaulttimeout(port['timeout']) _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
Scan the (TCP) port structure (dict) and update the status key.
def active_scan(zap_helper, url, scanners, recursive, context_name, user_name): """ Run an Active Scan against a URL. The URL to be scanned must be in ZAP's site tree, i.e. it should have already been opened using the open-url command or found by running the spider command. """ console.info('Ru...
Run an Active Scan against a URL. The URL to be scanned must be in ZAP's site tree, i.e. it should have already been opened using the open-url command or found by running the spider command.
def parse_expression(self): """Parse a template expression starting at ``pos``. Resulting components (Unicode strings, Symbols, and Calls) are added to the ``parts`` field, a list. The ``pos`` field is updated to be the next character after the expression. """ # Append c...
Parse a template expression starting at ``pos``. Resulting components (Unicode strings, Symbols, and Calls) are added to the ``parts`` field, a list. The ``pos`` field is updated to be the next character after the expression.
def selections(self) -> selectiontools.Selections: """The |Selections| object defined for the respective `reader` or `writer` element of the actual XML file. ToDo If the `reader` or `writer` element does not define a special selections element, the general |XMLInterface.selections| elem...
The |Selections| object defined for the respective `reader` or `writer` element of the actual XML file. ToDo If the `reader` or `writer` element does not define a special selections element, the general |XMLInterface.selections| element of |XMLInterface| is used. >>> from hydpy...
def _process_features(self, limit=None): """ This module provides information for the intrinsic and extrinsic genotype features of zebrafish. All items here are 'alterations', and are therefore instances. sequence alteration ID, SO type, abbreviation, and relationship to ...
This module provides information for the intrinsic and extrinsic genotype features of zebrafish. All items here are 'alterations', and are therefore instances. sequence alteration ID, SO type, abbreviation, and relationship to the affected gene, with the gene's ID, symbol, and S...
def startup_walk_for_missed_files(self): """Check xlog and xlog_incoming directories for files that receivexlog has received but not yet compressed as well as the files we have compressed but not yet uploaded and process them.""" for site in self.config["backup_sites"]: compressed_xl...
Check xlog and xlog_incoming directories for files that receivexlog has received but not yet compressed as well as the files we have compressed but not yet uploaded and process them.
def MDS(D, dim, method='simple', theta=False): """ recover points from euclidean distance matrix using classic MDS algorithm. """ N = D.shape[0] if method == 'simple': d1 = D[0, :] # buf_ = d1 * np.ones([1, N]).T + (np.ones([N, 1]) * d1).T buf_ = np.broadcast_to(d1, D.shape) + n...
recover points from euclidean distance matrix using classic MDS algorithm.
def get(self, key): """ Retrieve an item from the cache by key. :param key: The cache key :type key: str :return: The cache value """ value = self._redis.get(self._prefix + key) if value is not None: return self.unserialize(value)
Retrieve an item from the cache by key. :param key: The cache key :type key: str :return: The cache value
def Jpjmcoeff(ls, m, shift=False) -> sympy.Expr: r'''Eigenvalue of the $\Op{J}_{+}$ (:class:`Jplus`) operator .. math:: \Op{J}_{+} \ket{s, m} = \sqrt{s (s+1) - m (m+1)} \ket{s, m} where the multiplicity $s$ is implied by the size of the Hilbert space `ls`: there are $2s+1$ eigenstates with $m...
r'''Eigenvalue of the $\Op{J}_{+}$ (:class:`Jplus`) operator .. math:: \Op{J}_{+} \ket{s, m} = \sqrt{s (s+1) - m (m+1)} \ket{s, m} where the multiplicity $s$ is implied by the size of the Hilbert space `ls`: there are $2s+1$ eigenstates with $m = -s, -s+1, \dots, s$. Args: ls (LocalS...
def add_n_smooth(smooth_input, smooth_time, initial_value, order, subs, subscript_dict): """Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- smooth_input: <string> Reference to the model component that is the ...
Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- smooth_input: <string> Reference to the model component that is the input to the smoothing function smooth_time: <string> Can be a number (in s...
def handle(self, handler): """ Registers a handler. The handler can be transmitted together with two arguments as a list or dictionary. The arguments are: memoize if True, the execution result will be cached in self.memoize timeout will allocate...
Registers a handler. The handler can be transmitted together with two arguments as a list or dictionary. The arguments are: memoize if True, the execution result will be cached in self.memoize timeout will allocate a predefined time interval for the exec...
def header(self, text, level, raw=None): """Rendering header/heading tags like ``<h1>`` ``<h2>``. :param text: rendered text content for the header. :param level: a number for the header level, for example: 1. :param raw: raw text content of the header. """ return '\n{0}...
Rendering header/heading tags like ``<h1>`` ``<h2>``. :param text: rendered text content for the header. :param level: a number for the header level, for example: 1. :param raw: raw text content of the header.
def load_clubs(self): """Fetches the MAL character clubs page and sets the current character's clubs attributes. :rtype: :class:`.Character` :return: Current character object. """ character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(...
Fetches the MAL character clubs page and sets the current character's clubs attributes. :rtype: :class:`.Character` :return: Current character object.
def SendReply(self, rdf_value=None, request_id=None, response_id=None, session_id="W:0", message_type=None, name=None, require_fastpoll=None, ttl=None, blocking=True, ...
Send the protobuf to the server. Args: rdf_value: The RDFvalue to return. request_id: The id of the request this is a response to. response_id: The id of this response. session_id: The session id of the flow. message_type: The contents of this message, MESSAGE, STATUS or RDF_V...
def videos(self, **kwargs): """ Get the videos that have been added to a TV season (trailers, teasers, etc...). Args: language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._g...
Get the videos that have been added to a TV season (trailers, teasers, etc...). Args: language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API.
def run(self): """Run command.""" files = self.__zipped_files_data hashes = {} icons = {} # Read icons.json (from the webfont zip download) data = json.loads(files['icons.json']) # Group icons by style, since not all icons exist for all styles: for icon,...
Run command.
def filename_formatters(self, data, row): """ Returns a dict containing the various filename formatter values Values are gotten from the vaping data message as well as the currently processed row in the message - `data`: vaping message - `row`: vaping message data row ...
Returns a dict containing the various filename formatter values Values are gotten from the vaping data message as well as the currently processed row in the message - `data`: vaping message - `row`: vaping message data row
def get_list(client, list_id): ''' Gets the given list ''' endpoint = '/'.join([client.api.Endpoints.LISTS, str(list_id)]) response = client.authenticated_request(endpoint) return response.json()
Gets the given list