code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _set_port_to_port_profile_domain_association(self, v, load=False): """ Setter method for port_to_port_profile_domain_association, mapped from YANG variable /interface/port_channel/port_profile_to_interface_associations/port_profile_port/port_to_port_profile_domain_association (container) If this variabl...
Setter method for port_to_port_profile_domain_association, mapped from YANG variable /interface/port_channel/port_profile_to_interface_associations/port_profile_port/port_to_port_profile_domain_association (container) If this variable is read-only (config: false) in the source YANG file, then _set_port_to_port_...
def setmodulation(self, modu): """Set the interface modulation. It can be: - 0: dsss - 1: fhss - 2: irbaseband - 3: ofdm - 4: hrdss - 5: erp - 6: ht - 7: vht - 8: ihv - 9: mimo-ofdm - 10: mim...
Set the interface modulation. It can be: - 0: dsss - 1: fhss - 2: irbaseband - 3: ofdm - 4: hrdss - 5: erp - 6: ht - 7: vht - 8: ihv - 9: mimo-ofdm - 10: mimo-ofdm - the value directly ...
def initialize_pymol(options): """Initializes PyMOL""" import pymol # Pass standard arguments of function to prevent PyMOL from printing out PDB headers (workaround) pymol.finish_launching(args=['pymol', options, '-K']) pymol.cmd.reinitialize()
Initializes PyMOL
def gather_verify_arguments(self): """ Need to add some information before running verify() :return: dictionary with arguments to the verify call """ kwargs = {'client_id': self.service_context.client_id, 'iss': self.service_context.issuer, '...
Need to add some information before running verify() :return: dictionary with arguments to the verify call
def _vector_pattern_uniform_op_right(func): """decorator for operator overloading when VectorPatternUniform is on the right""" @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return TransversePatternUniform(func(self, self._tdsph...
decorator for operator overloading when VectorPatternUniform is on the right
def _rearrange_output_for_package(self, target_workdir, java_package): """Rearrange the output files to match a standard Java structure. Antlr emits a directory structure based on the relative path provided for the grammar file. If the source root of the file is different from the Pants build root, the...
Rearrange the output files to match a standard Java structure. Antlr emits a directory structure based on the relative path provided for the grammar file. If the source root of the file is different from the Pants build root, then the Java files end up with undesired parent directories.
def getflags(fd): """ Gets per-file filesystem flags. """ flags_ptr = ffi.new('uint64_t*') flags_buf = ffi.buffer(flags_ptr) fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf) return flags_ptr[0]
Gets per-file filesystem flags.
def get_build_work_items_refs(self, project, build_id, top=None): """GetBuildWorkItemsRefs. Gets the work items associated with a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :param int top: The maximum number of work items to re...
GetBuildWorkItemsRefs. Gets the work items associated with a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :param int top: The maximum number of work items to return. :rtype: [ResourceRef]
def handle_minute_close(self, dt, data_portal): """ Handles the close of the given minute in minute emission. Parameters ---------- dt : Timestamp The minute that is ending Returns ------- A minute perf packet. """ self.sync_l...
Handles the close of the given minute in minute emission. Parameters ---------- dt : Timestamp The minute that is ending Returns ------- A minute perf packet.
def _validate_region(self): """Validate region was passed in and is a valid GCE zone.""" if not self.region: raise GCECloudException( 'Zone is required for GCE cloud framework: ' 'Example: us-west1-a' ) try: zone = self.compute...
Validate region was passed in and is a valid GCE zone.
def set_state(self, sync_data): """Called when a state is received from the front-end.""" # The order of these context managers is important. Properties must # be locked when the hold_trait_notification context manager is # released and notifications are fired. with self._lock_pr...
Called when a state is received from the front-end.
def validate_group(images): """Validates that the combination of folder and name for all images in a group is unique. Raises a ValueError exception if uniqueness constraint is violated. Parameters ---------- images : List(GroupImage) List of images in group ...
Validates that the combination of folder and name for all images in a group is unique. Raises a ValueError exception if uniqueness constraint is violated. Parameters ---------- images : List(GroupImage) List of images in group
def read_mol2_from_list(self, mol2_lines, mol2_code, columns=None): r"""Reads Mol2 file from a list into DataFrames Attributes ---------- mol2_lines : list A list of lines containing the mol2 file contents. For example, ['@<TRIPOS>MOLECULE\n', 'ZINC3...
r"""Reads Mol2 file from a list into DataFrames Attributes ---------- mol2_lines : list A list of lines containing the mol2 file contents. For example, ['@<TRIPOS>MOLECULE\n', 'ZINC38611810\n', ' 65 68 0 0 0\n', 'SM...
def get_checkout(self, checkout_id, **params): """https://developers.coinbase.com/api/v2#show-a-checkout""" response = self._get('v2', 'checkouts', checkout_id, params=params) return self._make_api_object(response, Checkout)
https://developers.coinbase.com/api/v2#show-a-checkout
def _fast_count_smallints(arr): """Faster version of set(arr) for sequences of small numbers.""" counts = np.bincount(arr.astype(np.int_)) nz = counts.nonzero()[0] return np.c_[nz, counts[nz]]
Faster version of set(arr) for sequences of small numbers.
def compare_dbs(self, db_x, db_y, show=True): """Compare the tables and row counts of two databases.""" # TODO: Improve method self._printer("\tComparing database's {0} and {1}".format(db_x, db_y)) # Run compare_dbs_getter to get row counts x = self._compare_dbs_getter(db_x) ...
Compare the tables and row counts of two databases.
def mark_fit_good(self, fit, spec=None): """ Marks fit good so it is used in high level means Parameters ---------- fit : fit to mark good spec : specimen of fit to mark good (optional though runtime will increase if not provided) """ if spec ...
Marks fit good so it is used in high level means Parameters ---------- fit : fit to mark good spec : specimen of fit to mark good (optional though runtime will increase if not provided)
def tournament_game(n, k, random_state=None): """ Return a NormalFormGame instance of the 2-player win-lose game, whose payoffs are either 0 or 1, introduced by Anbalagan et al. (2013). Player 0 has n actions, which constitute the set of nodes {0, ..., n-1}, while player 1 has n choose k actions, ea...
Return a NormalFormGame instance of the 2-player win-lose game, whose payoffs are either 0 or 1, introduced by Anbalagan et al. (2013). Player 0 has n actions, which constitute the set of nodes {0, ..., n-1}, while player 1 has n choose k actions, each corresponding to a subset of k elements of the set ...
def _get_assumptions(t): """ Given a constraint, _get_assumptions() returns a set of constraints that are implicitly assumed to be true. For example, `x <= 10` would return `x >= 0`. """ if t.op in ('__le__', '__lt__', 'ULE', 'ULT'): return [ t.args[0] >= 0 ] ...
Given a constraint, _get_assumptions() returns a set of constraints that are implicitly assumed to be true. For example, `x <= 10` would return `x >= 0`.
async def _request( self, method: str, url: str, *, headers: dict = None, params: dict = None, json: dict = None) -> dict: """Make a request against AirVisual.""" full_url = '{0}/{1}'.format(url, self.zip_code) p...
Make a request against AirVisual.
def lstrip(self, set=" "): """ Return a copy of the column with leading characters removed. The set argument is a string specifying the set of characters to be removed. If omitted, the set argument defaults to removing whitespace. :param character set: The set of characters to ...
Return a copy of the column with leading characters removed. The set argument is a string specifying the set of characters to be removed. If omitted, the set argument defaults to removing whitespace. :param character set: The set of characters to lstrip from strings in column. :returns...
def _handle_enum(self, node, scope, ctxt, stream): """Handle enum nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling enum") if node.type is None: enum_cls = fields.Int else: ...
Handle enum nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
def relpath(path, start): """Get relative path to start. Note: Modeled after python2.6 :meth:`os.path.relpath`. """ path_items = path_list(path) start_items = path_list(start) # Find common parts of path. common = [] for pth, stt in zip(path_items, start_items): if pth != stt: ...
Get relative path to start. Note: Modeled after python2.6 :meth:`os.path.relpath`.
def _reporthook(t): """ ``reporthook`` to use with ``urllib.request`` that prints the process of the download. Uses ``tqdm`` for progress bar. **Reference:** https://github.com/tqdm/tqdm Args: t (tqdm.tqdm) Progress bar. Example: >>> with tqdm(unit='B', unit_scale=True, minit...
``reporthook`` to use with ``urllib.request`` that prints the process of the download. Uses ``tqdm`` for progress bar. **Reference:** https://github.com/tqdm/tqdm Args: t (tqdm.tqdm) Progress bar. Example: >>> with tqdm(unit='B', unit_scale=True, miniters=1, desc=filename) as t: ...
def convert_timestamp(timestamp): """ Converts bokehJS timestamp to datetime64. """ datetime = dt.datetime.utcfromtimestamp(timestamp/1000.) return np.datetime64(datetime.replace(tzinfo=None))
Converts bokehJS timestamp to datetime64.
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.comments_1 = None else: self.comments_1 = vals[i] i += 1
Read values. Args: vals (list): list of strings representing values
def on_natural_language(keywords: Union[Optional[Iterable], Callable] = None, *, permission: int = perm.EVERYBODY, only_to_me: bool = True, only_short_message: bool = True, allow_empty_message: bool = False) -> Callable: ...
Decorator to register a function as a natural language processor. :param keywords: keywords to respond to, if None, respond to all messages :param permission: permission required by the processor :param only_to_me: only handle messages to me :param only_short_message: only handle short messages :pa...
def has_filename(self, filename): """Return the self.data index position for the filename. Args: filename: Name of the file to search for in self.data. Returns: The self.data index for the filename. Returns None if the filename is not found in self....
Return the self.data index position for the filename. Args: filename: Name of the file to search for in self.data. Returns: The self.data index for the filename. Returns None if the filename is not found in self.data.
def values(self, *keys): """ Return the values of the record, optionally filtering to include only certain values by index or key. :param keys: indexes or keys of the items to include; if none are provided, all values will be included :return: list of values ...
Return the values of the record, optionally filtering to include only certain values by index or key. :param keys: indexes or keys of the items to include; if none are provided, all values will be included :return: list of values
def checkAndCreate(self, key, payload, osIds): """ Function checkAndCreate Check if an architectures exists and create it if not @param key: The targeted architectures @param payload: The targeted architectures description @param osIds: The list of os ids liked with this archite...
Function checkAndCreate Check if an architectures exists and create it if not @param key: The targeted architectures @param payload: The targeted architectures description @param osIds: The list of os ids liked with this architecture @return RETURN: The id of the object
def template_str(self): """Class property that returns a populated template string This property allows the template of a particular process to be dynamically generated and returned when doing ``Process.template_str``. Returns ------- x : str String with the...
Class property that returns a populated template string This property allows the template of a particular process to be dynamically generated and returned when doing ``Process.template_str``. Returns ------- x : str String with the complete and populated process tem...
def cnvlTcOld(idxPrc, aryPrfTcChunk, varTr, varNumVol, queOut): """ Old version: Convolution of time courses with one canonical HRF model. """ # Create 'canonical' HRF time course model: vecHrf = funcHrf(varNumVol, varTr) # adjust the ...
Old version: Convolution of time courses with one canonical HRF model.
def retry(default=None): """Retry functions after failures""" def decorator(func): """Retry decorator""" @functools.wraps(func) def _wrapper(*args, **kw): for pos in range(1, MAX_RETRIES): try: return func(*args, **kw) exc...
Retry functions after failures
def get_components(self, which): """ Get the component name dictionary for the desired object. The returned dictionary maps component names on this class to component names on the desired object. Parameters ---------- which : str Can either be ``'pos...
Get the component name dictionary for the desired object. The returned dictionary maps component names on this class to component names on the desired object. Parameters ---------- which : str Can either be ``'pos'`` or ``'vel'`` to get the components for the ...
def get_current_activities(self, login=None, **kwargs): """Get the current activities of user. Either use the `login` param, or the client's login if unset. :return: JSON """ _login = kwargs.get( 'login', login or self._login ) _activity_...
Get the current activities of user. Either use the `login` param, or the client's login if unset. :return: JSON
def process_samples_table(samples_table, instruments_table, mef_transform_fxns=None, beads_table=None, base_dir=".", verbose=False, plot=False, ...
Process flow cytometry samples, as specified by an input table. The function processes each entry in `samples_table`, and does the following: - Load the FCS file specified in the field "File Path". - Transform the forward scatter/side scatter to RFI. - Transform the fluorescence channel...
def requirements(requirements_file): """Return packages mentioned in the given file. Args: requirements_file (str): path to the requirements file to be parsed. Returns: (list): 3rd-party package dependencies contained in the file. """ return [ str(pkg.req) for pkg in parse_...
Return packages mentioned in the given file. Args: requirements_file (str): path to the requirements file to be parsed. Returns: (list): 3rd-party package dependencies contained in the file.
def update_shared_file(self, sharekey=None, title=None, description=None): """ Update the editable details (just the title and description) of a SharedFile. Args: sharekey (str): Sharekey of the...
Update the editable details (just the title and description) of a SharedFile. Args: sharekey (str): Sharekey of the SharedFile to update. title (Optional[str]): Title of the SharedFile. description (Optional[str]): Description of the SharedFile Returns: ...
def build_js_from_template(self, template_file, variables): """ Build a JS script from a template and args @type template_file: str @param template_file: Script template to implement; can be the name of a built-in script or full filepath to a js file...
Build a JS script from a template and args @type template_file: str @param template_file: Script template to implement; can be the name of a built-in script or full filepath to a js file that contains the script. E.g. 'clickElementTemplate.js', ...
def get_drive_api(): """ Get drive API client based on settings. """ settings = Settings() if settings.credentials: return get_drive_api_from_file(settings.credentials_path) if settings.client_secrets: return get_drive_api_from_client_secrets(settings.client_secrets_path)
Get drive API client based on settings.
def remove_callback(instance, prop, callback): """ Remove a callback function from a property in an instance Parameters ---------- instance The instance to detach the callback from prop : str Name of callback property in `instance` callback : func The callback functi...
Remove a callback function from a property in an instance Parameters ---------- instance The instance to detach the callback from prop : str Name of callback property in `instance` callback : func The callback function to remove
def get_modpath_from_modname(modname, prefer_pkg=False, prefer_main=False): """ Same as get_modpath but doesnt import directly SeeAlso: get_modpath """ from os.path import dirname, basename, join, exists initname = '__init__.py' mainname = '__main__.py' if modname in sys.modules...
Same as get_modpath but doesnt import directly SeeAlso: get_modpath
def get(key, profile=None): ''' Get a value from sqlite3 ''' if not profile: return None _, cur, table = _connect(profile) q = profile.get('get_query', ('SELECT value FROM {0} WHERE ' 'key=:key'.format(table))) res = cur.execute(q, {'key': key}) ...
Get a value from sqlite3
def _vmomentdensity(self,R,z,n,m,o,nsigma=None,mc=False,nmc=10000, _returnmc=False,_vrs=None,_vts=None,_vzs=None, _rawgausssamples=False, gl=False,ngl=_DEFAULTNGL,_returngl=False,_glqeval=None, _return_actions=False,_jr=None,_lz...
Non-physical version of vmomentdensity, otherwise the same
def _insert_dLbl_in_sequence(self, idx): """ Return a newly created `c:dLbl` element having `c:idx` child of *idx* and inserted in numeric sequence among the `c:dLbl` children of this element. """ new_dLbl = self._new_dLbl() new_dLbl.idx.val = idx dLbl = ...
Return a newly created `c:dLbl` element having `c:idx` child of *idx* and inserted in numeric sequence among the `c:dLbl` children of this element.
def destroy(name, stop=False, path=None): ''' Destroy the named container. .. warning:: Destroys all data associated with the container. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 stop : False If ``True``, the c...
Destroy the named container. .. warning:: Destroys all data associated with the container. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 stop : False If ``True``, the container will be destroyed even if it is runni...
def report(self): """ Print report of work at the end """ # We need only the first 4 significant digits tt = (str(self._endtime - self._starttime))[:4] self.log('\n%s finished in %s seconds.' % (__pkg_name__, tt)) self.log('%d directories parsed, %d files copied' % ...
Print report of work at the end
def kwonly_args(kws, required, withdefaults=(), leftovers=False): """ Based on the snippet by Eric Snow http://code.activestate.com/recipes/577940 SPDX-License-Identifier: MIT """ if hasattr(withdefaults, 'items'): # allows for OrderedDict to be passed withdefaults = withdefaul...
Based on the snippet by Eric Snow http://code.activestate.com/recipes/577940 SPDX-License-Identifier: MIT
def piece(piece: chess.Piece, size: Optional[int] = None) -> str: """ Renders the given :class:`chess.Piece` as an SVG image. >>> import chess >>> import chess.svg >>> >>> chess.svg.piece(chess.Piece.from_symbol("R")) # doctest: +SKIP .. image:: ../docs/wR.svg """ svg = _svg(SQUAR...
Renders the given :class:`chess.Piece` as an SVG image. >>> import chess >>> import chess.svg >>> >>> chess.svg.piece(chess.Piece.from_symbol("R")) # doctest: +SKIP .. image:: ../docs/wR.svg
def _create_properties(self): """Populate a frame with a list of all editable properties""" self._frame = f = ttk.Labelframe(self._sframe.innerframe, text=_('Widget properties')) f.grid(sticky='nswe') label_tpl = "{0}:" row = 0 co...
Populate a frame with a list of all editable properties
def smote(X, y, cost_mat=None, per=0.5): """SMOTE: synthetic minority over-sampling technique Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cos...
SMOTE: synthetic minority over-sampling technique Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4], op...
def emoticons_filter(content, exclude='', autoescape=None): """ Filter for rendering emoticons. """ esc = autoescape and conditional_escape or (lambda x: x) content = mark_safe(replace_emoticons(esc(content), exclude)) return content
Filter for rendering emoticons.
def cli(env, package_keyname, location, preset, verify, billing, complex_type, quantity, extras, order_items): """Place or verify an order. This CLI command is used for placing/verifying an order of the specified package in the given location (denoted by a datacenter's long name). Orders made via t...
Place or verify an order. This CLI command is used for placing/verifying an order of the specified package in the given location (denoted by a datacenter's long name). Orders made via the CLI can then be converted to be made programmatically by calling SoftLayer.OrderingManager.place_order() with the s...
def get_profile(session): """Get complete profile.""" try: profile = session.get(PROFILE_URL).json() if 'errorCode' in profile and profile['errorCode'] == '403': raise MoparError("not logged in") return profile except JSONDecodeError: raise MoparError("not logged ...
Get complete profile.
def entropy(state): """ Compute the von-Neumann entropy of a quantum state. Args: state (array_like): a density matrix or state vector. Returns: float: The von-Neumann entropy S(rho). """ rho = np.array(state) if rho.ndim == 1: return 0 evals = np.maximum(np.li...
Compute the von-Neumann entropy of a quantum state. Args: state (array_like): a density matrix or state vector. Returns: float: The von-Neumann entropy S(rho).
def _version_find_existing(): """Returns set of existing versions in this repository. This information is backed by previously used version tags in git. Available tags are pulled from origin repository before. :return: available versions :rtype: set """ _tool_run('git fetch...
Returns set of existing versions in this repository. This information is backed by previously used version tags in git. Available tags are pulled from origin repository before. :return: available versions :rtype: set
def handle_next_export(self): """ Retrieve and fully evaluate the next export task, including resolution of any sub-tasks requested by the import client such as requests for binary data, observation, etc. :return: An instance of ExportStateCache, the 'state' field contains t...
Retrieve and fully evaluate the next export task, including resolution of any sub-tasks requested by the import client such as requests for binary data, observation, etc. :return: An instance of ExportStateCache, the 'state' field contains the state of the export after running as many ...
def main(params=None): """ Main loop for the enumeration Args: ----- params: A list with the parameters as grabbed by the terminal. It is None when this is called by an entry_point. """ # Grabbing the parser parser = getParser() if params != None: ...
Main loop for the enumeration Args: ----- params: A list with the parameters as grabbed by the terminal. It is None when this is called by an entry_point.
def DbMySqlSelect(self, argin): """ This is a very low level command. It executes the specified SELECT command on TANGO database and returns its result without filter. :param argin: MySql Select command :type: tango.DevString :return: MySql Select command result - sval...
This is a very low level command. It executes the specified SELECT command on TANGO database and returns its result without filter. :param argin: MySql Select command :type: tango.DevString :return: MySql Select command result - svalues : select results - lvalue[n] : ...
def get_full_name(self, role, name): """ If ``name`` is already the full name of an object, return ``name``. Otherwise, if ``name`` is a partial object name, look up the full name and return it. """ # An initial '.' indicates a partial name if name[0] == '.': ...
If ``name`` is already the full name of an object, return ``name``. Otherwise, if ``name`` is a partial object name, look up the full name and return it.
def remove_tab(self, tab=0): """ Removes the tab by index. """ # pop it from the list t = self.tabs.pop(tab) # remove it from the gui self._widget.removeTab(tab) # return it in case someone cares return t
Removes the tab by index.
def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy(''.join(sys.stdin.readlines()).rstrip('\n')) else: # paste output print(paste())
Entry point for cli.
def Analyze(self, hashes): """Looks up hashes in Viper using the Viper HTTP API. Args: hashes (list[str]): hashes to look up. Returns: list[HashAnalysis]: hash analysis. Raises: RuntimeError: If no host has been set for Viper. """ hash_analyses = [] for digest in hashes:...
Looks up hashes in Viper using the Viper HTTP API. Args: hashes (list[str]): hashes to look up. Returns: list[HashAnalysis]: hash analysis. Raises: RuntimeError: If no host has been set for Viper.
async def emit(self, record: LogRecord): # type: ignore """ Actually log the specified logging record to the stream. """ if self.writer is None: self.writer = await self._init_writer() try: msg = self.format(record) + self.terminator self.wr...
Actually log the specified logging record to the stream.
def convert(b): ''' takes a number of bytes as an argument and returns the most suitable human readable unit conversion. ''' if b > 1024**3: hr = round(b/1024**3) unit = "GB" elif b > 1024**2: hr = round(b/1024**2) unit = "MB" else: hr = round(b/1024) ...
takes a number of bytes as an argument and returns the most suitable human readable unit conversion.
def _send_command(self, method_name, data=None): """Sends a command to API. :param str method_name: :param dict data: :return: """ try: response = self.lib.post(self._tpl_url % {'token': self.auth_token, 'method': method_name}, data=data) json = r...
Sends a command to API. :param str method_name: :param dict data: :return:
def check_requisite(self, low, running, chunks, pre=False): ''' Look into the running data to check the status of all requisite states ''' disabled_reqs = self.opts.get('disabled_requisites', []) if not isinstance(disabled_reqs, list): disabled_reqs = [disable...
Look into the running data to check the status of all requisite states
def msvc14_gen_lib_options(*args, **kwargs): """ Patched "distutils._msvccompiler.gen_lib_options" for fix compatibility between "numpy.distutils" and "distutils._msvccompiler" (for Numpy < 1.11.2) """ if "numpy.distutils" in sys.modules: import numpy as np if LegacyVersion(np.__...
Patched "distutils._msvccompiler.gen_lib_options" for fix compatibility between "numpy.distutils" and "distutils._msvccompiler" (for Numpy < 1.11.2)
def _run(name, cmd, output=None, no_start=False, stdin=None, python_shell=True, preserve_state=False, output_loglevel='debug', ignore_retcode=False, use_vt=False, keep_env=None): ''' Common logic for nspawn.run functions ...
Common logic for nspawn.run functions
def counter(path, delta, create_parents=False, **kwargs): """ Increment or decrement a counter in a document. :param path: Path to the counter :param delta: Amount by which to modify the value. The delta can be negative but not 0. It must be an integer (not a float) as well. :param ...
Increment or decrement a counter in a document. :param path: Path to the counter :param delta: Amount by which to modify the value. The delta can be negative but not 0. It must be an integer (not a float) as well. :param create_parents: Create the counter (and apply the modification) if it ...
def _init_from_csc(self, csc): """ Initialize data from a CSC matrix. """ if len(csc.indices) != len(csc.data): raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data))) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCrea...
Initialize data from a CSC matrix.
def _result(self, timeout=None): """ Return the result, if available. It may take an unknown amount of time to return the result, so a timeout option is provided. If the given number of seconds pass with no result, a TimeoutError will be thrown. If a previous call timed...
Return the result, if available. It may take an unknown amount of time to return the result, so a timeout option is provided. If the given number of seconds pass with no result, a TimeoutError will be thrown. If a previous call timed out, additional calls to this function will ...
def JMS_to_FormFlavor_lep(C, dd): """From JMS to semileptonic Fierz basis for Classes V. C should be the JMS basis and `ddll` should be of the form 'sbl_eni_tau', 'dbl_munu_e' etc.""" b = dflav[dd[0]] s = dflav[dd[1]] return { 'CVLL_' + dd + 'mm' : C["VedLL"][1, 1, s, b], 'CVRR_'...
From JMS to semileptonic Fierz basis for Classes V. C should be the JMS basis and `ddll` should be of the form 'sbl_eni_tau', 'dbl_munu_e' etc.
def _PrintSessionsDetails(self, storage_reader): """Prints the details of the sessions. Args: storage_reader (BaseStore): storage. """ for session_number, session in enumerate(storage_reader.GetSessions()): session_identifier = uuid.UUID(hex=session.identifier) session_identifier = '{...
Prints the details of the sessions. Args: storage_reader (BaseStore): storage.
def ffmpeg_works(): """Tries to encode images with ffmpeg to check if it works.""" images = np.zeros((2, 32, 32, 3), dtype=np.uint8) try: _encode_gif(images, 2) return True except (IOError, OSError): return False
Tries to encode images with ffmpeg to check if it works.
def show_zoning_enabled_configuration_output_enabled_configuration_enabled_zone_zone_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_zoning_enabled_configuration = ET.Element("show_zoning_enabled_configuration") config = show_zoning_enabled_con...
Auto Generated Code
def author_edit_view(self, context): """ View for adding/editing nested blocks """ fragment = Fragment() if 'wrap_children' in context: fragment.add_content(context['wrap_children']['head']) self.render_children(context, fragment, can_reorder=True, can_add=F...
View for adding/editing nested blocks
async def reconnect(self): """ Force a reconnection. """ monitor = self.monitor if monitor.reconnecting.locked() or monitor.close_called.is_set(): return async with monitor.reconnecting: await self.close() await self._connect_with_login([(self....
Force a reconnection.
def update_bgp_peer(self, bgp_peer_id, body=None): """Update a BGP peer.""" return self.put(self.bgp_peer_path % bgp_peer_id, body=body)
Update a BGP peer.
def cose(self,compoundGravityRange=None,compoundGravityStrength=None,\ EdgeAttribute=None,gravityRange=None,gravityStrength=None,idealEdgeLength=None,\ incremental=None,LayoutQuality=None,network=None,NodeAttribute=None,\ nodeList=None,repulsionStrength=None,smartEdgeLengthCalc=None,\ smartRepulsionRangeCalc=No...
Execute the Compound Spring Embedder (CoSE) on a network :param compoundGravityRange (string, optional): Compound gravity range (0-1 00) :param compoundGravityStrength (string, optional): Compound gravity strengt h (0-100) :param EdgeAttribute (string, optional): The name of the edge column contai ning ...
def combine_with(self, additional_constraints): """Combines two sets of constraints into a coherent single set.""" x = additional_constraints if not isinstance(additional_constraints, AffineWarpConstraints): x = AffineWarpConstraints(additional_constraints) new_constraints = [] for left, right...
Combines two sets of constraints into a coherent single set.
def load_html_metadata(filename): """ Get metadata from html file """ parser = MetaParser() data = open(filename, 'r').read() if 'pycbc-meta' in data: print("LOADING HTML FILE %s" % filename) parser.feed(data) cp = ConfigParser.ConfigParser(parser.metadata) cp.add_section(os.path.ba...
Get metadata from html file
def _getApplication(self): """Get the base application UIElement. If the UIElement is a child of the application, it will try to get the AXParent until it reaches the top application level element. """ app = self while True: try: app =...
Get the base application UIElement. If the UIElement is a child of the application, it will try to get the AXParent until it reaches the top application level element.
def draw(self, **kwargs): """ Called from the fit method, this method creates the canvas and draws the part-of-speech tag mapping as a bar chart. Parameters ---------- kwargs: dict generic keyword arguments. Returns ------- ax : matpl...
Called from the fit method, this method creates the canvas and draws the part-of-speech tag mapping as a bar chart. Parameters ---------- kwargs: dict generic keyword arguments. Returns ------- ax : matplotlib axes Axes on which the PosTa...
def available_products(cls, user, category=None, products=None): ''' Returns a list of all of the products that are available per flag conditions from the given categories. ''' if category is None and products is None: raise ValueError("You must provide products or a category") ...
Returns a list of all of the products that are available per flag conditions from the given categories.
def _run_python(work_bam_a, work_bam_b, out_dir, aligner, prefix, items): """Run python version of disambiguation """ Args = collections.namedtuple("Args", "A B output_dir intermediate_dir " "no_sort prefix aligner") args = Args(work_bam_a, work_bam_b, out_dir, out_di...
Run python version of disambiguation
def points(self): """Metric points Special property which point to a :class:`~pylls.cachet.MetricPoints` instance for convenience. This instance is initialized on first call. """ if not self._points: self._points = MetricPoints(self.api_client) return self._p...
Metric points Special property which point to a :class:`~pylls.cachet.MetricPoints` instance for convenience. This instance is initialized on first call.
def get_noise_level(cell): """ Gets the noise level of a network / cell. @param string cell A network / cell from iwlist scan. @return string The noise level of the network. """ noise = matching_line(cell, "Noise level=") if noise is None: return "" noise = noise.sp...
Gets the noise level of a network / cell. @param string cell A network / cell from iwlist scan. @return string The noise level of the network.
def __get_agent_host_port(self): """ Iterates the the various ways the host and port of the Instana host agent may be configured: default, env vars, sensor options... """ host = AGENT_DEFAULT_HOST port = AGENT_DEFAULT_PORT if "INSTANA_AGENT_HOST" in os.environ: ...
Iterates the the various ways the host and port of the Instana host agent may be configured: default, env vars, sensor options...
def depth_september_average_ground_temperature(self, value=None): """Corresponds to IDD Field `depth_september_average_ground_temperature` Args: value (float): value for IDD Field `depth_september_average_ground_temperature` Unit: C if `value` is None...
Corresponds to IDD Field `depth_september_average_ground_temperature` Args: value (float): value for IDD Field `depth_september_average_ground_temperature` Unit: C if `value` is None it will not be checked against the specification and is assu...
def _isinstance(obj, cls, bound_Generic=None, bound_typevars=None, bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None): """Access this via ``pytypes.is_of_type``. Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module. obj : Any The object...
Access this via ``pytypes.is_of_type``. Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module. obj : Any The object to check for being an instance of ``cls``. cls : type The type to check for ``obj`` being an instance of. bound_Generic : Optional[Generic] A ty...
def get_default_compartment(model): """Return what the default compartment should be set to. If some compounds have no compartment, unique compartment name is returned to avoid collisions. """ default_compartment = 'c' default_key = set() for reaction in model.reactions: equation = ...
Return what the default compartment should be set to. If some compounds have no compartment, unique compartment name is returned to avoid collisions.
def get_instance(self, payload): """ Build an instance of HighriskSpecialPrefixInstance :param dict payload: Payload response from the API :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance :rtype: twilio.rest.voice....
Build an instance of HighriskSpecialPrefixInstance :param dict payload: Payload response from the API :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefi...
def get_on_tmdb(uri, **kwargs): """ Get a resource on TMDB. """ kwargs['api_key'] = app.config['TMDB_API_KEY'] response = requests_session.get((TMDB_API_URL + uri).encode('utf8'), params=kwargs) response.raise_for_status() return json.loads(response.text)
Get a resource on TMDB.
def on_marker(self, marker): """ Convert our options into the actual marker object""" mid, pos = marker self.marker = Marker(__id__=mid) mapview = self.parent() # Save ref mapview.markers[mid] = self # Required so the packer can pass the id self.marker.se...
Convert our options into the actual marker object
def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j...
def create_signaling(args): """ Create a signaling method based on command-line arguments. """ if args.signaling == 'tcp-socket': return TcpSocketSignaling(args.signaling_host, args.signaling_port) elif args.signaling == 'unix-socket': return UnixSocketSignaling(args.signaling_path) ...
Create a signaling method based on command-line arguments.
def create_user(uid=None, username=None, password=None, priv=None): ''' Create a CIMC user with username and password. Args: uid(int): The user ID slot to create the user account in. username(str): The name of the user. password(str): The clear text password of the user. ...
Create a CIMC user with username and password. Args: uid(int): The user ID slot to create the user account in. username(str): The name of the user. password(str): The clear text password of the user. priv(str): The privilege level of the user. CLI Example: .. code-block...
def translate(self, message, locale): """ Translate Translates a message to the given locale language. Will return original message if no translation exists for the message. :param message: str, a message to translate :param locale: str, locale or langua...
Translate Translates a message to the given locale language. Will return original message if no translation exists for the message. :param message: str, a message to translate :param locale: str, locale or language code :return: str, translated (i...
def auth_ping(self): """Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for user authentication to work, an application must be able to authenticate. Returns: bool: Tru...
Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for user authentication to work, an application must be able to authenticate. Returns: bool: True if the application authenticat...