code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _call_pyfftw(self, x, out, **kwargs): """Implement ``self(x[, out, **kwargs])`` for pyfftw back-end. Parameters ---------- x : `numpy.ndarray` Array representing the function to be transformed out : `numpy.ndarray` Array to which the output is written...
Implement ``self(x[, out, **kwargs])`` for pyfftw back-end. Parameters ---------- x : `numpy.ndarray` Array representing the function to be transformed out : `numpy.ndarray` Array to which the output is written planning_effort : {'estimate', 'measure', 'p...
def get_full_pipe(sol, base=()): """ Returns the full pipe of a dispatch run. :param sol: A Solution object. :type sol: schedula.utils.Solution :param base: Base node id. :type base: tuple[str] :return: Full pipe of a dispatch run. :rtype: DspPipe """ ...
Returns the full pipe of a dispatch run. :param sol: A Solution object. :type sol: schedula.utils.Solution :param base: Base node id. :type base: tuple[str] :return: Full pipe of a dispatch run. :rtype: DspPipe
def get_upstream_paths(self, port): """Retrieve a dictionary containing the full URLs of the upstream apps :param int port: The port used by the replay and cdx servers :return: A dictionary containing the upstream paths (replay, cdx-server, record [if enabled]) :rtype: dict[str, str] ...
Retrieve a dictionary containing the full URLs of the upstream apps :param int port: The port used by the replay and cdx servers :return: A dictionary containing the upstream paths (replay, cdx-server, record [if enabled]) :rtype: dict[str, str]
def _cromwell_debug(metadata): """Format Cromwell failures to make debugging easier. """ def get_failed_calls(cur, key=None): if key is None: key = [] out = [] if isinstance(cur, dict) and "failures" in cur and "callRoot" in cur: out.append((key, cur)) elif isinst...
Format Cromwell failures to make debugging easier.
def credentials_loader(self, in_credentials: str = "client_secrets.json") -> dict: """Loads API credentials from a file, JSON or INI. :param str in_credentials: path to the credentials file. By default, look for a client_secrets.json file. """ accepted_extensions = (".ini", "....
Loads API credentials from a file, JSON or INI. :param str in_credentials: path to the credentials file. By default, look for a client_secrets.json file.
def addItem(self, item, message=None): """add a new Item class object""" if message is None: message = 'Adding item %s' % item.path try: v = Version.new(repo=self) v.addItem(item) v.save(message) except VersionError, e: raise Re...
add a new Item class object
def elixir_decode(elixir_filename): """ Takes an elixir style file name and decodes it's content. Values returned as a dictionary. Elixir filenames have the format RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits """ import re, pyfits parts_RE=re.compile(r'([^\.\s]+)') dataset_name =...
Takes an elixir style file name and decodes it's content. Values returned as a dictionary. Elixir filenames have the format RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits
def wrap(self, stream, name=None, filename=None): """This is called with the stream as returned by `tokenize` and wraps every token in a :class:`Token` and converts the value. """ for lineno, token, value in stream: if token in ignored_tokens: continue ...
This is called with the stream as returned by `tokenize` and wraps every token in a :class:`Token` and converts the value.
def print_http_nfc_lease_info(info): """ Prints information about the lease, such as the entity covered by the lease, and HTTP URLs for up/downloading file backings. :param info: :type info: vim.HttpNfcLease.Info :return: """ print 'Lease timeout: {0.leaseTimeout}\n' \ 'Disk Ca...
Prints information about the lease, such as the entity covered by the lease, and HTTP URLs for up/downloading file backings. :param info: :type info: vim.HttpNfcLease.Info :return:
def _brace_key(self, key): """ key: 'x' -> '{x}' """ if isinstance(key, six.integer_types): t = str key = t(key) else: t = type(key) return t(u'{') + key + t(u'}')
key: 'x' -> '{x}'
def clean(cls, path): '''Clean up all the files in a provided path''' for pth in os.listdir(path): pth = os.path.abspath(os.path.join(path, pth)) if os.path.isdir(pth): logger.debug('Removing directory %s' % pth) shutil.rmtree(pth) else...
Clean up all the files in a provided path
def _apply_sub_frames(cls, documents, subs): """Convert embedded documents to sub-frames for one or more documents""" # Dereference each reference for path, projection in subs.items(): # Get the SubFrame class we'll use to wrap the embedded document sub = None ...
Convert embedded documents to sub-frames for one or more documents
def _getKeyForUrl(url, existing=None): """ Extracts a key from a given s3:// URL. On return, but not on exceptions, this method leaks an S3Connection object. The caller is responsible to close that by calling key.bucket.connection.close(). :param bool existing: If True, key is e...
Extracts a key from a given s3:// URL. On return, but not on exceptions, this method leaks an S3Connection object. The caller is responsible to close that by calling key.bucket.connection.close(). :param bool existing: If True, key is expected to exist. If False, key is expected not to ...
def get_client_address(self): """ Returns an auth token dictionary for making calls to eventhub REST API. :rtype: str """ return "amqps://{}:{}@{}.{}:5671/{}".format( urllib.parse.quote_plus(self.policy), urllib.parse.quote_plus(self.sas_key), ...
Returns an auth token dictionary for making calls to eventhub REST API. :rtype: str
def sql_program_name_func(command): """ Extract program name from `command`. >>> sql_program_name_func('ls') 'ls' >>> sql_program_name_func('git status') 'git' >>> sql_program_name_func('EMACS=emacs make') 'make' :type command: str """ args = command.split(' ') for pro...
Extract program name from `command`. >>> sql_program_name_func('ls') 'ls' >>> sql_program_name_func('git status') 'git' >>> sql_program_name_func('EMACS=emacs make') 'make' :type command: str
def get_replacement_method(method_to_patch, side_effect=UNDEFINED, rvalue=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, context=UNDEFINED, subsequent_rvalue=UNDEFINED): """ Returns the method to be applied in place of an original method. This method either executes a side effect, returns an rvalue, or implem...
Returns the method to be applied in place of an original method. This method either executes a side effect, returns an rvalue, or implements caching in place of the method_to_patch :param function method_to_patch: A reference to the method that will be patched. :param mixed side_effect: The side effect to exec...
def get_port(self, id_or_uri, port_id_or_uri): """ Gets an interconnect port. Args: id_or_uri: Can be either the interconnect id or uri. port_id_or_uri: The interconnect port id or uri. Returns: dict: The interconnect port. """ uri = ...
Gets an interconnect port. Args: id_or_uri: Can be either the interconnect id or uri. port_id_or_uri: The interconnect port id or uri. Returns: dict: The interconnect port.
def list(): """Print a listing of known running TensorBoard instances. TensorBoard instances that were killed uncleanly (e.g., with SIGKILL or SIGQUIT) may appear in this list even if they are no longer running. Conversely, this list may be missing some entries if your operating system's temporary directory ...
Print a listing of known running TensorBoard instances. TensorBoard instances that were killed uncleanly (e.g., with SIGKILL or SIGQUIT) may appear in this list even if they are no longer running. Conversely, this list may be missing some entries if your operating system's temporary directory has been cleared ...
def make_config_file(guided=False): """ Options: --auto, --guided, --manual Places for the file: --inplace, --user """ config_path = _make_config_location(guided=guided) config_data = make_config_data(guided=guided) write_config_file(config_path, config_data)
Options: --auto, --guided, --manual Places for the file: --inplace, --user
def draw(self): """draw the curses ui on the screen, handle scroll if needed""" self.screen.clear() x, y = 1, 1 # start point max_y, max_x = self.screen.getmaxyx() max_rows = max_y - y # the max rows we can draw lines, current_line = self.get_lines() # calcul...
draw the curses ui on the screen, handle scroll if needed
def saveJSON(g, data, backup=False): """ Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename """ ...
Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename
def addvFunc(self,solution,EndOfPrdvP): ''' Creates the value function for this period and adds it to the solution. Parameters ---------- solution : ConsumerSolution The solution to this single period problem, likely including the consumption function, ma...
Creates the value function for this period and adds it to the solution. Parameters ---------- solution : ConsumerSolution The solution to this single period problem, likely including the consumption function, marginal value function, etc. EndOfPrdvP : np.array ...
def build_kal_scan_channel_string(kal_bin, channel, args): """Return string for CLI invocation of kal, for channel scan.""" option_mapping = {"gain": "-g", "device": "-d", "error": "-e"} base_string = "%s -v -c %s" % (kal_bin, channel) base_string += options_s...
Return string for CLI invocation of kal, for channel scan.
def previous_song(self): """previous song for player to play NOTE: not the last played song """ if self.current_song is None: return self._get_good_song(base=-1, direction=-1) if self.playback_mode == PlaybackMode.random: previous_song = self._get_good_s...
previous song for player to play NOTE: not the last played song
def finalize(self): """ Finalize the run - build the name generator and use it to build the remap symbol tables. """ self.global_scope.close() name_generator = NameGenerator(skip=self.reserved_keywords) self.global_scope.build_remap_symbols( name_gene...
Finalize the run - build the name generator and use it to build the remap symbol tables.
def _run_get_data_background(macs, queue, shared_data, bt_device): """ Background process function for RuuviTag Sensors """ run_flag = RunFlag() def add_data(data): if not shared_data['run_flag']: run_flag.running = False data[1]['time'] = datetime.utcnow().isoformat()...
Background process function for RuuviTag Sensors
def get_arctic_lib(connection_string, **kwargs): """ Returns a mongo library for the given connection string Parameters --------- connection_string: `str` Format must be one of the following: library@trading for known mongo servers library@hostname:port Returns:...
Returns a mongo library for the given connection string Parameters --------- connection_string: `str` Format must be one of the following: library@trading for known mongo servers library@hostname:port Returns: -------- Arctic library
def filter(self, **kwargs): """ Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned. """ ...
Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned.
def print_chain_summary(self, stream=sys.stdout, indent=""): """Print a summary of the files in this file dict. This version uses chain_input_files and chain_output_files to count the input and output files. """ stream.write("%sTotal files : %i\n" % (in...
Print a summary of the files in this file dict. This version uses chain_input_files and chain_output_files to count the input and output files.
def id_source(source, full=False): """ Returns the name of a website-scrapping function. """ if source not in source_ids: return '' if full: return source_ids[source][1] else: return source_ids[source][0]
Returns the name of a website-scrapping function.
def check_path(path, create=False): """ Check for a path on filesystem :param path: str - path name :param create: bool - create if do not exist :return: bool - path exists """ if not os.path.exists(path): if create: os.makedirs(path) return os.path.exists(pa...
Check for a path on filesystem :param path: str - path name :param create: bool - create if do not exist :return: bool - path exists
def create_page(self, **extra_kwargs): """ Create page (and page title) in default language extra_kwargs will be pass to cms.api.create_page() e.g.: extra_kwargs={ "soft_root": True, "reverse_id": my_reverse_id, } """ ...
Create page (and page title) in default language extra_kwargs will be pass to cms.api.create_page() e.g.: extra_kwargs={ "soft_root": True, "reverse_id": my_reverse_id, }
def rm_watch(self, wd, rec=False, quiet=True): """ Removes watch(s). @param wd: Watch Descriptor of the file or directory to unwatch. Also accepts a list of WDs. @type wd: int or list of int. @param rec: Recursively removes watches on every already watched ...
Removes watch(s). @param wd: Watch Descriptor of the file or directory to unwatch. Also accepts a list of WDs. @type wd: int or list of int. @param rec: Recursively removes watches on every already watched subdirectories and subfiles. @type rec: bo...
def updateData(self, axeskey, x, y): """Replaces the currently displayed data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param x: index values associated with y to plot :type x: numpy.ndarray :param y: values t...
Replaces the currently displayed data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param x: index values associated with y to plot :type x: numpy.ndarray :param y: values to plot at x :type y: numpy.ndarray
def _get_timestamp_tuple(ts): """ Internal method to get a timestamp tuple from a value. Handles input being a datetime or a Timestamp. """ if isinstance(ts, datetime.datetime): return Timestamp.from_datetime(ts).tuple() elif isinstance(ts, Timestamp): return ts raise...
Internal method to get a timestamp tuple from a value. Handles input being a datetime or a Timestamp.
def _process_uniprot_ids(self, limit=None): """ This method processes the mappings from ZFIN gene IDs to UniProtKB IDs. Triples created: <zfin_gene_id> a class <zfin_gene_id> rdfs:label gene_symbol <uniprot_id> is an Individual <uniprot_id> has type <polypeptide...
This method processes the mappings from ZFIN gene IDs to UniProtKB IDs. Triples created: <zfin_gene_id> a class <zfin_gene_id> rdfs:label gene_symbol <uniprot_id> is an Individual <uniprot_id> has type <polypeptide> <zfin_gene_id> has_gene_product <uniprot_id> ...
def get_net(req): """Get the net of any 'next' and 'prev' querystrings.""" try: nxt, prev = map( int, (req.GET.get('cal_next', 0), req.GET.get('cal_prev', 0)) ) net = nxt - prev except Exception: net = 0 return net
Get the net of any 'next' and 'prev' querystrings.
def calcAspectRatioFromCorners(corners, in_plane=False): ''' simple and better alg. than below in_plane -> whether object has no tilt, but only rotation and translation ''' q = corners l0 = [q[0, 0], q[0, 1], q[1, 0], q[1, 1]] l1 = [q[0, 0], q[0, 1], q[-1, 0], q[-1, 1]] l2 = ...
simple and better alg. than below in_plane -> whether object has no tilt, but only rotation and translation
def validate_sceneInfo(self): """Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong. """ if self.sceneInfo.prefix not in self.__satellitesMap: logger.error('Google Downloader: Prefix of %s (%s) is invalid' % ...
Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong.
def in_scope(self, exclude_scopes=None, include_scopes=None): """Whether this scope should be included by the given inclusion and exclusion rules. :param Scope exclude_scopes: An optional Scope containing scope names to exclude. None (the default value) indicates that no filtering should be done based on...
Whether this scope should be included by the given inclusion and exclusion rules. :param Scope exclude_scopes: An optional Scope containing scope names to exclude. None (the default value) indicates that no filtering should be done based on exclude_scopes. :param Scope include_scopes: An optional Scope c...
def current(self): """Returns the current user """ if not has_request_context(): return self.no_req_ctx_user_stack.top user_stack = getattr(_request_ctx_stack.top, 'user_stack', None) if user_stack and user_stack.top: return user_stack.top return _...
Returns the current user
def active_thresholds_value_maps(keywords, exposure_key): """Helper to retrieve active value maps or thresholds for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: Active thresholds or value map...
Helper to retrieve active value maps or thresholds for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: Active thresholds or value maps. :rtype: dict
def extract_audioclip_samples(d) -> dict: """ Extract all the sample data from an AudioClip and convert it from FSB5 if needed. """ ret = {} if not d.data: # eg. StreamedResource not available return {} try: from fsb5 import FSB5 except ImportError as e: raise RuntimeError("python-fsb5 is required to ...
Extract all the sample data from an AudioClip and convert it from FSB5 if needed.
def iter_variants(self): """Iterate over marker information.""" for idx, row in self.bim.iterrows(): yield Variant( row.name, CHROM_INT_TO_STR[row.chrom], row.pos, [row.a1, row.a2] )
Iterate over marker information.
def add_contig_to_header(line, ref_file): """Streaming target to add contigs to a VCF file header. """ if line.startswith("##fileformat=VCF"): out = [line] for region in ref.file_contigs(ref_file): out.append("##contig=<ID=%s,length=%s>" % (region.name, region.size)) retu...
Streaming target to add contigs to a VCF file header.
def ecg_hrv(rpeaks=None, rri=None, sampling_rate=1000, hrv_features=["time", "frequency", "nonlinear"]): """ Computes the Heart-Rate Variability (HRV). Shamelessly stolen from the `hrv <https://github.com/rhenanbartels/hrv/blob/develop/hrv>`_ package by Rhenan Bartels. All credits go to him. Parameters ...
Computes the Heart-Rate Variability (HRV). Shamelessly stolen from the `hrv <https://github.com/rhenanbartels/hrv/blob/develop/hrv>`_ package by Rhenan Bartels. All credits go to him. Parameters ---------- rpeaks : list or ndarray R-peak location indices. rri: list or ndarray RR interva...
def get_authority_key_identifier(self): """Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.""" try: ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier) except x509.ExtensionNotFound: return x509.AuthorityKeyIde...
Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.
def _get_exc_info(self, exc_tuple=None): """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. Ensures sys.last_type,value,traceback hold the exc_info we found, from whichever source. raises ValueError if none of these contain any information ...
get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. Ensures sys.last_type,value,traceback hold the exc_info we found, from whichever source. raises ValueError if none of these contain any information
def get_schema(repo, content_type): """ Return a schema for a content type in a repository. :param Repo repo: The git repository. :returns: dict """ try: with open( os.path.join(repo.working_dir, '_schemas', ...
Return a schema for a content type in a repository. :param Repo repo: The git repository. :returns: dict
def send_location(self, geo_uri, name, thumb_url=None, **thumb_info): """Send a location to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location for thumb_info Args: geo_uri (str): The geo uri representing the location. name (str): Desc...
Send a location to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location for thumb_info Args: geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of th...
def getprice(self): """ Here we obtain the price for the quote and make sure it has a feed price """ target = self.bot.get("target", {}) if target.get("reference") == "feed": assert self.market == self.market.core_quote_market(), "Wrong market for 'feed' reference...
Here we obtain the price for the quote and make sure it has a feed price
def iter_instances(self): """Iterate over the stored objects Yields: wrkey: The two-tuple key used to store the object obj: The instance or function object """ for wrkey in set(self.keys()): obj = self.get(wrkey) if obj is None: ...
Iterate over the stored objects Yields: wrkey: The two-tuple key used to store the object obj: The instance or function object
def get_csv_from_metadata(dsn, d): """ Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files. :param str dsn: Dataset name :param dict d: Metadata :return dict _csvs: Csv """ logger_csvs.info("enter get_csv_from_metadata") _csvs = OrderedD...
Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files. :param str dsn: Dataset name :param dict d: Metadata :return dict _csvs: Csv
def barycentric_to_cartesian(tri, bc): ''' barycentric_to_cartesian(tri, bc) yields the d x n coordinate matrix of the given barycentric coordinate matrix (also d x n) bc interpolated in the n triangles given in the array tri. See also cartesian_to_barycentric. If tri and bc represent one triangle and c...
barycentric_to_cartesian(tri, bc) yields the d x n coordinate matrix of the given barycentric coordinate matrix (also d x n) bc interpolated in the n triangles given in the array tri. See also cartesian_to_barycentric. If tri and bc represent one triangle and coordinate, then just the coordinate and not a m...
def update_thread(cls, session, conversation, thread): """Update a thread. Args: session (requests.sessions.Session): Authenticated session. conversation (helpscout.models.Conversation): The conversation that the thread belongs to. thread (helpscout.m...
Update a thread. Args: session (requests.sessions.Session): Authenticated session. conversation (helpscout.models.Conversation): The conversation that the thread belongs to. thread (helpscout.models.Thread): The thread to be updated. Returns: ...
def format_all(self): """ return a trace of parents and children of the obect """ res = '\n--- Format all : ' + str(self.name) + ' -------------\n' res += ' parent = ' + str(self.parent) + '\n' res += self._get_all_children() res += self._get_links() ...
return a trace of parents and children of the obect
def rtype_to_model(rtype): """ Return a model class object given a string resource type :param rtype: string resource type :return: model class object :raise: ValueError """ models = goldman.config.MODELS for model in models: if rtype.lower() == model.RTYPE....
Return a model class object given a string resource type :param rtype: string resource type :return: model class object :raise: ValueError
def get_repo(name, basedir=None, **kwargs): # pylint: disable=W0613 ''' Display a repo from <basedir> (default basedir: all dirs in ``reposdir`` yum option). CLI Examples: .. code-block:: bash salt '*' pkg.get_repo myrepo salt '*' pkg.get_repo myrepo basedir=/path/to/dir ...
Display a repo from <basedir> (default basedir: all dirs in ``reposdir`` yum option). CLI Examples: .. code-block:: bash salt '*' pkg.get_repo myrepo salt '*' pkg.get_repo myrepo basedir=/path/to/dir salt '*' pkg.get_repo myrepo basedir=/path/to/dir,/path/to/another/dir
def _set_collection(self, v, load=False): """ Setter method for collection, mapped from YANG variable /interface/fortygigabitethernet/rmon/collection (container) If this variable is read-only (config: false) in the source YANG file, then _set_collection is considered as a private method. Backends lo...
Setter method for collection, mapped from YANG variable /interface/fortygigabitethernet/rmon/collection (container) If this variable is read-only (config: false) in the source YANG file, then _set_collection is considered as a private method. Backends looking to populate this variable should do so via c...
def save_cloud_optimized(self, dest_url, resampling=Resampling.gauss, blocksize=256, overview_blocksize=256, creation_options=None): """Save as Cloud Optimized GeoTiff object to a new file. :param dest_url: path to the new raster :param resampling: which Resampling ...
Save as Cloud Optimized GeoTiff object to a new file. :param dest_url: path to the new raster :param resampling: which Resampling to use on reading, default Resampling.gauss :param blocksize: the size of the blocks default 256 :param overview_blocksize: the block size of the overviews, ...
def env(): """Verify SSH variables and construct exported variables""" ssh = cij.env_to_dict(PREFIX, REQUIRED) if "KEY" in ssh: ssh["KEY"] = cij.util.expand_path(ssh["KEY"]) if cij.ENV.get("SSH_PORT") is None: cij.ENV["SSH_PORT"] = "22" cij.warn("cij.ssh.env: SSH_PORT was not s...
Verify SSH variables and construct exported variables
def cli(self, commands): """ Execute a list of commands and return the output in a dictionary format using the command as the key. Example input: ['show clock', 'show calendar'] Output example: { 'show calendar': u'22:02:01 UTC Thu Feb 18 2016', 's...
Execute a list of commands and return the output in a dictionary format using the command as the key. Example input: ['show clock', 'show calendar'] Output example: { 'show calendar': u'22:02:01 UTC Thu Feb 18 2016', 'show clock': u'*22:01:51.165 UTC Thu Feb 18 20...
def run_review(*args): ''' Get the difference of recents modification, and send the Email. For: wiki, page, and post. ''' email_cnt = '''<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> table.diff {font-family:C...
Get the difference of recents modification, and send the Email. For: wiki, page, and post.
def update_marker(self, iid, **kwargs): """ Change the options for a certain marker and redraw the marker :param iid: identifier of the marker to change :type iid: str :param kwargs: Dictionary of options to update :type kwargs: dict :raises: ValueError "...
Change the options for a certain marker and redraw the marker :param iid: identifier of the marker to change :type iid: str :param kwargs: Dictionary of options to update :type kwargs: dict :raises: ValueError
def failback_from_replicant(self, volume_id, replicant_id): """Failback from a volume replicant. :param integer volume_id: The id of the volume :param integer replicant_id: ID of replicant to failback from :return: Returns whether failback was successful or not """ retu...
Failback from a volume replicant. :param integer volume_id: The id of the volume :param integer replicant_id: ID of replicant to failback from :return: Returns whether failback was successful or not
def make_error_response(self, cond): """Create error response for the any non-error presence stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :Types: - `cond`: `unicode` :return: new presence stanza. :returntype: `Pr...
Create error response for the any non-error presence stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :Types: - `cond`: `unicode` :return: new presence stanza. :returntype: `Presence`
def get(self, key: Text, count: Optional[int]=None, formatter: Formatter=None, locale: Text=None, params: Optional[Dict[Text, Any]]=None, flags: Optional[Flags]=None) -> List[Text]: """ Get the appropriate translation given the spec...
Get the appropriate translation given the specified parameters. :param key: Translation key :param count: Count for plurals :param formatter: Optional string formatter to use :param locale: Prefered locale to get the string from :param params: Params to be substituted :p...
def get_entry_by_material_id(self, material_id, compatible_only=True, inc_structure=None, property_data=None, conventional_unit_cell=False): """ Get a ComputedEntry corresponding to a material_id. Args: material_id (s...
Get a ComputedEntry corresponding to a material_id. Args: material_id (str): Materials Project material_id (a string, e.g., mp-1234). compatible_only (bool): Whether to return only "compatible" entries. Compatible entries are entries that have been ...
def create(cls, tokens:Tokens, max_vocab:int, min_freq:int) -> 'Vocab': "Create a vocabulary from a set of `tokens`." freq = Counter(p for o in tokens for p in o) itos = [o for o,c in freq.most_common(max_vocab) if c >= min_freq] for o in reversed(defaults.text_spec_tok): if ...
Create a vocabulary from a set of `tokens`.
def get_mapping_from_db3_file( db_path ): ''' Does the work of reading the Rosetta SQLite3 .db3 file to retrieve the mapping ''' import sqlite3 # should be moved to the top but we do this here for CentOS 5 support conn = sqlite3.connect(db_path) results = conn.cursor().execute(''' SELECT ch...
Does the work of reading the Rosetta SQLite3 .db3 file to retrieve the mapping
def get_version(module): """ Return package version as listed in `__version__`. """ init_py = open('{0}.py'.format(module)).read() return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
Return package version as listed in `__version__`.
def find_movers(choosers, rates, rate_column): """ Returns an array of the indexes of the `choosers` that are slated to move. Parameters ---------- choosers : pandas.DataFrame Table of agents from which to find movers. rates : pandas.DataFrame Table of relocation rates. Inde...
Returns an array of the indexes of the `choosers` that are slated to move. Parameters ---------- choosers : pandas.DataFrame Table of agents from which to find movers. rates : pandas.DataFrame Table of relocation rates. Index is unused. Other columns describe filters on the...
def render_mail(self, template_prefix, email, context): """ Renders an e-mail to `email`. `template_prefix` identifies the e-mail that is to be sent, e.g. "account/email/email_confirmation" """ subject = render_to_string('{0}_subject.txt'.format(template_prefix), ...
Renders an e-mail to `email`. `template_prefix` identifies the e-mail that is to be sent, e.g. "account/email/email_confirmation"
def upload_all_books(book_id_start, book_id_end, rdf_library=None): """ Uses the fetch, make, push subcommands to mirror Project Gutenberg to a github3 api """ # TODO refactor appname into variable logger.info( "starting a gitberg mass upload: {0} -> {1}".format( book_id_sta...
Uses the fetch, make, push subcommands to mirror Project Gutenberg to a github3 api
def _restore_replace(self): """ Check if we need to replace ".gitignore" to ".keep". :return: The replacement status. :rtype: bool """ if PyFunceble.path.isdir(self.base + ".git"): # The `.git` directory exist. if "PyFunceble" not in Command("gi...
Check if we need to replace ".gitignore" to ".keep". :return: The replacement status. :rtype: bool
def getattr(self, name, default: Any = _missing): """ Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])`` """ return deep_getattr(self.clsdict, self.bases, name, default)
Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])``
def _fetch_stock_data(self, stock_list): """获取股票信息""" pool = multiprocessing.pool.ThreadPool(len(stock_list)) try: res = pool.map(self.get_stocks_by_range, stock_list) finally: pool.close() return [d for d in res if d is not None]
获取股票信息
def Earth(pos=(0, 0, 0), r=1, lw=1): """Build a textured actor representing the Earth. .. hint:: |geodesic| |geodesic.py|_ """ import os tss = vtk.vtkTexturedSphereSource() tss.SetRadius(r) tss.SetThetaResolution(72) tss.SetPhiResolution(36) earthMapper = vtk.vtkPolyDataMapper() ...
Build a textured actor representing the Earth. .. hint:: |geodesic| |geodesic.py|_
def _check_lock_permission( self, url, lock_type, lock_scope, lock_depth, token_list, principal ): """Check, if <principal> can lock <url>, otherwise raise an error. If locking <url> would create a conflict, DAVError(HTTP_LOCKED) is raised. An embedded DAVErrorCondition contains the...
Check, if <principal> can lock <url>, otherwise raise an error. If locking <url> would create a conflict, DAVError(HTTP_LOCKED) is raised. An embedded DAVErrorCondition contains the conflicting resource. @see http://www.webdav.org/specs/rfc4918.html#lock-model - Parent locks WILL NOT ...
def client_list(self, *args): """Display a list of connected clients""" if len(self._clients) == 0: self.log('No clients connected') else: self.log(self._clients, pretty=True)
Display a list of connected clients
def certify_enum(value, kind=None, required=True): """ Certifier for enum. :param value: The value to be certified. :param kind: The enum type that value should be an instance of. :param bool required: Whether the value can be `None`. Defaults to True. :raises CertifierT...
Certifier for enum. :param value: The value to be certified. :param kind: The enum type that value should be an instance of. :param bool required: Whether the value can be `None`. Defaults to True. :raises CertifierTypeError: The type is invalid
def is_shortcut_in_use(self, shortcut): """ Returns if given action shortcut is in use. :param name: Action shortcut. :type name: unicode :return: Is shortcut in use. :rtype: bool """ for path, actionName, action in foundations.walkers.dictionaries_walke...
Returns if given action shortcut is in use. :param name: Action shortcut. :type name: unicode :return: Is shortcut in use. :rtype: bool
def line_spacing_rule(self): """ A member of the :ref:`WdLineSpacing` enumeration indicating how the value of :attr:`line_spacing` should be interpreted. Assigning any of the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or :attr:`ONE_POINT_FIVE` will cause the val...
A member of the :ref:`WdLineSpacing` enumeration indicating how the value of :attr:`line_spacing` should be interpreted. Assigning any of the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or :attr:`ONE_POINT_FIVE` will cause the value of :attr:`line_spacing` to be updated ...
def dequeue(self, k): """Outputs *k* draws from the multinomial distribution.""" if self.j + k <= self.M: out = self.A[self.j:(self.j + k)] self.j += k elif k <= self.M: out = np.empty(k, 'int') nextra = self.j + k - self.M out[:(k - ne...
Outputs *k* draws from the multinomial distribution.
def export(self, exclude=[]): """ returns a dictionary representation of the document """ fields = ( (key, self.get_field(key)) for key in self.schema if not key.startswith("_") and key not in exclude ) doc = {name: field.export() for name, field in fields} r...
returns a dictionary representation of the document
def wait_for(self, pids=[], status_list=process_result_statuses): ''' wait_for(self, pids=[], status_list=process_result_statuses) Waits for a process to finish :Parameters: * *pids* (`list`) -- list of processes waiting to be finished * *status_list* (`list`) -- option...
wait_for(self, pids=[], status_list=process_result_statuses) Waits for a process to finish :Parameters: * *pids* (`list`) -- list of processes waiting to be finished * *status_list* (`list`) -- optional - List of statuses to wait for processes to finish with :Example: ...
def _group_dict_set(iterator): """Make a dict that accumulates the values for each key in an iterator of doubles. :param iter[tuple[A,B]] iterator: An iterator :rtype: dict[A,set[B]] """ d = defaultdict(set) for key, value in iterator: d[key].add(value) return dict(d)
Make a dict that accumulates the values for each key in an iterator of doubles. :param iter[tuple[A,B]] iterator: An iterator :rtype: dict[A,set[B]]
def profile(self, name): """Return a specific profile.""" self.selected_profile = self.profiles.get(name) return self.profiles.get(name)
Return a specific profile.
def set_icon_data(self, base64_data, mimetype="image/png", rel="icon"): """ Allows to define an icon for the App Args: base64_data (str): base64 encoded image data (ie. "data:image/x-icon;base64,AAABAAEAEBA....") mimetype (str): mimetype of the image ("image...
Allows to define an icon for the App Args: base64_data (str): base64 encoded image data (ie. "data:image/x-icon;base64,AAABAAEAEBA....") mimetype (str): mimetype of the image ("image/png" or "image/x-icon"...) rel (str): leave it unchanged (standard ...
def gen_postinit(self, cls: ClassDefinition, slotname: str) -> Optional[str]: """ Generate python post init rules for slot in class """ rlines: List[str] = [] slot = self.schema.slots[slotname] if slot.alias: slotname = slot.alias slotname = self.python_name_f...
Generate python post init rules for slot in class
def indent(self, space=4): '''Return an indented Newick string, just like ``nw_indent`` in Newick Utilities Args: ``space`` (``int``): The number of spaces a tab should equal Returns: ``str``: An indented Newick string ''' if not isinstance(space,int): ...
Return an indented Newick string, just like ``nw_indent`` in Newick Utilities Args: ``space`` (``int``): The number of spaces a tab should equal Returns: ``str``: An indented Newick string
def minutes_from_utc(self): """ The timezone offset of this point in time object as +/- minutes from UTC. A positive value of the timezone offset indicates minutes east of UTC, and a negative value indicates minutes west of UTC. 0, if this object represents a time inter...
The timezone offset of this point in time object as +/- minutes from UTC. A positive value of the timezone offset indicates minutes east of UTC, and a negative value indicates minutes west of UTC. 0, if this object represents a time interval.
def handle_args_and_set_context(args): """ Args: args: the command line args, probably passed from main() as sys.argv[1:] Returns: a populated Context object based on CLI args """ parser = argparse.ArgumentParser() parser.add_argument("env", help="environment") parser.add_argument("path_to_templat...
Args: args: the command line args, probably passed from main() as sys.argv[1:] Returns: a populated Context object based on CLI args
def console_load_apf(con: tcod.console.Console, filename: str) -> bool: """Update a console from an ASCII Paint `.apf` file.""" return bool( lib.TCOD_console_load_apf(_console(con), filename.encode("utf-8")) )
Update a console from an ASCII Paint `.apf` file.
def to_bytes(self): ''' Takes a list of ICMPv6Option objects and returns a packed byte string of options, appropriately padded if necessary. ''' raw = b'' if not self._options: return raw for icmpv6popt in self._options: raw += icmpv6popt.t...
Takes a list of ICMPv6Option objects and returns a packed byte string of options, appropriately padded if necessary.
def _generateModel0(numCategories): """ Generate the initial, first order, and second order transition probabilities for 'model0'. For this model, we generate the following set of sequences: 1-2-3 (4X) 1-2-4 (1X) 5-2-3 (1X) 5-2-4 (4X) Parameters: --------------------------------------...
Generate the initial, first order, and second order transition probabilities for 'model0'. For this model, we generate the following set of sequences: 1-2-3 (4X) 1-2-4 (1X) 5-2-3 (1X) 5-2-4 (4X) Parameters: ---------------------------------------------------------------------- numCate...
def adict(*classes): '''Install one or more classes to be handled as dict. ''' a = True for c in classes: # if class is dict-like, add class # name to _dict_classes[module] if isclass(c) and _infer_dict(c): t = _dict_classes.get(c.__module__, ()) if c.__...
Install one or more classes to be handled as dict.
def has_child(self, term): """Return True if this GO object has a child GO ID.""" for parent in self.children: if parent.item_id == term or parent.has_child(term): return True return False
Return True if this GO object has a child GO ID.
def open511_convert(input_doc, output_format, serialize=True, **kwargs): """ Convert an Open511 document between formats. input_doc - either an lxml open511 Element or a deserialized JSON dict output_format - short string name of a valid output format, as listed above """ try: output_fo...
Convert an Open511 document between formats. input_doc - either an lxml open511 Element or a deserialized JSON dict output_format - short string name of a valid output format, as listed above
def FindLiteral(self, pattern, data): """Search the data for a hit.""" pattern = utils.Xor(pattern, self.xor_in_key) offset = 0 while 1: # We assume here that data.find does not make a copy of pattern. offset = data.find(pattern, offset) if offset < 0: break yield (off...
Search the data for a hit.