code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_corpus_path(name: str) -> [str, None]: """ Get corpus path :param string name: corpus name """ db = TinyDB(corpus_db_path()) temp = Query() if len(db.search(temp.name == name)) > 0: path = get_full_data_path(db.search(temp.name == name)[0]["file"]) db.close() ...
Get corpus path :param string name: corpus name
def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3): """ Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matr...
Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: opt...
def post(self, url, headers=None, params=None, **kwargs): """Send a JSON POST request with the given request headers, additional URL query parameters, and the given JSON in the request body. The extra query parameters are merged with any which already exist in the URL. The 'json' and '...
Send a JSON POST request with the given request headers, additional URL query parameters, and the given JSON in the request body. The extra query parameters are merged with any which already exist in the URL. The 'json' and 'data' parameters may not both be given. Args: ur...
def is_dtype(cls, dtype): """Check if we match 'dtype'. Parameters ---------- dtype : object The object to check. Returns ------- is_dtype : bool Notes ----- The default implementation is True if 1. ``cls.construct_f...
Check if we match 'dtype'. Parameters ---------- dtype : object The object to check. Returns ------- is_dtype : bool Notes ----- The default implementation is True if 1. ``cls.construct_from_string(dtype)`` is an instance ...
def start(self): """ Prepare the server to start serving connections. Configure the server socket handler and establish a TLS wrapping socket from which all client connections descend. Bind this TLS socket to the specified network address for the server. Raises: ...
Prepare the server to start serving connections. Configure the server socket handler and establish a TLS wrapping socket from which all client connections descend. Bind this TLS socket to the specified network address for the server. Raises: NetworkingError: Raised if the T...
def combining_search(self): """ Searching the path for combining the pair. """ start = ( self.get_pair(), ( self.cube["L"], self.cube["U"], self.cube["F"], self.cube["D"], self.cu...
Searching the path for combining the pair.
def run_procedure(self, process_number, std_vs_mfg, params=''): """ Initiate a C1219 procedure, the request is written to table 7 and the response is read from table 8. :param int process_number: The numeric procedure identifier (0 <= process_number <= 2047). :param bool std_vs_mfg: Whether the procedure is ...
Initiate a C1219 procedure, the request is written to table 7 and the response is read from table 8. :param int process_number: The numeric procedure identifier (0 <= process_number <= 2047). :param bool std_vs_mfg: Whether the procedure is manufacturer specified or not. True is manufacturer specified. :pa...
def _nonzero(self): """ Equivalent numpy's nonzero but returns a tuple of Varibles. """ # TODO we should replace dask's native nonzero # after https://github.com/dask/dask/issues/1076 is implemented. nonzeros = np.nonzero(self.data) return tuple(Variable((dim), nz) for nz, dim ...
Equivalent numpy's nonzero but returns a tuple of Varibles.
def println(msg): """ Convenience function to print messages on a single line in the terminal """ sys.stdout.write(msg) sys.stdout.flush() sys.stdout.write('\x08' * len(msg)) sys.stdout.flush()
Convenience function to print messages on a single line in the terminal
def get_views_traffic(self, per=github.GithubObject.NotSet): """ :calls: `GET /repos/:owner/:repo/traffic/views <https://developer.github.com/v3/repos/traffic/>`_ :param per: string, must be one of day or week, day by default :rtype: None or list of :class:`github.View.View` """ ...
:calls: `GET /repos/:owner/:repo/traffic/views <https://developer.github.com/v3/repos/traffic/>`_ :param per: string, must be one of day or week, day by default :rtype: None or list of :class:`github.View.View`
async def delete(self, turn_context: TurnContext) -> None: """ Delete any state currently stored in this state scope. :param turn_context: The context object for this turn. :return: None """ if turn_context == None: raise TypeError('BotState.delete():...
Delete any state currently stored in this state scope. :param turn_context: The context object for this turn. :return: None
def dry_run_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path serialization_dir = args.serialization_dir overrides = args.overrides params = Params.from_file(parameter_path, overrides) dry_run_fr...
Just converts from an ``argparse.Namespace`` object to params.
def _compute_ll(self): """ m._compute_ll() -- [utility] Compute the log-likelihood matrix from the count matrix """ self.fracs = [] self.logP = [] self.ll = [] for i in range(self.width): Dll = {'A': 0, 'C': 0, 'T': 0, 'G': 0} Df = {...
m._compute_ll() -- [utility] Compute the log-likelihood matrix from the count matrix
def set_options(self, **kw): r"""Set Parser options. .. seealso:: ``kw`` argument have the same meaning as in :func:`lazyxml.loads` """ for k, v in kw.iteritems(): if k in self.__options: self.__options[k] = v
r"""Set Parser options. .. seealso:: ``kw`` argument have the same meaning as in :func:`lazyxml.loads`
def create_job_flow(self, job_flow_overrides): """ Creates a job flow using the config from the EMR connection. Keys of the json extra hash may have the arguments of the boto3 run_job_flow method. Overrides for this config may be passed as the job_flow_overrides. """ ...
Creates a job flow using the config from the EMR connection. Keys of the json extra hash may have the arguments of the boto3 run_job_flow method. Overrides for this config may be passed as the job_flow_overrides.
def check_py(self, version, name, original, loc, tokens): """Check for Python-version-specific syntax.""" internal_assert(len(tokens) == 1, "invalid " + name + " tokens", tokens) if self.target_info < get_target_info(version): raise self.make_err(CoconutTargetError, "found Python " +...
Check for Python-version-specific syntax.
def default_sort_key(item, order=None): """Return a key that can be used for sorting. The key has the structure: (class_key, (len(args), args), exponent.sort_key(), coefficient) This key is supplied by the sort_key routine of Basic objects when ``item`` is a Basic object or an object (other than ...
Return a key that can be used for sorting. The key has the structure: (class_key, (len(args), args), exponent.sort_key(), coefficient) This key is supplied by the sort_key routine of Basic objects when ``item`` is a Basic object or an object (other than a string) that sympifies to a Basic object....
def show_condition_operators(self, condition): """ Show available operators for a given saved search condition """ # dict keys of allowed operators for the current condition permitted_operators = self.savedsearch.conditions_operators.get(condition) # transform these into values p...
Show available operators for a given saved search condition
def _create_at(self, timestamp=None, id=None, forced_identity=None, **kwargs): """ WARNING: Only for internal use and testing. Create a Versionable having a version_start_date and version_birth_date set to some pre-defined timestamp :param timestamp: point in...
WARNING: Only for internal use and testing. Create a Versionable having a version_start_date and version_birth_date set to some pre-defined timestamp :param timestamp: point in time at which the instance has to be created :param id: version 4 UUID unicode object. Usually this is not ...
def logout(self): """Logout of a vSphere server.""" if self._logged_in is True: self.si.flush_cache() self.sc.sessionManager.Logout() self._logged_in = False
Logout of a vSphere server.
def extract(group_id, access_token, fields=None): ''' FIXME: DOCS... Links: * https://developers.facebook.com/tools/explorer/ ''' fields = fields or ['id', 'owner', 'email', 'name', 'members'] # TEST that fields are a subset of valid fields assert set(fields).issubset(VALID_FIELDS) ...
FIXME: DOCS... Links: * https://developers.facebook.com/tools/explorer/
def remove_child_family(self, family_id, child_id): """Removes a child from a family. arg: family_id (osid.id.Id): the ``Id`` of a family arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``family_id`` not a parent of ``child_id`` raise: NullArgum...
Removes a child from a family. arg: family_id (osid.id.Id): the ``Id`` of a family arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``family_id`` not a parent of ``child_id`` raise: NullArgument - ``family_id`` or ``child_id`` is ``null`` raise: ...
def apply_templates(toks, templates): """ Generate features for an item sequence by applying feature templates. A feature template consists of a tuple of (name, offset) pairs, where name and offset specify a field name and offset from which the template extracts a feature value. Generated features a...
Generate features for an item sequence by applying feature templates. A feature template consists of a tuple of (name, offset) pairs, where name and offset specify a field name and offset from which the template extracts a feature value. Generated features are stored in the 'F' field of each item in the...
def commit_branches(sha1): # type: (str) -> List[str] """ Get the name of the branches that this commit belongs to. """ cmd = 'git branch --contains {}'.format(sha1) return shell.run( cmd, capture=True, never_pretend=True ).stdout.strip().split()
Get the name of the branches that this commit belongs to.
def qhalfx(self): """get the half normal matrix attribute. Create the attribute if it has not yet been created Returns ------- qhalfx : pyemu.Matrix """ if self.__qhalfx is None: self.log("qhalfx") self.__qhalfx = self.qhalf * self.jco ...
get the half normal matrix attribute. Create the attribute if it has not yet been created Returns ------- qhalfx : pyemu.Matrix
def get_end(pos, alt, category, snvend=None, svend=None, svlen=None): """Return the end coordinate for a variant Args: pos(int) alt(str) category(str) snvend(str) svend(int) svlen(int) Returns: end(int) """ # If nothing is known we set end to...
Return the end coordinate for a variant Args: pos(int) alt(str) category(str) snvend(str) svend(int) svlen(int) Returns: end(int)
def create_or_update_record(data, pid_type, id_key, minter): """Register a funder or grant.""" resolver = Resolver( pid_type=pid_type, object_type='rec', getter=Record.get_record) try: pid, record = resolver.resolve(data[id_key]) data_c = deepcopy(data) del data_c['remote_mo...
Register a funder or grant.
def get_versioned_delete_collector_class(): """ Gets the class to use for deletion collection. :return: class """ key = 'VERSIONED_DELETE_COLLECTOR' try: cls = _cache[key] except KeyError: collector_class_string = getattr(settings, key) cls = import_from_string(colle...
Gets the class to use for deletion collection. :return: class
def check_marker_kwargs(self, kwargs): """ Check the types of the keyword arguments for marker creation :param kwargs: dictionary of options for marker creation :type kwargs: dict :raises: TypeError, ValueError """ text = kwargs.get("text", "") if not isi...
Check the types of the keyword arguments for marker creation :param kwargs: dictionary of options for marker creation :type kwargs: dict :raises: TypeError, ValueError
def validate_extra_link(self, extra_link): """validate extra link""" if EXTRA_LINK_NAME_KEY not in extra_link or EXTRA_LINK_FORMATTER_KEY not in extra_link: raise Exception("Invalid extra.links format. " + "Extra link must include a 'name' and 'formatter' field") self.validated_...
validate extra link
def blogroll(request, btype): 'View that handles the generation of blogrolls.' response, site, cachekey = initview(request) if response: return response[0] template = loader.get_template('feedjack/{0}.xml'.format(btype)) ctx = dict() fjlib.get_extra_context(site, ctx) ctx = Context(ctx) response = HttpResponse...
View that handles the generation of blogrolls.
def visualize_detection(self, img, dets, classes=[], thresh=0.6): """ visualize detections in one image Parameters: ---------- img : numpy.array image, in bgr format dets : numpy.array ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...]) ...
visualize detections in one image Parameters: ---------- img : numpy.array image, in bgr format dets : numpy.array ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...]) each row is one object classes : tuple or list of str ...
def bgc(mag_file, dir_path=".", input_dir_path="", meas_file='measurements.txt', spec_file='specimens.txt', samp_file='samples.txt', site_file='sites.txt', loc_file='locations.txt', append=False, location="unknown", site="", samp_con='1', specnum=0, meth_code="LP-NO", volume=12, user="",...
Convert BGC format file to MagIC file(s) Parameters ---------- mag_file : str input file name dir_path : str working directory, default "." input_dir_path : str input file directory IF different from dir_path, default "" meas_file : str output measurement file na...
def get_calc_id(db, datadir, job_id=None): """ Return the latest calc_id by looking both at the datastore and the database. :param db: a :class:`openquake.server.dbapi.Db` instance :param datadir: the directory containing the datastores :param job_id: a job ID; if None, returns the latest job I...
Return the latest calc_id by looking both at the datastore and the database. :param db: a :class:`openquake.server.dbapi.Db` instance :param datadir: the directory containing the datastores :param job_id: a job ID; if None, returns the latest job ID
def part(z, s): r"""Get the real or imaginary part of a complex number.""" if sage_included: if s == 1: return np.real(z) elif s == -1: return np.imag(z) elif s == 0: return z else: if s == 1: return z.real elif s == -1: return z.imag elif s == 0: ...
r"""Get the real or imaginary part of a complex number.
def convert_basis(basis_dict, fmt, header=None): ''' Returns the basis set data as a string representing the data in the specified output format ''' # make converters case insensitive fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown basis set format "{}"'....
Returns the basis set data as a string representing the data in the specified output format
def get_performance_signatures(self, project, **params): ''' Gets a set of performance signatures associated with a project and time range ''' results = self._get_json(self.PERFORMANCE_SIGNATURES_ENDPOINT, project, **params) return PerformanceSignatureCollection(results)
Gets a set of performance signatures associated with a project and time range
def args_to_inject(self, function, bindings, owner_key): """Inject arguments into a function. :param function: The function. :param bindings: Map of argument name to binding key to inject. :param owner_key: A key uniquely identifying the *scope* of this function. For a metho...
Inject arguments into a function. :param function: The function. :param bindings: Map of argument name to binding key to inject. :param owner_key: A key uniquely identifying the *scope* of this function. For a method this will be the owning class. :returns: Dictionary of res...
def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry.""" if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 16...
Returns the meta description for the given entry.
def main(search, query): """main function that does the search""" url = search.search(query) print(url) search.open_page(url)
main function that does the search
def get_um(method_name, response=False): """Get protobuf for given method name :param method_name: full method name (e.g. ``Player.GetGameBadgeLevels#1``) :type method_name: :class:`str` :param response: whether to return proto for response or request :type response: :class:`bool` :return: prot...
Get protobuf for given method name :param method_name: full method name (e.g. ``Player.GetGameBadgeLevels#1``) :type method_name: :class:`str` :param response: whether to return proto for response or request :type response: :class:`bool` :return: protobuf message
def thumbnail(self): """Path to the thumbnail image (relative to the album directory).""" if not isfile(self.thumb_path): self.logger.debug('Generating thumbnail for %r', self) path = (self.dst_path if os.path.exists(self.dst_path) else self.src_path) ...
Path to the thumbnail image (relative to the album directory).
def Parse(conditions): """Parses the file finder condition types into the condition objects. Args: conditions: An iterator over `FileFinderCondition` objects. Yields: `MetadataCondition` objects that correspond to the file-finder conditions. """ kind = rdf_file_finder.FileFinderConditi...
Parses the file finder condition types into the condition objects. Args: conditions: An iterator over `FileFinderCondition` objects. Yields: `MetadataCondition` objects that correspond to the file-finder conditions.
def parse(self, data, extent): # type: (bytes, int) -> None ''' Parse the passed in data into a UDF Descriptor tag. Parameters: data - The data to parse. extent - The extent to compare against for the tag location. Returns: Nothing. ''' ...
Parse the passed in data into a UDF Descriptor tag. Parameters: data - The data to parse. extent - The extent to compare against for the tag location. Returns: Nothing.
def GetPatternIdTripDict(self): """Return a dictionary that maps pattern_id to a list of Trip objects.""" d = {} for t in self._trips: d.setdefault(t.pattern_id, []).append(t) return d
Return a dictionary that maps pattern_id to a list of Trip objects.
def batch_get_documents( self, database, documents, mask=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): ...
Gets multiple documents. Documents returned by this method are not guaranteed to be returned in the same order that they were requested. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() ...
def is_micropython_usb_device(port): """Checks a USB device to see if it looks like a MicroPython device. """ if type(port).__name__ == 'Device': # Assume its a pyudev.device.Device if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or 'SUBSYSTEM' not in port or port['SUBSYSTEM'...
Checks a USB device to see if it looks like a MicroPython device.
def print_validation_errors(result): """ Accepts validation result object and prints report (in red)""" click.echo(red('\nValidation failed:')) click.echo(red('-' * 40)) messages = result.get_messages() for property in messages.keys(): click.echo(yellow(property + ':')) for error in ...
Accepts validation result object and prints report (in red)
def remove_widget(self, widget): """Remove the given widget from the tooltip :param widget: the widget to remove :type widget: QtGui.QWidget :returns: None :rtype: None :raises: KeyError """ button = self._buttons.pop(widget) self.layout().removeW...
Remove the given widget from the tooltip :param widget: the widget to remove :type widget: QtGui.QWidget :returns: None :rtype: None :raises: KeyError
def _traverse_repos(self, callback, repo_name=None): ''' Traverse through all repo files and apply the functionality provided in the callback to them ''' repo_files = [] if os.path.exists(self.opts['spm_repos_config']): repo_files.append(self.opts['spm_repos_c...
Traverse through all repo files and apply the functionality provided in the callback to them
def login_failures(user): ''' Query for all accounts which have 3 or more login failures. CLI Example: .. code-block:: bash salt <minion_id> shadow.login_failures ALL ''' cmd = 'lsuser -a unsuccessful_login_count {0}'.format(user) cmd += " | grep -E 'unsuccessful_login_count=([3...
Query for all accounts which have 3 or more login failures. CLI Example: .. code-block:: bash salt <minion_id> shadow.login_failures ALL
def lookup(self, mbid, include=()): """ Lookup an entity directly from a specified :term:`MBID`\ . """ if include: for included in include: if included not in self.available_includes: raise ValueError( "{0!r} is no...
Lookup an entity directly from a specified :term:`MBID`\ .
def listDataTypes(self, datatype="", dataset=""): """ API to list data types known to dbs (when no parameter supplied). :param dataset: Returns data type (of primary dataset) of the dataset (Optional) :type dataset: str :param datatype: List specific data type :type data...
API to list data types known to dbs (when no parameter supplied). :param dataset: Returns data type (of primary dataset) of the dataset (Optional) :type dataset: str :param datatype: List specific data type :type datatype: str :returns: List of dictionaries containing the follow...
def _freeze_relations(self, relations): """Freeze relation.""" if relations: sel = relations[0] sel.relations.extend(relations[1:]) return ct.SelectorList([sel.freeze()]) else: return ct.SelectorList()
Freeze relation.
def addports(self): """ Look through the list of service ports and construct a list of tuples where each tuple is used to describe a port and it's list of methods as: (port, [method]). Each method is tuple: (name, [pdef,..] where each pdef is a tuple: (param-name, type). ...
Look through the list of service ports and construct a list of tuples where each tuple is used to describe a port and it's list of methods as: (port, [method]). Each method is tuple: (name, [pdef,..] where each pdef is a tuple: (param-name, type).
def discover(self, metafile): """ Determine what summary stats, time series, and CDF csv exist for the reports that need to be diffed. :return: boolean: return whether the summary stats / time series / CDF csv summary was successfully located """ for report in self.reports: if report.remote_lo...
Determine what summary stats, time series, and CDF csv exist for the reports that need to be diffed. :return: boolean: return whether the summary stats / time series / CDF csv summary was successfully located
def uimports(code): """ converts CPython module names into MicroPython equivalents """ for uimport in UIMPORTLIST: uimport = bytes(uimport, 'utf8') code = code.replace(uimport, b'u' + uimport) return code
converts CPython module names into MicroPython equivalents
def bios_image(self, bios_image): """ Sets the bios image for this QEMU VM. :param bios_image: QEMU bios image path """ self._bios_image = self.manager.get_abs_image_path(bios_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU bios image path to {bios_image}'.form...
Sets the bios image for this QEMU VM. :param bios_image: QEMU bios image path
def names(self): """Names, by which the instance can be retrieved.""" if getattr(self, 'key', None) is None: result = [] else: result = [self.key] if hasattr(self, 'aliases'): result.extend(self.aliases) return result
Names, by which the instance can be retrieved.
def url(self): """The url for this collection.""" if self.parent is None: # TODO: differing API Versions? pieces = [self.client.base_url, 'api', 'atlas', 'v2'] else: pieces = [self.parent.url] pieces.append(self.model_class.path) return '/'.jo...
The url for this collection.
def translate_latex2unicode(text, kb_file=None): """Translate latex text to unicode. This function will take given text, presumably containing LaTeX symbols, and attempts to translate it to Unicode using the given or default KB translation table located under CFG_ETCDIR/bibconvert/KB/latex-to-unico...
Translate latex text to unicode. This function will take given text, presumably containing LaTeX symbols, and attempts to translate it to Unicode using the given or default KB translation table located under CFG_ETCDIR/bibconvert/KB/latex-to-unicode.kb. The translated Unicode string will then be re...
def extendedEuclid(a, b): """return a tuple of three values: x, y and z, such that x is the GCD of a and b, and x = y * a + z * b""" if a == 0: return b, 0, 1 else: g, y, x = extendedEuclid(b % a, a) return g, x - (b // a) * y, y
return a tuple of three values: x, y and z, such that x is the GCD of a and b, and x = y * a + z * b
def soma_points(self): '''Get the soma points''' db = self.data_block return db[db[:, COLS.TYPE] == POINT_TYPE.SOMA]
Get the soma points
def decrypt(self, ciphertext): """Return plaintext for given ciphertext.""" # String to bytes. cipherbytes = ciphertext.encode('utf8') # Decode from Base64. try: combined = base64.b64decode(cipherbytes) except (base64.binascii.Error, TypeError) as e: ...
Return plaintext for given ciphertext.
def fetch_access_token_by_client_credentials(self): ''' There are three ways to let you start using KKBOX's Open/Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from K...
There are three ways to let you start using KKBOX's Open/Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from KKBOX such as public albums, playlists and so on. Howeve...
def pseudosection(self, column='r', filename=None, log10=False, **kwargs): """Plot a pseudosection of the given column. Note that this function only works with dipole-dipole data at the moment. Parameters ---------- column : string, optional Column to plot into the p...
Plot a pseudosection of the given column. Note that this function only works with dipole-dipole data at the moment. Parameters ---------- column : string, optional Column to plot into the pseudosection, default: r filename : string, optional if not None, ...
def content_children(self): """ A sequence containing the text-container child elements of this ``<a:p>`` element, i.e. (a:r|a:br|a:fld). """ text_types = {CT_RegularTextRun, CT_TextLineBreak, CT_TextField} return tuple(elm for elm in self if type(elm) in text_types)
A sequence containing the text-container child elements of this ``<a:p>`` element, i.e. (a:r|a:br|a:fld).
def get_pool_details(self, pool_id): """ Method to return object pool by id Param pool_id: pool id Returns object pool """ uri = 'api/v3/pool/details/%s/' % pool_id return super(ApiPool, self).get(uri)
Method to return object pool by id Param pool_id: pool id Returns object pool
def MatrixTriangularSolve(a, rhs, lower, adj): """ Matrix triangular solve op. """ trans = 0 if not adj else 2 r = np.empty(rhs.shape).astype(a.dtype) for coord in np.ndindex(a.shape[:-2]): pos = coord + (Ellipsis,) r[pos] = sp.linalg.solve_triangular(a[pos] if not adj else np.c...
Matrix triangular solve op.
def print_file(self, f=sys.stdout, file_format="mwtab"): """Print :class:`~mwtab.mwtab.MWTabFile` into a file or stdout. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `mwtab` or `json`. :param f: Print to file or stdout. :param int tw: T...
Print :class:`~mwtab.mwtab.MWTabFile` into a file or stdout. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `mwtab` or `json`. :param f: Print to file or stdout. :param int tw: Tab width. :return: None :rtype: :py:obj:`None`
def unindex_template(self, tpl): """ Unindex a template from the `templates` container. :param tpl: The template to un-index :type tpl: alignak.objects.item.Item :return: None """ name = getattr(tpl, 'name', '') try: del self.name_to_template[...
Unindex a template from the `templates` container. :param tpl: The template to un-index :type tpl: alignak.objects.item.Item :return: None
def avl_release_parent(node): """ removes the parent of a child """ parent = node.parent if parent is not None: if parent.right is node: parent.right = None elif parent.left is node: parent.left = None else: raise AssertionError('impossible...
removes the parent of a child
def get_K(rho, z, alpha=1.0, zint=100.0, n2n1=0.95, get_hdet=False, K=1, Kprefactor=None, return_Kprefactor=False, npts=20, **kwargs): """ Calculates one of three electric field integrals. Internal function for calculating point spread functions. Returns one of three electric field integrals th...
Calculates one of three electric field integrals. Internal function for calculating point spread functions. Returns one of three electric field integrals that describe the electric field near the focus of a lens; these integrals appear in Hell's psf calculation. Parameters ---------- r...
def _process_state_embryo(self, job_record): """ method that takes care of processing job records in STATE_EMBRYO state""" uow, is_duplicate = self.insert_and_publish_uow(job_record, 0, 0) self.update_job(job_record, uow, job.STATE_IN_PROGRESS)
method that takes care of processing job records in STATE_EMBRYO state
def add(self, field, op=None, val=None): """Update report fields to include new one, if it doesn't already. :param field: The field to include :type field: Field :param op: Operation :type op: ConstraintOperator :return: None """ if field.has_subfield(): ...
Update report fields to include new one, if it doesn't already. :param field: The field to include :type field: Field :param op: Operation :type op: ConstraintOperator :return: None
def month_days(year, month): '''How many days are in a given month of a given year''' if month > 13: raise ValueError("Incorrect month index") # First of all, dispose of fixed-length 29 day months if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR): return 29 # If it's not a leap yea...
How many days are in a given month of a given year
def transforms(self) -> Mapping[Type, Iterable[Type]]: """The available data transformers.""" try: return getattr(self.__class__, "transform")._transforms except AttributeError: return {}
The available data transformers.
def get_template_names(self): """Returns the template name to use for this request.""" if self.request.is_ajax(): template = self.ajax_template_name else: template = self.template_name return template
Returns the template name to use for this request.
def _slice_area_from_bbox(self, src_area, dst_area, ll_bbox=None, xy_bbox=None): """Slice the provided area using the bounds provided.""" if ll_bbox is not None: dst_area = AreaDefinition( 'crop_area', 'crop_area', 'crop_latlong', ...
Slice the provided area using the bounds provided.
def configure(args, parser): """ Color guide - red: Error and warning messages - green: Welcome messages (use sparingly) - blue: Default values - bold_magenta: Action items - bold_black: Parts of code to be run or copied that should be modified """ if not args.force and on_travis():...
Color guide - red: Error and warning messages - green: Welcome messages (use sparingly) - blue: Default values - bold_magenta: Action items - bold_black: Parts of code to be run or copied that should be modified
def create_resource_quota(self, name, quota_json): """ Prevent builds being scheduled and wait for running builds to finish. :return: """ url = self._build_k8s_url("resourcequotas/") response = self._post(url, data=json.dumps(quota_json), h...
Prevent builds being scheduled and wait for running builds to finish. :return:
def __roll(self, unrolled): """Converts parameter array back into matrices.""" rolled = [] index = 0 for count in range(len(self.__sizes) - 1): in_size = self.__sizes[count] out_size = self.__sizes[count+1] theta_unrolled = np.matrix(unrolled[index:ind...
Converts parameter array back into matrices.
def attribute(name, value, getter=None, setter=None, deleter=None, label=None, desc=None, meta=None): """ Annotates a model attribute. @param name: attribute name, unique for a model. @type name: str or unicode @param value: attribute type information. @type value: implementer of L...
Annotates a model attribute. @param name: attribute name, unique for a model. @type name: str or unicode @param value: attribute type information. @type value: implementer of L{src.feat.models.interface.IValueInfo} @param getter: an effect or None if the attribute is write-only; t...
def getMonitor(self): """ Returns an instance of the ``Screen`` object this Location is inside. Returns the primary screen if the Location isn't positioned in any screen. """ from .RegionMatching import Screen scr = self.getScreen() return scr if scr is not None else Scr...
Returns an instance of the ``Screen`` object this Location is inside. Returns the primary screen if the Location isn't positioned in any screen.
def remove_isolated_nodes(graph): """Remove isolated nodes from the network, in place. :param pybel.BELGraph graph: A BEL graph """ nodes = list(nx.isolates(graph)) graph.remove_nodes_from(nodes)
Remove isolated nodes from the network, in place. :param pybel.BELGraph graph: A BEL graph
def hasLogger(self, logger): """ Returns whether or not the inputed logger is tracked by this widget. :param logger | <str> || <logging.Logger> """ if isinstance(logger, logging.Logger): logger = logging.name return logger in se...
Returns whether or not the inputed logger is tracked by this widget. :param logger | <str> || <logging.Logger>
def get_exception(self): """ Return any exception that happened during the last server request. This can be used to fetch more specific error information after using calls like `start_client`. The exception (if any) is cleared after this call. :return: an ex...
Return any exception that happened during the last server request. This can be used to fetch more specific error information after using calls like `start_client`. The exception (if any) is cleared after this call. :return: an exception, or ``None`` if there is no stored ex...
def light_3d(self, r, kwargs_list, k=None): """ computes 3d density at radius r :param x: coordinate in units of arcsec relative to the center of the image :type x: set or single 1d numpy array """ r = np.array(r, dtype=float) flux = np.zeros_like(r) for i...
computes 3d density at radius r :param x: coordinate in units of arcsec relative to the center of the image :type x: set or single 1d numpy array
def _delete(self, identifier=None): """ Deletes given identifier from index. Args: identifier (str): identifier of the document to delete. """ assert identifier is not None, 'identifier argument can not be None.' writer = self.index.writer() writer.delete_by...
Deletes given identifier from index. Args: identifier (str): identifier of the document to delete.
def cosine(brands, exemplars, weighted_avg=False, sqrt=False): """ Return the cosine similarity betwee a brand's followers and the exemplars. """ scores = {} for brand, followers in brands: if weighted_avg: scores[brand] = np.average([_cosine(followers, others) for others in exem...
Return the cosine similarity betwee a brand's followers and the exemplars.
def process_tokens(self, tokens): """process tokens from the current module to search for module/block level options """ control_pragmas = {"disable", "enable"} for (tok_type, content, start, _, _) in tokens: if tok_type != tokenize.COMMENT: continue ...
process tokens from the current module to search for module/block level options
def get_group_target(self): """Returns the current destination surface for the context. This is either the original target surface as passed to :class:`Context` or the target surface for the current group as started by the most recent call to :meth:`push_group` or :meth:`...
Returns the current destination surface for the context. This is either the original target surface as passed to :class:`Context` or the target surface for the current group as started by the most recent call to :meth:`push_group` or :meth:`push_group_with_content`.
def wsp(word): '''Return the number of unstressed superheavy syllables.''' violations = 0 unstressed = [] for w in extract_words(word): unstressed += w.split('.')[1::2] # even syllables # include extrametrical odd syllables as potential WSP violations if w.count('.') % 2 == 0:...
Return the number of unstressed superheavy syllables.
def db_downgrade(version): """Downgrade the database""" v1 = get_db_version() migrate_api.downgrade(url=db_url, repository=db_repo, version=version) v2 = get_db_version() if v1 == v2: print 'No changes made.' else: print 'Downgraded: %s ... %s' % (v1, v2)
Downgrade the database
def _fixpath(self, p): """Apply tilde expansion and absolutization to a path.""" return os.path.abspath(os.path.expanduser(p))
Apply tilde expansion and absolutization to a path.
def __select_builder(lxml_builder, libxml2_builder, cmdline_builder): """ Selects a builder, based on which Python modules are present. """ if prefer_xsltproc: return cmdline_builder if not has_libxml2: # At the moment we prefer libxml2 over lxml, the latter can lead # to confli...
Selects a builder, based on which Python modules are present.
def hardmask(self): """ Mask all lowercase nucleotides with N's """ p = re.compile("a|c|g|t|n") for seq_id in self.fasta_dict.keys(): self.fasta_dict[seq_id] = p.sub("N", self.fasta_dict[seq_id]) return self
Mask all lowercase nucleotides with N's
def log_request_data_send(self, target_system, target_component, id, ofs, count, force_mavlink1=False): ''' Request a chunk of a log target_system : System ID (uint8_t) target_component : Component ID (uint8_t) id ...
Request a chunk of a log target_system : System ID (uint8_t) target_component : Component ID (uint8_t) id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) ...
def jsonRender(self, def_buf): """ Translate the passed serial block into string only JSON. Args: def_buf (SerialBlock): Any :class:`~ekmmeters.SerialBlock` object. Returns: str: JSON rendering of meter record. """ try: ret_dict = SerialBlock...
Translate the passed serial block into string only JSON. Args: def_buf (SerialBlock): Any :class:`~ekmmeters.SerialBlock` object. Returns: str: JSON rendering of meter record.
def cleanup(self): """Cleanup all the expired keys""" keys = self.client.smembers(self.keys_container) for key in keys: entry = self.client.get(key) if entry: entry = pickle.loads(entry) if self._is_expired(entry, self.timeout): ...
Cleanup all the expired keys