code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _exclude_on_fail(self, df): """Assign a selection of scenarios as `exclude: True` in meta""" idx = df if isinstance(df, pd.MultiIndex) else _meta_idx(df) self.meta.loc[idx, 'exclude'] = True logger().info('{} non-valid scenario{} will be excluded' .format(len(id...
Assign a selection of scenarios as `exclude: True` in meta
def register_function(self, patterns, instances=None, **reg_kwargs): """Decorator for register.""" def wrapper(function): self.register(patterns, function, instances=instances, **reg_kwargs) return function return wrapper
Decorator for register.
def add_link(self, link): """Add a Link. :type link: :class: `~opencensus.trace.link.Link` :param link: A Link object. """ if isinstance(link, link_module.Link): self.links.append(link) else: raise TypeError("Type Error: received {}, but requires ...
Add a Link. :type link: :class: `~opencensus.trace.link.Link` :param link: A Link object.
def _set_evpn_instance(self, v, load=False): """ Setter method for evpn_instance, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance (list) If this variable is read-only (config: false) in the source YANG file, then _set_evpn_instance is considered as a private method. Backends...
Setter method for evpn_instance, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance (list) If this variable is read-only (config: false) in the source YANG file, then _set_evpn_instance is considered as a private method. Backends looking to populate this variable should do so via c...
def _db_urls(opts: Namespace) -> Tuple[str, str]: """ Return the crc and ontology db urls :param opts: options :return: Tuple w/ crc and ontology url """ return opts.crcdb.replace("//", "//{crcuser}:{crcpassword}@".format(**opts.__dict__)),\ opts.ontodb.replac...
Return the crc and ontology db urls :param opts: options :return: Tuple w/ crc and ontology url
def report_data(self, entity_data): """ Used to report entity data (metrics & snapshot) to the host agent. """ try: response = None response = self.client.post(self.__data_url(), data=self.to_json(entity_data), ...
Used to report entity data (metrics & snapshot) to the host agent.
def recv_file_from_host(src_file, dst_filename, filesize, dst_mode='wb'): """Function which runs on the pyboard. Matches up with send_file_to_remote.""" import sys import ubinascii if HAS_BUFFER: try: import pyb usb = pyb.USB_VCP() except: try: ...
Function which runs on the pyboard. Matches up with send_file_to_remote.
def post_attachment(self, bugid, attachment): '''http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#create-attachment''' assert type(attachment) is DotDict assert 'data' in attachment assert 'file_name' in attachment assert 'summary' in attachment if (n...
http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#create-attachment
def get_value(self, node): """Convert value from an AST node.""" if not isinstance(node, ast.Dict): raise TypeError("must be a dictionary") evaluator = SafeEvaluator() try: value = evaluator.run(node) except Exception as ex: # TODO: Handle err...
Convert value from an AST node.
def accumulate(a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the...
Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function.
def time2internaldate(date_time): """Convert date_time to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The date_time argument can be a number (int or float) representing seconds since epoch (as returned by time.time()), a 9-tuple representing local time...
Convert date_time to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The date_time argument can be a number (int or float) representing seconds since epoch (as returned by time.time()), a 9-tuple representing local time, an instance of time.struct_time (as ...
def search(**criteria): """ Search registered *component* classes matching the given criteria. :param criteria: search criteria of the form: ``a='1', b='x'`` :return: parts registered with the given criteria :rtype: :class:`set` Will return an empty :class:`set` if nothing is found. :: ...
Search registered *component* classes matching the given criteria. :param criteria: search criteria of the form: ``a='1', b='x'`` :return: parts registered with the given criteria :rtype: :class:`set` Will return an empty :class:`set` if nothing is found. :: from cqparts.search import se...
def dist_baystat(src, tar, min_ss_len=None, left_ext=None, right_ext=None): """Return the Baystat distance. This is a wrapper for :py:meth:`Baystat.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison min_ss_len : int ...
Return the Baystat distance. This is a wrapper for :py:meth:`Baystat.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison min_ss_len : int Minimum substring length to be considered left_ext : int Left-sid...
def _getEventFromUid(self, request, uid): """Try and find an event with the given UID in this site.""" event = getEventFromUid(request, uid) # might raise ObjectDoesNotExist home = request.site.root_page if event.get_ancestors().filter(id=home.id).exists(): # only return even...
Try and find an event with the given UID in this site.
def urlopen(self, method, url, redirect=True, **kw): """ Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appr...
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be cho...
def iterable(obj): """Returns ``True`` if *obj* can be iterated over and is *not* a string.""" if isinstance(obj, string_types): return False # avoid iterating over characters of a string if hasattr(obj, 'next'): return True # any iterator will do try: len(obj) # any...
Returns ``True`` if *obj* can be iterated over and is *not* a string.
def release_lock(dax, key, lock_mode=LockMode.wait): """Manually release a pg advisory lock. :dax: a DataAccess instance :key: either a big int or a 2-tuple of integers :lock_mode: a member of the LockMode enum """ lock_fxn = _lock_fxn("unlock", lock_mode, False) return dax.get_scalar( dax.callproc(l...
Manually release a pg advisory lock. :dax: a DataAccess instance :key: either a big int or a 2-tuple of integers :lock_mode: a member of the LockMode enum
def is_import_interface(instrument_interface): """Returns whether the instrument interface passed in is for results import """ if IInstrumentImportInterface.providedBy(instrument_interface): return True # TODO Remove this once classic instrument interface migrated if hasattr(instrument_inte...
Returns whether the instrument interface passed in is for results import
def input(self): """ Input items used for process stored in a dictionary. Keys are the hashes of the input parameters, values the respective InputData classes. """ # the delimiters are used by some input drivers delimiters = dict( zoom=self.init_zoom_...
Input items used for process stored in a dictionary. Keys are the hashes of the input parameters, values the respective InputData classes.
def __validate(data, classes, labels): "Validator of inputs." if not isinstance(data, dict): raise TypeError( 'data must be a dict! keys: sample ID or any unique identifier') if not isinstance(labels, dict): raise TypeError( 'labels must b...
Validator of inputs.
def contains_plural_field(model, fields): """ Returns a boolean indicating if ``fields`` contains a relationship to multiple items. """ source_model = model for orm_path in fields: model = source_model bits = orm_path.lstrip('+-').split('__') for bit in bits[:-1]: field =...
Returns a boolean indicating if ``fields`` contains a relationship to multiple items.
def full_data(self): """ Returns all the info available for the chat in the following format: title [username] (type) <id> If any data is not available, it is not added. """ data = [ self.chat.title, self._username(), self._type(), ...
Returns all the info available for the chat in the following format: title [username] (type) <id> If any data is not available, it is not added.
def load(self): """ Load the file. """ fd = None try: obj = parse_dot_file( self.dot_file.absolute_path ) finally: if fd is not None: fd.close() return obj
Load the file.
def get_indices(self, labels): """ Find the indices of the input ``labels``. Parameters ---------- labels : int, array-like (1D, int) The label numbers(s) to find. Returns ------- indices : int `~numpy.ndarray` An integer array of...
Find the indices of the input ``labels``. Parameters ---------- labels : int, array-like (1D, int) The label numbers(s) to find. Returns ------- indices : int `~numpy.ndarray` An integer array of indices with the same shape as ``label...
def get_connection_details(session, vcenter_resource_model, resource_context): """ Methods retrieves the connection details from the vcenter resource model attributes. :param CloudShellAPISession session: :param VMwarevCenterResourceModel vcenter_resource_model: Instance of VMwarevCente...
Methods retrieves the connection details from the vcenter resource model attributes. :param CloudShellAPISession session: :param VMwarevCenterResourceModel vcenter_resource_model: Instance of VMwarevCenterResourceModel :param ResourceContextDetails resource_context: the context of the command
def calc_trees(self, indices=None, task_interface=None, jobhandler=default_jobhandler, batchsize=1, show_progress=True, **kwargs): """ Infer phylogenetic trees for the loaded Alignments :param indices: Only run inference on the alignments at these given indices :param...
Infer phylogenetic trees for the loaded Alignments :param indices: Only run inference on the alignments at these given indices :param task_interface: Inference tool specified via TaskInterface (default RaxmlTaskInterface) :param jobhandler: Launch jobs via this JobHandler (default SequentialJob...
def add_tag(self, name, value): """ :param name: Name of the tag :type name: string :param value: Value of the tag :type value: string """ self.tags.append(Tag(name, value))
:param name: Name of the tag :type name: string :param value: Value of the tag :type value: string
def compute_balance_median_ts(self, ts): """ Compute the balance at each time 't' of the time series.""" balance = [self.compute_balance_median(ts, t) for t in np.arange(0, len(ts) - 1)] return balance
Compute the balance at each time 't' of the time series.
def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str: """Convert a name field returned by the cryptography module to a string suitable for displaying it to the user. """ # Name_field is supposed to be a Subject or an Issuer; print the CN if there is one common_names...
Convert a name field returned by the cryptography module to a string suitable for displaying it to the user.
def split(self): """ Split a Path2D into multiple Path2D objects where each one has exactly one root curve. Parameters -------------- self : trimesh.path.Path2D Input geometry Returns ------------- split : list of trimesh.path.Path2D Original geometry as separate paths ...
Split a Path2D into multiple Path2D objects where each one has exactly one root curve. Parameters -------------- self : trimesh.path.Path2D Input geometry Returns ------------- split : list of trimesh.path.Path2D Original geometry as separate paths
def name(self, src=None): """Return string representing the name of this type.""" return " & ".join(_get_type_name(tt, src) for tt in self._types)
Return string representing the name of this type.
def desc_from_uri(uri): """Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.c...
Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'``
def get_facets_ranges(self): ''' Returns query facet ranges :: >>> res = solr.query('SolrClient_unittest',{ 'q':'*:*', 'facet':True, 'facet.range':'price', 'facet.range.start':0, 'facet.range.end':100, ...
Returns query facet ranges :: >>> res = solr.query('SolrClient_unittest',{ 'q':'*:*', 'facet':True, 'facet.range':'price', 'facet.range.start':0, 'facet.range.end':100, 'facet.range.gap':10 }) ...
def get_vads_trans_id(vads_site_id, vads_trans_date): """ Returns a default value for vads_trans_id field. vads_trans_id field is mandatory. It is composed by 6 numeric characters that identifies the transaction. There is a unicity contraint between vads_site_id and vads_trans_date (the first 8 cha...
Returns a default value for vads_trans_id field. vads_trans_id field is mandatory. It is composed by 6 numeric characters that identifies the transaction. There is a unicity contraint between vads_site_id and vads_trans_date (the first 8 characters representing the transaction date). We consider t...
def modLocationPort(self, location): """ Ensures that the location port is a the given port value Used in `handleHeader` """ components = urlparse.urlparse(location) reverse_proxy_port = self.father.getHost().port reverse_proxy_host = self.father.getHost().host ...
Ensures that the location port is a the given port value Used in `handleHeader`
def mktns(self, root): """Get/create the target namespace.""" tns = root.get("targetNamespace") prefix = root.findPrefix(tns) if prefix is None: log.debug("warning: tns (%s), not mapped to prefix", tns) prefix = "tns" return (prefix, tns)
Get/create the target namespace.
def addItem(self, itemParameters, filePath=None, overwrite=False, folder=None, dataURL=None, url=None, text=None, relationshipType=None, originItemId=None, dest...
Adds an item to ArcGIS Online or Portal. Te Add Item operation (POST only) is used to upload an item file, submit text content, or submit the item URL to the specified user folder depending on documented items and item types. This operation is available only to the specified user. ...
def add(self, client_id, email_address, name, access_level, password): """Adds a person to a client. Password is optional and if not supplied, an invitation will be emailed to the person""" body = { "EmailAddress": email_address, "Name": name, "AccessLevel": access_le...
Adds a person to a client. Password is optional and if not supplied, an invitation will be emailed to the person
def launchApp(self, **kwargs): """Launch Starcraft2 process in the background using this configuration. WARNING: if the same IP address and port are specified between multiple SC2 process instances, all subsequent processes after the first will fail to initialize and cr...
Launch Starcraft2 process in the background using this configuration. WARNING: if the same IP address and port are specified between multiple SC2 process instances, all subsequent processes after the first will fail to initialize and crash.
def update_intervals(self): ''' Returns a dictionary mapping remote IDs to their intervals, designed to be used for variable update intervals in salt.master.FileserverUpdate. A remote's ID is defined here as a tuple of the GitPython/Pygit2 object's "id" and "name" attributes, wi...
Returns a dictionary mapping remote IDs to their intervals, designed to be used for variable update intervals in salt.master.FileserverUpdate. A remote's ID is defined here as a tuple of the GitPython/Pygit2 object's "id" and "name" attributes, with None being assumed as the "name" valu...
def autodecode(b): """ Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect Args: b (bytes): byte string Returns: str: decoded text string """ import warnings import chardet try: return b.decode() except UnicodeError: ...
Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect Args: b (bytes): byte string Returns: str: decoded text string
def detect_encoding(sample, encoding=None): """Detect encoding of a byte string sample. """ # To reduce tabulator import time from cchardet import detect if encoding is not None: return normalize_encoding(sample, encoding) result = detect(sample) confidence = result['confidence'] or ...
Detect encoding of a byte string sample.
def create_category(cls, category, **kwargs): """Create Category Create a new Category This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_category(category, async=True) >>> result ...
Create Category Create a new Category This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_category(category, async=True) >>> result = thread.get() :param async bool :param ...
def add_filtered_folder(self, path, regex, depth=None, source_type=DefaultSourceType): """ Add a folder source to scan recursively, with a regex filter on directories. :param regex: regex string to filter folders by. :param depth: if provided will be depth limit. 0 = first level only. ...
Add a folder source to scan recursively, with a regex filter on directories. :param regex: regex string to filter folders by. :param depth: if provided will be depth limit. 0 = first level only. :param source_type: what to return; files only, folders only, or both.
def _reset(self, **kwargs): """ Reset after repopulating from API. """ # there are some inconsistenciens in the API regarding these # note: this could be written in fancier ways, but this way is simpler if 'uuid' in kwargs: self.uuid = kwargs['uuid'] ...
Reset after repopulating from API.
def __evaluate_result(self, result, condition): """ Evaluates a result of a heuristic with the condition given in the config. :param mixed result: The result of the heuristic :param mixed condition: The condition string to evaluate on the result :return bool: Whether the...
Evaluates a result of a heuristic with the condition given in the config. :param mixed result: The result of the heuristic :param mixed condition: The condition string to evaluate on the result :return bool: Whether the heuristic result matches the condition
def seek(self, pos=0): """Set the stream's file pointer to pos. Negative seeking is forbidden. """ if pos - self.pos >= 0: blocks, remainder = divmod(pos - self.pos, self.bufsize) for i in range(blocks): self.read(self.bufsize) self....
Set the stream's file pointer to pos. Negative seeking is forbidden.
def makeGlyphsBoundingBoxes(self): """ Make bounding boxes for all the glyphs, and return a dictionary of BoundingBox(xMin, xMax, yMin, yMax) namedtuples keyed by glyph names. The bounding box of empty glyphs (without contours or components) is set to None. Check that th...
Make bounding boxes for all the glyphs, and return a dictionary of BoundingBox(xMin, xMax, yMin, yMax) namedtuples keyed by glyph names. The bounding box of empty glyphs (without contours or components) is set to None. Check that the float values are within the range of the specified ...
def rename_genome(genome_in, genome_out=None): """Rename genome and slugify headers Rename genomes according to a simple naming scheme; this is mainly done to avoid special character weirdness. Parameters ---------- genome_in : file, str or pathlib.Path The input genome to be renamed a...
Rename genome and slugify headers Rename genomes according to a simple naming scheme; this is mainly done to avoid special character weirdness. Parameters ---------- genome_in : file, str or pathlib.Path The input genome to be renamed and slugify. genome_out : file, str or pathlib.Path...
def add_issue_comment(self, issue_id_or_key, content, extra_request_params={}): """ client = BacklogClient("your_space_name", "your_api_key") client.add_issue_comment("YOUR_PROJECT-999", u"or ... else e.") """ request_params = extra_request_params request_params["content"...
client = BacklogClient("your_space_name", "your_api_key") client.add_issue_comment("YOUR_PROJECT-999", u"or ... else e.")
def register_iq_request_coro(self, type_, payload_cls, coro): """ Alias of :meth:`register_iq_request_handler`. .. deprecated:: 0.10 This alias will be removed in version 1.0. """ warnings.warn( "register_iq_request_coro is a deprecated alias to " ...
Alias of :meth:`register_iq_request_handler`. .. deprecated:: 0.10 This alias will be removed in version 1.0.
def get_axis_bin_index(self, value, axis): """Returns index along axis of bin in histogram which contains value Inclusive on both endpoints """ axis = self.get_axis_number(axis) bin_edges = self.bin_edges[axis] # The right bin edge of np.histogram is inclusive: if...
Returns index along axis of bin in histogram which contains value Inclusive on both endpoints
def get_cfg_value(config, section, option): """Get configuration value.""" try: value = config[section][option] except KeyError: if (section, option) in MULTI_OPTIONS: return [] else: return '' if (section, option) in MULTI_OPTIONS: value = split_m...
Get configuration value.
def find_includes(basedirs, source, log=None): """Finds all thrift files included by the given thrift source. :basedirs: A set of thrift source file base directories to look for includes in. :source: The thrift source file to scan for includes. :log: An optional logger """ all_basedirs = [os.path.dirname(...
Finds all thrift files included by the given thrift source. :basedirs: A set of thrift source file base directories to look for includes in. :source: The thrift source file to scan for includes. :log: An optional logger
def packvalue(value, *properties): ''' Store a specified value to specified property path. Often used in nstruct "init" parameter. :param value: a fixed value :param properties: specified field name, same as sizefromlen. :returns: a function which takes a NamedStruct as parameter, and...
Store a specified value to specified property path. Often used in nstruct "init" parameter. :param value: a fixed value :param properties: specified field name, same as sizefromlen. :returns: a function which takes a NamedStruct as parameter, and store the value to property path.
def _structure_recipients_data(cls, recipients): """Converts recipients data into a list of Recipient objects. :param list recipients: list of objects :return: list of Recipient :rtype: list """ try: # That's all due Django 1.7 apps loading. from django.cont...
Converts recipients data into a list of Recipient objects. :param list recipients: list of objects :return: list of Recipient :rtype: list
def diff_one(model1, model2, **kwargs): """Find difference between given peewee models.""" changes = [] fields1 = model1._meta.fields fields2 = model2._meta.fields # Add fields names1 = set(fields1) - set(fields2) if names1: fields = [fields1[name] for name in names1] chang...
Find difference between given peewee models.
def scatter_table(self, x, y, c, s, mark='*'): """Add a data series to the plot. :param x: array containing x-values. :param y: array containing y-values. :param c: array containing values for the color of the mark. :param s: array containing values for the size of the mark. ...
Add a data series to the plot. :param x: array containing x-values. :param y: array containing y-values. :param c: array containing values for the color of the mark. :param s: array containing values for the size of the mark. :param mark: the symbol used to mark the data point. ...
def _on_update_rt_filter(self, peer, new_rts, old_rts): """Handles update of peer RT filter. Parameters: - `peer`: (Peer) whose RT filter has changed. - `new_rts`: (set) of new RTs that peer is interested in. - `old_rts`: (set) of RTs that peers is no longer interest...
Handles update of peer RT filter. Parameters: - `peer`: (Peer) whose RT filter has changed. - `new_rts`: (set) of new RTs that peer is interested in. - `old_rts`: (set) of RTs that peers is no longer interested in.
def cache_makedirs(self, subdir=None): ''' Make necessary directories to hold cache value ''' if subdir is not None: dirname = self.cache_path if subdir: dirname = os.path.join(dirname, subdir) else: dirname = os.path.dirname(se...
Make necessary directories to hold cache value
def get_human_size(size, use_giga=True): '''将文件大小由byte, 转为人类可读的字符串 size - 整数, 文件的大小, 以byte为单位 use_giga - 如果这个选项为False, 那最大的单位就是MegaBytes, 而不会用到 GigaBytes, 这个在显示下载进度时很有用, 因为可以动态的显示下载 状态. ''' size_kb = '{0:,}'.format(size) if size < SIZE_K: return ('{0} B...
将文件大小由byte, 转为人类可读的字符串 size - 整数, 文件的大小, 以byte为单位 use_giga - 如果这个选项为False, 那最大的单位就是MegaBytes, 而不会用到 GigaBytes, 这个在显示下载进度时很有用, 因为可以动态的显示下载 状态.
def get_pipe(self): """ Returns a list that maps the input of the pipe to an elasticsearch object. Will call id_to_object if it cannot serialize the data from json. """ lines = [] for line in sys.stdin: try: lines.append(self.line_to_ob...
Returns a list that maps the input of the pipe to an elasticsearch object. Will call id_to_object if it cannot serialize the data from json.
def convertSequenceMachineSequence(generatedSequences): """ Convert a sequence from the SequenceMachine into a list of sequences, such that each sequence is a list of set of SDRs. """ sequenceList = [] currentSequence = [] for s in generatedSequences: if s is None: sequenceList.append(currentSeq...
Convert a sequence from the SequenceMachine into a list of sequences, such that each sequence is a list of set of SDRs.
def plot_polar( log, title, dataDictionary, pathToOutputPlotsFolder="~/Desktop", dataRange=False, ylabel=False, radius=False, circumference=True, circleTicksRange=(0, 360, 60), circleTicksLabels=".", prependNum=False): """ *...
*Plot a dictionary of numpy lightcurves polynomials* **Key Arguments:** - ``log`` -- logger - ``title`` -- title for the plot - ``dataDictionary`` -- dictionary of data to plot { label01 : dataArray01, label02 : dataArray02 } - ``pathToOutputPlotsFolder`` -- path the the output fold...
def getVersion(init_file): """ Return BUILDBOT_VERSION environment variable, content of VERSION file, git tag or 'latest' """ try: return os.environ['BUILDBOT_VERSION'] except KeyError: pass try: cwd = os.path.dirname(os.path.abspath(init_file)) fn = os.path...
Return BUILDBOT_VERSION environment variable, content of VERSION file, git tag or 'latest'
def tokenize (self, value): """Take a string and break it into tokens. Return the tokens as a list of strings. """ # This code uses a state machine: class STATE: NORMAL = 0 GROUP_PUNCTUATION = 1 PROCESS_HTML_TAG = 2 PROCESS_HTML_E...
Take a string and break it into tokens. Return the tokens as a list of strings.
def Open(pathfileext=None, shot=None, t=None, Dt=None, Mesh=None, Deg=None, Deriv=None, Sep=True, Pos=True, OutPath=None, ReplacePath=None, Ves=None, out='full', Verb=False, Print=True): """ Open a ToFu object saved file This generic open function identifies the required loading rout...
Open a ToFu object saved file This generic open function identifies the required loading routine by detecting how the object was saved from the file name extension. Also, it uses :meth:`~tofu.pathfile.FindSolFile()` to identify the relevant file in case key criteria such as shot, Deg... are provided instead of...
def set_edges(self, name: str, a: np.ndarray, b: np.ndarray, w: np.ndarray, *, axis: int) -> None: """ **DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead """ deprecated("'set_edges' is deprecated. Use 'ds.row_graphs[name] = g' or 'ds.col_graphs[name] = g' instead") try: g =...
**DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead
def _GetIdValue(self, registry_key): """Retrieves the Id value from Task Cache Tree key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Yields: tuple: containing: dfwinreg.WinRegistryKey: Windows Registry key. dfwinreg.WinRegistryValue: Windows Registry va...
Retrieves the Id value from Task Cache Tree key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Yields: tuple: containing: dfwinreg.WinRegistryKey: Windows Registry key. dfwinreg.WinRegistryValue: Windows Registry value.
def executor(self, max_workers=1): """single global executor""" cls = self.__class__ if cls._executor is None: cls._executor = ThreadPoolExecutor(max_workers) return cls._executor
single global executor
def error(self, s): """ Prints out an error message to stderr. :param s: The error string to print :return: None """ print(" ERROR: '%s', %s" % (self.src_id, s), file=sys.stderr)
Prints out an error message to stderr. :param s: The error string to print :return: None
def _remove_dummies(self, to_remove=None, inplace=False): """Works INPLACE""" zmat = self if inplace else self.copy() if to_remove is None: to_remove = zmat._has_removable_dummies() if not to_remove: if inplace: return None else: ...
Works INPLACE
def copy(self): """Return a deep copy""" result = Vector3(self.size, self.deriv) result.x.v = self.x.v result.y.v = self.y.v result.z.v = self.z.v if self.deriv > 0: result.x.d[:] = self.x.d result.y.d[:] = self.y.d result.z.d[:] = self...
Return a deep copy
def check_multi_dimensional_coords(self, ds): ''' Checks that no multidimensional coordinate shares a name with its dimensions. Chapter 5 paragraph 4 We recommend that the name of a [multidimensional coordinate] should not match the name of any of its dimensions. ...
Checks that no multidimensional coordinate shares a name with its dimensions. Chapter 5 paragraph 4 We recommend that the name of a [multidimensional coordinate] should not match the name of any of its dimensions. :param netCDF4.Dataset ds: An open netCDF dataset :rtyp...
def run(self, coords=None, debug=False): """ Run the likelihood grid search """ #self.grid.precompute() self.grid.search(coords=coords) return self.grid
Run the likelihood grid search
def peek(self): """ Returns PeekableIterator.Nothing when the iterator is exhausted. """ try: v = next(self._iter) self._iter = itertools.chain((v,), self._iter) return v except StopIteration: return PeekableIterator.Nothing
Returns PeekableIterator.Nothing when the iterator is exhausted.
def getUsrCfgFilesForPyPkg(pkgName): """ See if the user has one of their own local .cfg files for this task, such as might be created automatically during the save of a read-only package, and return their names. """ # Get the python package and it's .cfg file thePkg, theFile = findCfgFileFo...
See if the user has one of their own local .cfg files for this task, such as might be created automatically during the save of a read-only package, and return their names.
def get_value_in_base_currency(self) -> Decimal: """ Calculates the value of security holdings in base currency """ # check if the currency is the base currency. amt_orig = self.get_value() # Security currency sec_cur = self.get_currency() #base_cur = self.book.default_cu...
Calculates the value of security holdings in base currency
def dcc_connect(self, address, port, dcctype="chat"): """Connect to a DCC peer. Arguments: address -- IP address of the peer. port -- Port to connect to. Returns a DCCConnection instance. """ warnings.warn("Use self.dcc(type).connect()", DeprecationWar...
Connect to a DCC peer. Arguments: address -- IP address of the peer. port -- Port to connect to. Returns a DCCConnection instance.
def _any_would_run(func, filenames, *args): """True if a linter function would be called on any of filenames.""" if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None): return True for filename in filenames: # suppress(E204) stamp_args, stamp_kwargs = _run_lint_on_fi...
True if a linter function would be called on any of filenames.
def quadratic_jacobian_polynomial(nodes): r"""Compute the Jacobian determinant of a quadratic surface. .. note:: This is used **only** by :meth:`Surface._compute_valid` (which is in turn used to compute / cache the :attr:`Surface.is_valid` property). Converts :math:`\det(J(s, t))` to...
r"""Compute the Jacobian determinant of a quadratic surface. .. note:: This is used **only** by :meth:`Surface._compute_valid` (which is in turn used to compute / cache the :attr:`Surface.is_valid` property). Converts :math:`\det(J(s, t))` to a polynomial on the reference triangle an...
def emit(self, signal, message='__nomessagetoken__'): """Emit a signal to the frontend. :param str signal: name of the signal :param message: message to send :returns: return value from frontend emit function :rtype: tornado.concurrent.Future """ # call pre-emit ...
Emit a signal to the frontend. :param str signal: name of the signal :param message: message to send :returns: return value from frontend emit function :rtype: tornado.concurrent.Future
def _pywrap_tensorflow(): """Provide pywrap_tensorflow access in TensorBoard. pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow and needs to be imported using `from tensorflow.python import pywrap_tensorflow`. Therefore, we provide a separate accessor function for it here. NOTE: pywrap...
Provide pywrap_tensorflow access in TensorBoard. pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow and needs to be imported using `from tensorflow.python import pywrap_tensorflow`. Therefore, we provide a separate accessor function for it here. NOTE: pywrap_tensorflow is not part of Tens...
def getchallenge(self): "Return server challenge" self.sock.send(CHALLENGE_PACKET) # wait challenge response for packet in self.read_iterator(self.CHALLENGE_TIMEOUT): if packet.startswith(CHALLENGE_RESPONSE_HEADER): return parse_challenge_response(packet)
Return server challenge
def _parse_dict(element, definition): """Parse xml element by a definition given in dict format. :param element: ElementTree element :param definition: definition schema :type definition: dict :return: parsed xml :rtype: dict """ sub_dict = {} for name, subdef in viewitems(definiti...
Parse xml element by a definition given in dict format. :param element: ElementTree element :param definition: definition schema :type definition: dict :return: parsed xml :rtype: dict
def error_response(self, request, error, **kwargs): """ Return an error to be displayed to the resource owner if anything goes awry. Errors can include invalid clients, authorization denials and other edge cases such as a wrong ``redirect_uri`` in the authorization request. ...
Return an error to be displayed to the resource owner if anything goes awry. Errors can include invalid clients, authorization denials and other edge cases such as a wrong ``redirect_uri`` in the authorization request. :param request: :attr:`django.http.HttpRequest` :param error...
def generate_ha_relation_data(service, extra_settings=None): """ Generate relation data for ha relation Based on configuration options and unit interfaces, generate a json encoded dict of relation data items for the hacluster relation, providing configuration for DNS HA or VIP's + haproxy clone sets. ...
Generate relation data for ha relation Based on configuration options and unit interfaces, generate a json encoded dict of relation data items for the hacluster relation, providing configuration for DNS HA or VIP's + haproxy clone sets. Example of supplying additional settings:: COLO_CONSOLEA...
def Reverse(self, copy=False): """ Reverse the order of the points """ numPoints = self.GetN() if copy: revGraph = self.Clone() else: revGraph = self X = self.GetX() EXlow = self.GetEXlow() EXhigh = self.GetEXhigh() ...
Reverse the order of the points
def fit(self, X=None, u=None, s = None): """Fit X into an embedded space. Inputs ---------- X : array, shape (n_samples, n_features) u,s,v : svd decomposition of X (optional) Assigns ---------- embedding : array-like, shape (n_samples, n_components) ...
Fit X into an embedded space. Inputs ---------- X : array, shape (n_samples, n_features) u,s,v : svd decomposition of X (optional) Assigns ---------- embedding : array-like, shape (n_samples, n_components) Stores the embedding vectors. u,sv,v ...
async def declareWorkerType(self, *args, **kwargs): """ Update a worker-type Declare a workerType, supplying some details about it. `declareWorkerType` allows updating one or more properties of a worker-type as long as the required scopes are possessed. For example, a request t...
Update a worker-type Declare a workerType, supplying some details about it. `declareWorkerType` allows updating one or more properties of a worker-type as long as the required scopes are possessed. For example, a request to update the `gecko-b-1-w2008` worker-type within the `aws-provisioner-v...
def wait(self, timeout=None): """Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method releases the underlying lock, and then blocks until it is awakened by a notify() or ...
Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method releases the underlying lock, and then blocks until it is awakened by a notify() or notifyAll() call for the same condition ...
def get(self, path): """ Get the content of a file, indentified by its path relative to the folder configured in PyGreen. If the file extension is one of the extensions that should be processed through Mako, it will be processed. """ data = self.app.test_client().get("/%s...
Get the content of a file, indentified by its path relative to the folder configured in PyGreen. If the file extension is one of the extensions that should be processed through Mako, it will be processed.
def cli(ctx, name, dname, license_key, ips_version, force, enable, ssl, spdy, gzip, cache, install, dev): """ Downloads and installs a new instance of the latest Invision Power Suite release. """ assert isinstance(ctx, Context) login_session = ctx.get_login() log = logging.getLogger('ipsv.new') ...
Downloads and installs a new instance of the latest Invision Power Suite release.
def make_unicode(string): """ Python 2 and 3 compatibility function that converts a string to Unicode. In case of Unicode, the string is returned unchanged :param string: input string :return: Unicode string """ if sys.version < '3' and isinstance(string, str): return unicode(string....
Python 2 and 3 compatibility function that converts a string to Unicode. In case of Unicode, the string is returned unchanged :param string: input string :return: Unicode string
def _RetryRequest(self, timeout=None, **request_args): """Retry the request a few times before we determine it failed. Sometimes the frontend becomes loaded and issues a 500 error to throttle the clients. We wait Client.error_poll_min seconds between each attempt to back off the frontend. Note that thi...
Retry the request a few times before we determine it failed. Sometimes the frontend becomes loaded and issues a 500 error to throttle the clients. We wait Client.error_poll_min seconds between each attempt to back off the frontend. Note that this does not affect any timing algorithm in the client itsel...
def get_blog_context(context): """ Get context data useful on all blog related pages """ context['authors'] = get_user_model().objects.filter( owned_pages__live=True, owned_pages__content_type__model='blogpage' ).annotate(Count('owned_pages')).order_by('-owned_pages__count') context['all...
Get context data useful on all blog related pages
def standardise_quotes(self, val): """ Change the quotes used to wrap a value to the pprint default E.g. "val" to 'val' or 'val' to "val" """ if self._in_quotes(val, self.altquote): middle = self.remove_quotes(val) val = self.add_quotes(middle) re...
Change the quotes used to wrap a value to the pprint default E.g. "val" to 'val' or 'val' to "val"
def normalized_per_object(image, labels): """Normalize the intensities of each object to the [0, 1] range.""" nobjects = labels.max() objects = np.arange(nobjects + 1) lmin, lmax = scind.extrema(image, labels, objects)[:2] # Divisor is the object's max - min, or 1 if they are the same. divisor =...
Normalize the intensities of each object to the [0, 1] range.
def qn_df(df, axis='row', keep_orig=False): ''' do quantile normalization of a dataframe dictionary, does not write to net ''' df_qn = {} for mat_type in df: inst_df = df[mat_type] # using transpose to do row qn if axis == 'row': inst_df = inst_df.transpose() missing_values = inst_df....
do quantile normalization of a dataframe dictionary, does not write to net
def form_invalid(self, post_form, attachment_formset, poll_option_formset, **kwargs): """ Processes invalid forms. """ poll_errors = [k for k in post_form.errors.keys() if k.startswith('poll_')] if ( poll_errors or ( poll_option_formset and ...
Processes invalid forms.