code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def index(self, strictindex): """ Return a chunk in a sequence referenced by index. """ return self._select(self._pointer.index(self.ruamelindex(strictindex)))
Return a chunk in a sequence referenced by index.
def put_key(key_name, value, description, meta, modify, add, lock, key_type, stash, passphrase, backend): """Insert a key to the stash `KEY_NAME` is the name of the key to insert `VALUE`...
Insert a key to the stash `KEY_NAME` is the name of the key to insert `VALUE` is a key=value argument which can be provided multiple times. it is the encrypted value of your key
def _construct_w(self, inputs): """Construct the convolution weight matrix. Figures out the shape of the weight matrix, initialize it, and return it. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: w: A weight matri...
Construct the convolution weight matrix. Figures out the shape of the weight matrix, initialize it, and return it. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: w: A weight matrix of the same type as `inputs` and of s...
def getSubstituteType(self, elt, ps): '''if xsi:type does not match the instance type attr, check to see if it is a derived type substitution. DONT Return the element's type. Parameters: elt -- the DOM element being parsed ps -- the ParsedSoap ob...
if xsi:type does not match the instance type attr, check to see if it is a derived type substitution. DONT Return the element's type. Parameters: elt -- the DOM element being parsed ps -- the ParsedSoap object.
def save_figure_tofile(fig, fmt, fname): """Save fig to fname in the format specified by fmt.""" root, ext = osp.splitext(fname) if ext == '.png' and fmt == 'image/svg+xml': qimg = svg_to_image(fig) qimg.save(fname) else: if fmt == 'image/svg+xml' and is_unicode(fig): ...
Save fig to fname in the format specified by fmt.
def add_categories(self, new_categories, inplace=False): """ Add new categories. `new_categories` will be included at the last/highest place in the categories and will be unused directly after this call. Parameters ---------- new_categories : category or list-li...
Add new categories. `new_categories` will be included at the last/highest place in the categories and will be unused directly after this call. Parameters ---------- new_categories : category or list-like of category The new categories to be included. inplace ...
def plot_spectrum(self, convention='power', unit='per_l', base=10., lmax=None, xscale='lin', yscale='log', grid=True, legend=None, axes_labelsize=None, tick_labelsize=None, show=True, ax=None, fname=None, **kwargs): """ Plot the spectrum ...
Plot the spectrum as a function of spherical harmonic degree. Usage ----- x.plot_spectrum([convention, unit, base, lmax, xscale, yscale, grid, axes_labelsize, tick_labelsize, legend, show, ax, fname, **kwargs]) Parameters ------...
def bandstats(filenames=None, num_sample_points=3, temperature=None, degeneracy_tol=1e-4, parabolic=True): """Calculate the effective masses of the bands of a semiconductor. Args: filenames (:obj:`str` or :obj:`list`, optional): Path to vasprun.xml or vasprun.xml.gz file. If n...
Calculate the effective masses of the bands of a semiconductor. Args: filenames (:obj:`str` or :obj:`list`, optional): Path to vasprun.xml or vasprun.xml.gz file. If no filenames are provided, the code will search for vasprun.xml or vasprun.xml.gz files in folders named ...
def _set_guard(self, v, load=False): """ Setter method for guard, mapped from YANG variable /interface/port_channel/spanning_tree/guard (container) If this variable is read-only (config: false) in the source YANG file, then _set_guard is considered as a private method. Backends looking to populate t...
Setter method for guard, mapped from YANG variable /interface/port_channel/spanning_tree/guard (container) If this variable is read-only (config: false) in the source YANG file, then _set_guard is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
def _make_unique_slug(slug: str, language: str, is_unique: Callable[[str], bool]) -> str: """Guarentees that the specified slug is unique by appending a number until it is unique. Arguments: slug: The slug to make unique. is_unique: Funct...
Guarentees that the specified slug is unique by appending a number until it is unique. Arguments: slug: The slug to make unique. is_unique: Function that can be called to verify whether the generate slug is unique. Return...
def accuracy(self): r"""Return accuracy. Accuracy is defined as :math:`\frac{tp + tn}{population}` Cf. https://en.wikipedia.org/wiki/Accuracy Returns ------- float The accuracy of the confusion table Example ------- >>> ct = Confusi...
r"""Return accuracy. Accuracy is defined as :math:`\frac{tp + tn}{population}` Cf. https://en.wikipedia.org/wiki/Accuracy Returns ------- float The accuracy of the confusion table Example ------- >>> ct = ConfusionTable(120, 60, 20, 30) ...
def optimize(self, loss, num_async_replicas=1, use_tpu=False): """Return a training op minimizing loss.""" lr = learning_rate.learning_rate_schedule(self.hparams) if num_async_replicas > 1: log_info("Dividing learning rate by num_async_replicas: %d", num_async_replicas) lr /= math.s...
Return a training op minimizing loss.
def _validate_j2k_colorspace(self, cparams, colorspace): """ Cannot specify a colorspace with J2K. """ if cparams.codec_fmt == opj2.CODEC_J2K and colorspace is not None: msg = 'Do not specify a colorspace when writing a raw codestream.' raise IOError(msg)
Cannot specify a colorspace with J2K.
def __parse_affiliations_json(self, affiliations, uuid): """Parse identity's affiliations from a json dict""" enrollments = [] for affiliation in affiliations.values(): name = self.__encode(affiliation['name']) try: start_date = str_to_datetime(affiliat...
Parse identity's affiliations from a json dict
def get(self): """Gets the object out of the plasma store. Returns: The object from the plasma store. """ if len(self.call_queue): return self.apply(lambda x: x).get() try: return ray.get(self.oid) except RayTaskError as e: ...
Gets the object out of the plasma store. Returns: The object from the plasma store.
def snooze(self, from_email, duration): """Snooze this incident for `duration` seconds.""" if from_email is None or not isinstance(from_email, six.string_types): raise MissingFromEmail(from_email) endpoint = '/'.join((self.endpoint, self.id, 'snooze')) add_headers = {'from':...
Snooze this incident for `duration` seconds.
def options(self, *args, **kwargs): """XHR cross-domain OPTIONS handler""" self.enable_cache() self.handle_session_cookie() self.preflight() if self.verify_origin(): allowed_methods = getattr(self, 'access_methods', 'OPTIONS, POST') self.set_header('Acces...
XHR cross-domain OPTIONS handler
def get_global_gradient_norm(self) -> float: """ Returns global gradient norm. """ # average norm across executors: exec_norms = [global_norm([arr for arr in exe.grad_arrays if arr is not None]) for exe in self.executors] norm_val = sum(exec_norms) / float(len(exec_norms)...
Returns global gradient norm.
def extract_mime(self, mime, def_mime='unk'): """ Utility function to extract mimetype only from a full content type, removing charset settings """ self['mime'] = def_mime if mime: self['mime'] = self.MIME_RE.split(mime, 1)[0] self['_content_type'] = mime
Utility function to extract mimetype only from a full content type, removing charset settings
def control_group(self, control_group_id, ctrl, shift, alt): """Act on a control group, selecting, setting, etc.""" action = sc_pb.Action() select = action.action_ui.control_group mod = sc_ui.ActionControlGroup if not ctrl and not shift and not alt: select.action = mod.Recall elif ctrl an...
Act on a control group, selecting, setting, etc.
def inv(self): """The inverse rotation""" result = Rotation(self.r.transpose()) result._cache_inv = self return result
The inverse rotation
def _deliverAnswer(self, answer): """ Attempt to deliver an answer to a message sent to this store, via my store's parent's L{IMessageRouter} powerup. @param answer: an L{AlreadyAnswered} that contains an answer to a message sent to this store. """ router = self....
Attempt to deliver an answer to a message sent to this store, via my store's parent's L{IMessageRouter} powerup. @param answer: an L{AlreadyAnswered} that contains an answer to a message sent to this store.
def serialize(transform, **kwargs): '''Serialize a transformation object or pipeline. Parameters ---------- transform : BaseTransform or Pipeline The transformation object to be serialized kwargs Additional keyword arguments to `jsonpickle.encode()` Returns ------- jso...
Serialize a transformation object or pipeline. Parameters ---------- transform : BaseTransform or Pipeline The transformation object to be serialized kwargs Additional keyword arguments to `jsonpickle.encode()` Returns ------- json_str : str A JSON encoding of the ...
async def start(request): """ Begins the session manager for factory calibration, if a session is not already in progress, or if the "force" key is specified in the request. To force, use the following body: { "force": true } :return: The current session ID token or an error message ...
Begins the session manager for factory calibration, if a session is not already in progress, or if the "force" key is specified in the request. To force, use the following body: { "force": true } :return: The current session ID token or an error message
def set_plot_tcrhoc(self,linestyle=['-'],burn_limit=0.997,marker=['o'],markevery=500,end_model=[-1],deg_line=True): ''' Plots HRDs end_model - array, control how far in models a run is plottet, if -1 till end symbs_1 - set symbols of runs ''' if len(linestyle)==0: linestyle=200*['-'] ...
Plots HRDs end_model - array, control how far in models a run is plottet, if -1 till end symbs_1 - set symbols of runs
def parse_duration_with_start(start, duration): """ Attepmt to parse an ISO8601 formatted duration based on a start datetime. Accepts a ``duration`` and a start ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. """ elements = _parse_du...
Attepmt to parse an ISO8601 formatted duration based on a start datetime. Accepts a ``duration`` and a start ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object.
def collapse_witnesses(self): """Groups together witnesses for the same n-gram and work that has the same count, and outputs a single row for each group. This output replaces the siglum field with a sigla field that provides a comma separated list of the witness sigla. Due to th...
Groups together witnesses for the same n-gram and work that has the same count, and outputs a single row for each group. This output replaces the siglum field with a sigla field that provides a comma separated list of the witness sigla. Due to this, it is not necessarily possible to run...
def fetch_suvi_l1b(self, product, correct=True, median_kernel=5): """ Given a product keyword, downloads the SUVI l1b image into the current directory. NOTE: the suvi_l1b_url must be properly set for the Fetcher object :param product: the keyword for the product, e.g. suvi-l1b-fe094 ...
Given a product keyword, downloads the SUVI l1b image into the current directory. NOTE: the suvi_l1b_url must be properly set for the Fetcher object :param product: the keyword for the product, e.g. suvi-l1b-fe094 :param correct: remove nans and negatives :return: tuple of product name, ...
def stream(self, muted=values.unset, hold=values.unset, coaching=values.unset, limit=None, page_size=None): """ Streams ParticipantInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached...
Streams ParticipantInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param bool muted: Whether to return only pa...
def retrieve(self, id) : """ Retrieve a single source Returns a single source available to the user by the provided id If a source with the supplied unique identifier does not exist it returns an error :calls: ``get /sources/{id}`` :param int id: Unique identifier of a ...
Retrieve a single source Returns a single source available to the user by the provided id If a source with the supplied unique identifier does not exist it returns an error :calls: ``get /sources/{id}`` :param int id: Unique identifier of a Source. :return: Dictionary that supp...
def load_mo(self, state, page_idx): """ Loads a memory object from memory. :param page_idx: the index into the page :returns: a tuple of the object """ try: key = next(self._storage.irange(maximum=page_idx, reverse=True)) except StopIteration: ...
Loads a memory object from memory. :param page_idx: the index into the page :returns: a tuple of the object
def _run_xmlsec(self, com_list, extra_args): """ Common code to invoke xmlsec and parse the output. :param com_list: Key-value parameter list for xmlsec :param extra_args: Positional parameters to be appended after all key-value parameters :result: Whatever xmlsec wro...
Common code to invoke xmlsec and parse the output. :param com_list: Key-value parameter list for xmlsec :param extra_args: Positional parameters to be appended after all key-value parameters :result: Whatever xmlsec wrote to an --output temporary file
def showinfo(self): ''' 總覽顯示 ''' print 'money:',self.money print 'store:',self.store print 'avgprice:',self.avgprice
總覽顯示
def reading(self): """Message reading """ sys.stdout.write("{0}Reading package lists...{1} ".format( self.meta.color["GREY"], self.meta.color["ENDC"])) sys.stdout.flush()
Message reading
def remove_kv_store(self, key): """Remove a key-value store entry. :param key: string """ data = { 'operation': 'DELETE', 'key': key } return self.post(self.make_url("/useragent-kv"), data=to_json(data), headers=self.defau...
Remove a key-value store entry. :param key: string
def validateInterfaceName(n): """ Verifies that the supplied name is a valid DBus Interface name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus interface name """ try: if '.' not in n: raise Exception('At least two compo...
Verifies that the supplied name is a valid DBus Interface name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus interface name
def dollars_to_math(source): r""" Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`...
r""" Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`$ or $`), because of strings like...
def geoplot(df, filter=None, n=0, p=0, sort=None, x=None, y=None, figsize=(25, 10), inline=False, by=None, cmap='YlGn', **kwargs): """ Generates a geographical data nullity heatmap, which shows the distribution of missing data across geographic regions. The precise output...
Generates a geographical data nullity heatmap, which shows the distribution of missing data across geographic regions. The precise output depends on the inputs provided. If no geographical context is provided, a quadtree is computed and nullities are rendered as abstract geographic squares. If geographical cont...
def x_vs_y(collection_x, collection_y, title_x=None, title_y=None, width=43, filter_none=False): """ Print a histogram with bins for x to the left and bins of y to the right """ data = merge_x_y(collection_x, collection_y, filter_none) max_value = get_max_x_y(data) bins_total = int(float(max_va...
Print a histogram with bins for x to the left and bins of y to the right
def get_addressbooks(self, order=None, append_remaining=True): """returns list of all defined :class:`AddressBook` objects""" order = order or [] abooks = [] for a in order: if a: if a.abook: abooks.append(a.abook) if append_remaini...
returns list of all defined :class:`AddressBook` objects
def consult_response_hook(self, item_session: ItemSession) -> Actions: '''Return scripting action when a response ends.''' try: return self.hook_dispatcher.call( PluginFunctions.handle_response, item_session ) except HookDisconnected: return Ac...
Return scripting action when a response ends.
def get_telnet_template(auth, url, template_name=None): """ Takes no input, or template_name as input to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authcla...
Takes no input, or template_name as input to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param template_name: str value of template name :retur...
def get_assessment_basic_authoring_session_for_bank(self, bank_id, proxy): """Gets the ``OsidSession`` associated with the assessment authoring service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of a bank arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessme...
Gets the ``OsidSession`` associated with the assessment authoring service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of a bank arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentBasicAuthoringSession) - an ``AssessmentBasicAuthoringSes...
def get_clan_war(self, tag: crtag, **params: keys): """Get inforamtion about a clan's current clan war Parameters ---------- *tag: str A valid clan tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter ...
Get inforamtion about a clan's current clan war Parameters ---------- *tag: str A valid clan tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be included in the response ...
def _datatarget_defaults(args, default_args): """Set data installation targets, handling defaults. Sets variation, rnaseq, smallrna as default targets if we're not isolated to a single method. Provides back compatibility for toolplus specifications. """ default_data = default_args.get("datatar...
Set data installation targets, handling defaults. Sets variation, rnaseq, smallrna as default targets if we're not isolated to a single method. Provides back compatibility for toolplus specifications.
def address(self): """ Should be called to get client direct address @method address @returns {String} client direct address """ if self.isDirect(): base36 = self._iban[4:] asInt = int(base36, 36) return to_checksum_address(pad_left_he...
Should be called to get client direct address @method address @returns {String} client direct address
def _raise_on_error(data: Union[str, dict]) -> None: """Raise the appropriate exception on error.""" if isinstance(data, str): raise_error(data) elif 'status' in data and data['status'] != 'success': raise_error(data['data']['message'])
Raise the appropriate exception on error.
def search(self, query): """ Search the Skype Directory for a user. Args: query (str): name to search for Returns: SkypeUser list: collection of possible results """ results = self.skype.conn("GET", SkypeConnection.API_DIRECTORY, ...
Search the Skype Directory for a user. Args: query (str): name to search for Returns: SkypeUser list: collection of possible results
def cumprod(self, axis=None, skipna=True, *args, **kwargs): """Perform a cumulative product across the DataFrame. Args: axis (int): The axis to take product on. skipna (bool): True to skip NA values, false otherwise. Returns: The cumulative product o...
Perform a cumulative product across the DataFrame. Args: axis (int): The axis to take product on. skipna (bool): True to skip NA values, false otherwise. Returns: The cumulative product of the DataFrame.
def get_job_logs(id): """Get the crawl logs from the job.""" crawler_job = models.CrawlerJob.query.filter_by(id=id).one_or_none() if crawler_job is None: click.secho( ( "CrawlJob %s was not found, maybe it's not a crawl job?" % id ), ...
Get the crawl logs from the job.
def majority_vote_byte_scan(relfilepath, fileslist, outpath, blocksize=65535, default_char_null=False): '''Takes a list of files in string format representing the same data, and disambiguate by majority vote: for position in string, if the character is not the same accross all entries, we keep the major one. If non...
Takes a list of files in string format representing the same data, and disambiguate by majority vote: for position in string, if the character is not the same accross all entries, we keep the major one. If none, it will be replaced by a null byte (because we can't know if any of the entries are correct about this chara...
def get_custom_layouts_active_label(self): """ Provides the default **Custom_Layouts_active_label** widget. :return: Layout active label. :rtype: Active_QLabel """ layout_active_label = Active_QLabel(self, QPixmap(umbra.ui.com...
Provides the default **Custom_Layouts_active_label** widget. :return: Layout active label. :rtype: Active_QLabel
def get_rpms(self): """ Build a list of installed RPMs in the format required for the metadata. """ tags = [ 'NAME', 'VERSION', 'RELEASE', 'ARCH', 'EPOCH', 'SIGMD5', 'SIGPGP:pgpsig', ...
Build a list of installed RPMs in the format required for the metadata.
def focus(self): """ Unsets the focused element """ focus_msg = FocusSignalMsg(None, self._focus) self._focus = None self.focus_signal.emit(focus_msg)
Unsets the focused element
def resample(y, orig_sr, target_sr, res_type='kaiser_best', fix=True, scale=False, **kwargs): """Resample a time series from orig_sr to target_sr Parameters ---------- y : np.ndarray [shape=(n,) or shape=(2, n)] audio time series. Can be mono or stereo. orig_sr : number > 0 [scalar] ...
Resample a time series from orig_sr to target_sr Parameters ---------- y : np.ndarray [shape=(n,) or shape=(2, n)] audio time series. Can be mono or stereo. orig_sr : number > 0 [scalar] original sampling rate of `y` target_sr : number > 0 [scalar] target sampling rate ...
def keep_max_priority_effects(effects): """ Given a list of effects, only keep the ones with the maximum priority effect type. Parameters ---------- effects : list of MutationEffect subclasses Returns list of same length or shorter """ priority_values = map(effect_priority, effects...
Given a list of effects, only keep the ones with the maximum priority effect type. Parameters ---------- effects : list of MutationEffect subclasses Returns list of same length or shorter
def cache_subdirectory( reference_name=None, annotation_name=None, annotation_version=None): """ Which cache subdirectory to use for a given annotation database over a particular reference. All arguments can be omitted to just get the base subdirectory for all pyensembl cached da...
Which cache subdirectory to use for a given annotation database over a particular reference. All arguments can be omitted to just get the base subdirectory for all pyensembl cached datasets.
def get_export_files(cursor, id, version, types, exports_dirs, read_file=True): """Retrieve files associated with document.""" request = get_current_request() type_info = dict(request.registry.settings['_type_info']) metadata = get_content_metadata(id, version, cursor) legacy_id = metadata['legacy_i...
Retrieve files associated with document.
def load(self, content): """Parse yaml content.""" # Try parsing the YAML with global tags try: config = yaml.load(content, Loader=self._loader(self._global_tags)) except yaml.YAMLError: raise InvalidConfigError(_("Config is not valid yaml.")) # Try extra...
Parse yaml content.
def apply_mask(self, mask_img): """First set_mask and the get_masked_data. Parameters ---------- mask_img: nifti-like image, NeuroImage or str 3D mask array: True where a voxel should be used. Can either be: - a file path to a Nifti image ...
First set_mask and the get_masked_data. Parameters ---------- mask_img: nifti-like image, NeuroImage or str 3D mask array: True where a voxel should be used. Can either be: - a file path to a Nifti image - any object with get_data() and get_affin...
def strip(self, chars=None): """ Like str.strip, except it returns the Colr instance. """ return self.__class__( self._str_strip('strip', chars), no_closing=chars and (closing_code in chars), )
Like str.strip, except it returns the Colr instance.
def SMS_me(self, body): """ Quickly send an SMS to yourself. Calls :py:meth:`SMS`. * *stored credential name: PERSONAL_PHONE_NUMBER* :param string body: The content of the SMS message. """ logging.debug('Texting myself') return self.text(self._c...
Quickly send an SMS to yourself. Calls :py:meth:`SMS`. * *stored credential name: PERSONAL_PHONE_NUMBER* :param string body: The content of the SMS message.
def _add_timedeltalike_scalar(self, other): """ Add a delta of a timedeltalike return the i8 result view """ if isna(other): # i.e np.timedelta64("NaT"), not recognized by delta_to_nanoseconds new_values = np.empty(len(self), dtype='i8') new_va...
Add a delta of a timedeltalike return the i8 result view
def set_U(self, U): """Set background zonal flow""" self.Ubg = np.asarray(U)[np.newaxis,...]
Set background zonal flow
def moving_average(data, xcol, ycol, width): """Compute the moving average of YCOL'th column of each sample point in DATA. In particular, for each element I in DATA, this function extracts up to WIDTH*2+1 elements, consisting of I itself, WIDTH elements before I, and WIDTH elements after I. It then comput...
Compute the moving average of YCOL'th column of each sample point in DATA. In particular, for each element I in DATA, this function extracts up to WIDTH*2+1 elements, consisting of I itself, WIDTH elements before I, and WIDTH elements after I. It then computes the mean of the YCOL'th column of these elements...
def scale(self, by): """Scale the points in the Pattern. Parameters ---------- by : float or np.ndarray, shape=(3,) The factor to scale by. If a scalar, scale all directions isotropically. If np.ndarray, scale each direction independently. """ sel...
Scale the points in the Pattern. Parameters ---------- by : float or np.ndarray, shape=(3,) The factor to scale by. If a scalar, scale all directions isotropically. If np.ndarray, scale each direction independently.
def is_token_valid(self, token): """ Checks validity of a given token :param token: Access or refresh token """ try: _tinfo = self.handler.info(token) except KeyError: return False if is_expired(int(_tinfo['exp'])) or _tinfo['black_liste...
Checks validity of a given token :param token: Access or refresh token
def _reset_server_state(self) -> None: """ Clear stored information about the server. """ self.last_helo_response = None self._last_ehlo_response = None self.esmtp_extensions = {} self.supports_esmtp = False self.server_auth_methods = []
Clear stored information about the server.
def _check_timers(self): """ Check for expired timers. If there are any timers that expired, place them in the event queue. """ if self._timer_queue: timer = self._timer_queue[0] if timer['timeout_abs'] < _current_time_millis(): # ...
Check for expired timers. If there are any timers that expired, place them in the event queue.
def group_by(fn: Callable[[T], TR]): """ >>> from Redy.Collections import Flow, Traversal >>> x = [1, '1', 1.0] >>> Flow(x)[Traversal.group_by(type)] """ def inner(seq: ActualIterable[T]) -> Dict[TR, List[T]]: ret = defaultdict(list) for each in seq: ret[fn(each)].ap...
>>> from Redy.Collections import Flow, Traversal >>> x = [1, '1', 1.0] >>> Flow(x)[Traversal.group_by(type)]
def prepare_files(self, finder): """ Prepare process. Create temp directories, download and/or unpack files. """ # make the wheelhouse if self.wheel_download_dir: ensure_dir(self.wheel_download_dir) self._walk_req_to_install( functools.partial(sel...
Prepare process. Create temp directories, download and/or unpack files.
def cli_auth(context): """ Authenticates and then outputs the resulting information. See :py:mod:`swiftly.cli.auth` for context usage information. See :py:class:`CLIAuth` for more information. """ with context.io_manager.with_stdout() as fp: with context.client_manager.with_client() as...
Authenticates and then outputs the resulting information. See :py:mod:`swiftly.cli.auth` for context usage information. See :py:class:`CLIAuth` for more information.
def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir): """Extract an LZMA archive with the lzma Python module.""" return _extract(archive, compression, cmd, 'alone', verbosity, outdir)
Extract an LZMA archive with the lzma Python module.
def modifie_options(self, field_option, value): """Set options in modifications. All options will be stored since it should be grouped in the DB.""" options = dict(self["options"] or {}, **{field_option: value}) self.modifications["options"] = options
Set options in modifications. All options will be stored since it should be grouped in the DB.
def add_tunnel_interface(self, interface_id, address, network_value, zone_ref=None, comment=None): """ Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip ad...
Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip address of interface :param str network_value: network cidr for interface; format: 1.1.1.0/24 :param str zone_ref: zone reference for ...
def get_sstable_data_files(self, ks, table): """ Read sstable data files by using sstableutil, so we ignore temporary files """ p = self.get_sstable_data_files_process(ks=ks, table=table) out, _, _ = handle_external_tool_process(p, ["sstableutil", '--type', 'final', ks, table]) ...
Read sstable data files by using sstableutil, so we ignore temporary files
def _run_hooks(config, hooks, args, environ): """Actually run the hooks.""" skips = _get_skips(environ) cols = _compute_cols(hooks, args.verbose) filenames = _all_filenames(args) filenames = filter_by_include_exclude(filenames, '', config['exclude']) classifier = Classifier(filenames) retval...
Actually run the hooks.
def prevnext(resource): """ Parse a resource to get the prev and next urn :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: (str, str) """ _prev, _next = False, False resource = xmlparse...
Parse a resource to get the prev and next urn :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: (str, str)
def display_latex(*objs, **kwargs): """Display the LaTeX representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw latex data to display. raw : bool Are the data objects raw data or Python objects that need t...
Display the LaTeX representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw latex data to display. raw : bool Are the data objects raw data or Python objects that need to be formatted before display? [def...
def nearby(word): ''' Nearby word ''' w = any2unicode(word) # read from cache if w in _cache_nearby: return _cache_nearby[w] words, scores = [], [] try: for x in _vectors.neighbours(w): words.append(x[0]) scores.append(x[1]) except: pass # ignore key ...
Nearby word
def get_void_volume_surfarea(structure, rad_dict=None, chan_rad=0.3, probe_rad=0.1): """ Computes the volume and surface area of isolated void using Zeo++. Useful to compute the volume and surface area of vacant site. Args: structure: pymatgen Structure containing v...
Computes the volume and surface area of isolated void using Zeo++. Useful to compute the volume and surface area of vacant site. Args: structure: pymatgen Structure containing vacancy rad_dict(optional): Dictionary with short name of elements and their radii. chan_rad(option...
def create_object(container, portal_type, **data): """Creates an object slug :returns: The new created content object :rtype: object """ if "id" in data: # always omit the id as senaite LIMS generates a proper one id = data.pop("id") logger.warn("Passed in ID '{}' omitted! ...
Creates an object slug :returns: The new created content object :rtype: object
def _validate_item(self, item): """Validate char/word count""" if not isinstance(item, six.string_types): raise ValidationError( self._record, "Text list field items must be strings, not '{}'".format(item.__class__) ) words = item.split(' ...
Validate char/word count
def _count_inversions(a, b): '''Count the number of inversions in two numpy arrays: # points i, j where a[i] >= b[j] Parameters ---------- a, b : np.ndarray, shape=(n,) (m,) The arrays to be compared. This implementation is optimized for arrays with many repeated values. ...
Count the number of inversions in two numpy arrays: # points i, j where a[i] >= b[j] Parameters ---------- a, b : np.ndarray, shape=(n,) (m,) The arrays to be compared. This implementation is optimized for arrays with many repeated values. Returns ------- inversio...
def reset(self, path, pretend=False): """ Rolls all of the currently applied migrations back. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool :rtype: count """ self._notes = ...
Rolls all of the currently applied migrations back. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool :rtype: count
def forwards(self, orm): "Write your forwards methods here." # Note: Don't use "from appname.models import ModelName". # Use orm.ModelName to refer to models in this application, # and orm['appname.ModelName'] for models in other applications. print("Updating: JednostkaAdministr...
Write your forwards methods here.
def _format_lines(self, tokensource): """ Just format the tokens, without any wrapping tags. Yield individual lines. """ nocls = self.noclasses lsep = self.lineseparator # for <span style=""> lookup only getcls = self.ttype2class.get c2s = self.cla...
Just format the tokens, without any wrapping tags. Yield individual lines.
def iter_notifications(self, all=False, participating=False, since=None, number=-1, etag=None): """Iterates over the notifications for this repository. :param bool all: (optional), show all notifications, including ones marked as read :param bool participa...
Iterates over the notifications for this repository. :param bool all: (optional), show all notifications, including ones marked as read :param bool participating: (optional), show only the notifications the user is participating in directly :param since: (optional), filt...
def print_exception(etype, value, tb, limit=None, file=None): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception ...
Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError ...
def set_custom(sld, tld, nameservers): ''' Sets domain to use custom DNS servers. returns True if the custom nameservers were set successfully sld SLD of the domain name tld TLD of the domain name nameservers array of strings List of nameservers to be associated with...
Sets domain to use custom DNS servers. returns True if the custom nameservers were set successfully sld SLD of the domain name tld TLD of the domain name nameservers array of strings List of nameservers to be associated with this domain CLI Example: .. code-block::...
def get_scm_status(config, read_modules=False, repo_url=None, mvn_repo_local=None, additional_params=None): """ Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by default, although it can be requested to read the whole available module struct...
Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by default, although it can be requested to read the whole available module structure. :param config: artifact config (ArtifactConfig instance) :param read_modules: if True all modules are read...
def searchZone(self, zone, q=None, has_geo=False, callback=None, errback=None): """ Search a zone for a given search query (e.g., for geological data, etc) :param zone: NOT a string like loadZone - an already loaded ns1.zones.Zone, like one returned from loadZone :return: """ ...
Search a zone for a given search query (e.g., for geological data, etc) :param zone: NOT a string like loadZone - an already loaded ns1.zones.Zone, like one returned from loadZone :return:
def lbrt(self): """Return (left,bottom,right,top) as a tuple.""" return self._left, self._bottom, self._right, self._top
Return (left,bottom,right,top) as a tuple.
def annulus(script, radius=None, radius1=None, radius2=None, diameter=None, diameter1=None, diameter2=None, cir_segments=32, color=None): """Create a 2D (surface) circle or annulus radius1=1 # Outer radius of the circle radius2=0 # Inner radius of the circle (if non-zero it creates an annulus) ...
Create a 2D (surface) circle or annulus radius1=1 # Outer radius of the circle radius2=0 # Inner radius of the circle (if non-zero it creates an annulus) color="" # specify a color name to apply vertex colors to the newly created mesh OpenSCAD: parameters: diameter overrides radius, radius1 & radius2 o...
def _is_nmrstar(string): """Test if input string is in NMR-STAR format. :param string: Input string. :type string: :py:class:`str` or :py:class:`bytes` :return: Input string if in NMR-STAR format or False otherwise. :rtype: :py:class:`str` or :py:obj:`False` """ ...
Test if input string is in NMR-STAR format. :param string: Input string. :type string: :py:class:`str` or :py:class:`bytes` :return: Input string if in NMR-STAR format or False otherwise. :rtype: :py:class:`str` or :py:obj:`False`
def _get_config_fname(): """Helper for the vispy config file""" directory = _get_vispy_app_dir() if directory is None: return None fname = op.join(directory, 'vispy.json') if os.environ.get('_VISPY_CONFIG_TESTING', None) is not None: fname = op.join(_TempDir(), 'vispy.json') retu...
Helper for the vispy config file
def current_site_url(): """Returns fully qualified URL (no trailing slash) for the current site.""" protocol = getattr(settings, 'MY_SITE_PROTOCOL', 'https') port = getattr(settings, 'MY_SITE_PORT', '') url = '%s://%s' % (protocol, settings.SITE_DOMAIN) if port: url += ':%s' % port r...
Returns fully qualified URL (no trailing slash) for the current site.
def rej(vec, vec_onto): """ Vector rejection. Calculated by subtracting from `vec` the projection of `vec` onto `vec_onto`: .. math:: \\mathsf{vec} - \\mathrm{proj}\\left(\\mathsf{vec}, \\ \\mathsf{vec\\_onto}\\right) Parameters ---------- vec length-R |npfloat_| ...
Vector rejection. Calculated by subtracting from `vec` the projection of `vec` onto `vec_onto`: .. math:: \\mathsf{vec} - \\mathrm{proj}\\left(\\mathsf{vec}, \\ \\mathsf{vec\\_onto}\\right) Parameters ---------- vec length-R |npfloat_| -- Vector to reject ...
async def set_as_boot_disk(self): """Set as boot disk for this node.""" await self._handler.set_boot_disk( system_id=self.node.system_id, id=self.id)
Set as boot disk for this node.
def is_network_source_fw(cls, nwk, nwk_name): """Check if SOURCE is FIREWALL, if yes return TRUE. If source is None or entry not in NWK DB, check from Name. Name should have constant AND length should match. """ if nwk is not None: if nwk.source == fw_const.FW_CONST:...
Check if SOURCE is FIREWALL, if yes return TRUE. If source is None or entry not in NWK DB, check from Name. Name should have constant AND length should match.