code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def check_file_for_tabs(filename, verbose=True): """identifies if the file contains tabs and returns True if it does. It also prints the location of the lines and columns. If verbose is set to False, the location is not printed. :param verbose: if true prints information about issues :param filenam...
identifies if the file contains tabs and returns True if it does. It also prints the location of the lines and columns. If verbose is set to False, the location is not printed. :param verbose: if true prints information about issues :param filename: the filename :rtype: True if there are tabs in th...
def new_filename(data, file_kind, ext): """Returns an available filename. :param file_kind: Name under which numbering is recorded, such as 'img' or 'table'. :type file_kind: str :param ext: Filename extension. :type ext: str :returns: (filename, rel_filepath) where file...
Returns an available filename. :param file_kind: Name under which numbering is recorded, such as 'img' or 'table'. :type file_kind: str :param ext: Filename extension. :type ext: str :returns: (filename, rel_filepath) where filename is a path in the filesystem ...
def indent(text: str, num: int = 2) -> str: """Indent a piece of text.""" lines = text.splitlines() return "\n".join(indent_iterable(lines, num=num))
Indent a piece of text.
def ligolw_add(xmldoc, urls, non_lsc_tables_ok = False, verbose = False, contenthandler = DefaultContentHandler): """ An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added. """ # Input for n, url in enumerate(...
An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added.
def load_extra_emacs_page_navigation_bindings(): """ Key bindings, for scrolling up and down through pages. This are separate bindings, because GNU readline doesn't have them. """ registry = ConditionalRegistry(Registry(), EmacsMode()) handle = registry.add_binding handle(Keys.ControlV)(scr...
Key bindings, for scrolling up and down through pages. This are separate bindings, because GNU readline doesn't have them.
def terminate_bits(self, payload): """This method adds zeros to the end of the encoded data so that the encoded data is of the correct length. It returns a binary string containing the bits to be added. """ data_capacity = tables.data_capacity[self.version][self.error][0] ...
This method adds zeros to the end of the encoded data so that the encoded data is of the correct length. It returns a binary string containing the bits to be added.
def status(self): """ Collects the instances state and returns a list. .. important:: Molecule assumes all instances were created successfully by Ansible, otherwise Ansible would return an error on create. This may prove to be a bad assumption. However, co...
Collects the instances state and returns a list. .. important:: Molecule assumes all instances were created successfully by Ansible, otherwise Ansible would return an error on create. This may prove to be a bad assumption. However, configuring Molecule's drive...
def walk_egg(egg_dir): """Walk an unpacked egg's contents, skipping the metadata directory""" walker = sorted_walk(egg_dir) base, dirs, files = next(walker) if 'EGG-INFO' in dirs: dirs.remove('EGG-INFO') yield base, dirs, files for bdf in walker: yield bdf
Walk an unpacked egg's contents, skipping the metadata directory
def _downloaded_filename(self): """Download the package's archive if necessary, and return its filename. --no-deps is implied, as we have reimplemented the bits that would ordinarily do dependency resolution. """ # Peep doesn't support requirements that don't come down ...
Download the package's archive if necessary, and return its filename. --no-deps is implied, as we have reimplemented the bits that would ordinarily do dependency resolution.
def operator(func=None, *, pipable=False): """Create a stream operator from an asynchronous generator (or any function returning an asynchronous iterable). Decorator usage:: @operator async def random(offset=0., width=1.): while True: yield offset + width * rand...
Create a stream operator from an asynchronous generator (or any function returning an asynchronous iterable). Decorator usage:: @operator async def random(offset=0., width=1.): while True: yield offset + width * random.random() Decorator usage for pipable opera...
def list_runids(s3_client, full_path): """Return list of all run ids inside S3 folder. It does not respect S3 pagination (`MaxKeys`) and returns **all** keys from bucket and won't list any prefixes with object archived to AWS Glacier Arguments: s3_client - boto3 S3 client (not service) full_pat...
Return list of all run ids inside S3 folder. It does not respect S3 pagination (`MaxKeys`) and returns **all** keys from bucket and won't list any prefixes with object archived to AWS Glacier Arguments: s3_client - boto3 S3 client (not service) full_path - full valid S3 path to events (such as enri...
def configure_settings(settings, environment_settings=True): ''' Given a settings object, run automatic configuration of all the apps in INSTALLED_APPS. ''' changes = 1 iterations = 0 while changes: changes = 0 app_names = ['django_autoconfig'] + list(settings['INSTALLED_APP...
Given a settings object, run automatic configuration of all the apps in INSTALLED_APPS.
def _do_refresh_session(self): """:returns: `!True` if it had to create new session""" if self._session and self._last_session_refresh + self._loop_wait > time.time(): return False if self._session: try: self._client.session.renew(self._session) ...
:returns: `!True` if it had to create new session
def precedence(item): """Returns the precedence of a given object.""" try: mro = item.__class__.__mro__ except AttributeError: return PRECEDENCE["Atom"] for i in mro: n = i.__name__ if n in PRECEDENCE_FUNCTIONS: return PRECEDENCE_FUNCTIONS[n](item) eli...
Returns the precedence of a given object.
def flatten(nested_iterable): """ Flattens arbitrarily nested lists/tuples. Code partially taken from https://stackoverflow.com/a/10824420. Parameters ---------- nested_iterable A list or tuple of arbitrarily nested values. Yields ------ any Non-list and non-tuple ...
Flattens arbitrarily nested lists/tuples. Code partially taken from https://stackoverflow.com/a/10824420. Parameters ---------- nested_iterable A list or tuple of arbitrarily nested values. Yields ------ any Non-list and non-tuple values in `nested_iterable`.
def remove_override(self, key): """Remove a setting override, if one exists.""" keys = key.split('.') if len(keys) > 1: raise NotImplementedError elif key in self.overrides: del self.overrides[key] self._uncache(key)
Remove a setting override, if one exists.
def spielman_wr(self, norm=True): """Returns a list of site-specific omega values calculated from the `ExpCM`. Args: `norm` (bool) If `True`, normalize the `omega_r` values by the ExpCM gene-wide `omega`. Returns: ...
Returns a list of site-specific omega values calculated from the `ExpCM`. Args: `norm` (bool) If `True`, normalize the `omega_r` values by the ExpCM gene-wide `omega`. Returns: `wr` (list) list of `omeg...
def _match_line(self, city_name, lines): """ The lookup is case insensitive and returns the first matching line, stripped. :param city_name: str :param lines: list of str :return: str """ for line in lines: toponym = line.split(',')[0] ...
The lookup is case insensitive and returns the first matching line, stripped. :param city_name: str :param lines: list of str :return: str
def get_default_config(self): """ Return the default config for the handler """ config = super(rmqHandler, self).get_default_config() config.update({ 'server': '127.0.0.1', 'rmq_exchange': 'diamond', }) return config
Return the default config for the handler
def setImage(self, img, autoRange=True, useAutoLevels=None, levels=None, axes=None, pos=None, scale=None, transform=None, ): """ Set the image to be di...
Set the image to be displayed in the widget. ================== =========================================================================== **Arguments:** img (numpy array) the image to be displayed. See :func:`ImageItem.setImage` and *notes* below. ...
def regularizer(name, regularization_fn, name_filter='weights'): """Wraps a regularizer in a parameter-function. Args: name: The name scope for this regularizer. regularization_fn: A function with signature: fn(variable) -> loss `Tensor` or `None`. name_filter: A regex that will be used to filter...
Wraps a regularizer in a parameter-function. Args: name: The name scope for this regularizer. regularization_fn: A function with signature: fn(variable) -> loss `Tensor` or `None`. name_filter: A regex that will be used to filter variables by name. Returns: A parameter modification function ...
def concat_batch_variantcalls(items, region_block=True, skip_jointcheck=False): """CWL entry point: combine variant calls from regions into single VCF. """ items = [utils.to_single_data(x) for x in items] batch_name = _get_batch_name(items, skip_jointcheck) variantcaller = _get_batch_variantcaller(i...
CWL entry point: combine variant calls from regions into single VCF.
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
def process_large_file(self, local_file, parent): """ Upload a single file using multiple processes to upload multiple chunks at the same time. Updates local_file with it's remote_id when done. :param local_file: LocalFile: file we are uploading :param parent: LocalFolder/LocalPr...
Upload a single file using multiple processes to upload multiple chunks at the same time. Updates local_file with it's remote_id when done. :param local_file: LocalFile: file we are uploading :param parent: LocalFolder/LocalProject: parent of the file
def get_variant_type(variant_source): """Try to find out what type of variants that exists in a variant source Args: variant_source (str): Path to variant source source_mode (str): 'vcf' or 'gemini' Returns: variant_type (str): 'sv' or 'snv' """ ...
Try to find out what type of variants that exists in a variant source Args: variant_source (str): Path to variant source source_mode (str): 'vcf' or 'gemini' Returns: variant_type (str): 'sv' or 'snv'
def twoQ_gates(self): """Get list of 2-qubit gates. Ignore snapshot, barriers, and the like.""" two_q_gates = [] for node in self.gate_nodes(): if len(node.qargs) == 2: two_q_gates.append(node) return two_q_gates
Get list of 2-qubit gates. Ignore snapshot, barriers, and the like.
def get_build_controllers(self, name=None): """GetBuildControllers. Gets controller, optionally filtered by name :param str name: :rtype: [BuildController] """ query_parameters = {} if name is not None: query_parameters['name'] = self._serialize.query(...
GetBuildControllers. Gets controller, optionally filtered by name :param str name: :rtype: [BuildController]
def _assert_path_is_rw(self): """ Make sure, that `self.path` exists, is directory a readable/writeable. Raises: IOError: In case that any of the assumptions failed. ValueError: In case that `self.path` is not set. """ if not self.path: raise ...
Make sure, that `self.path` exists, is directory a readable/writeable. Raises: IOError: In case that any of the assumptions failed. ValueError: In case that `self.path` is not set.
def clone(self, name=None): """Creates a new MLP with the same structure. Args: name: Optional string specifying the name of the new module. The default name is constructed by appending "_clone" to the original name. Returns: A cloned `MLP` module. """ if name is None: n...
Creates a new MLP with the same structure. Args: name: Optional string specifying the name of the new module. The default name is constructed by appending "_clone" to the original name. Returns: A cloned `MLP` module.
def _GetShowID(self, showName): """ Get epguides show id for a given show name. Attempts to match the given show name against a show title in self._showTitleList and, if found, returns the corresponding index in self._showIDList. Parameters ---------- showName : string Show n...
Get epguides show id for a given show name. Attempts to match the given show name against a show title in self._showTitleList and, if found, returns the corresponding index in self._showIDList. Parameters ---------- showName : string Show name to get show ID for. Returns ---...
def writePIDFile(self): """ Write a the pid of this process to a file in the jobstore. Overwriting the current contents of pid.log is a feature, not a bug of this method. Other methods will rely on always having the most current pid available. So far there is no reason to store ...
Write a the pid of this process to a file in the jobstore. Overwriting the current contents of pid.log is a feature, not a bug of this method. Other methods will rely on always having the most current pid available. So far there is no reason to store any old pids.
def proximity_metric(self, a, b): """Return the weight of the dependency from a to b. Higher weights usually have shorter straighter edges. Return 1 if it has normal weight. A value of 4 is usually good for ensuring that a related pair of modules are drawn next to each other. ...
Return the weight of the dependency from a to b. Higher weights usually have shorter straighter edges. Return 1 if it has normal weight. A value of 4 is usually good for ensuring that a related pair of modules are drawn next to each other. Returns an int between 1 (unknown, ...
def taskfileinfo_descriptor_data(tfi, role): """Return the data for descriptor :param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the desc...
Return the data for descriptor :param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the descriptor :rtype: depending on role :raises: No...
def import_apps_submodule(submodule): """ Look for a submodule is a series of packages, e.g. ".pagetype_plugins" in all INSTALLED_APPS. """ found_apps = [] for appconfig in apps.get_app_configs(): app = appconfig.name if import_module_or_none('{0}.{1}'.format(app, submodule)) is not ...
Look for a submodule is a series of packages, e.g. ".pagetype_plugins" in all INSTALLED_APPS.
def promote(self, content): """ Promote (replace) the content.data with the first attribute of the current content.data that is a I{list}. Note: the content.data may be empty or contain only _x attributes. In either case, the content.data is assigned an empty list. @para...
Promote (replace) the content.data with the first attribute of the current content.data that is a I{list}. Note: the content.data may be empty or contain only _x attributes. In either case, the content.data is assigned an empty list. @param content: An array content. @type conte...
def _set_pos(self, pos): """ Set current position for scroll bar. """ if self._canvas.height < self._max_height: pos *= self._max_height - self._canvas.height + 1 pos = int(round(max(0, pos), 0)) self._canvas.scroll_to(pos)
Set current position for scroll bar.
def match(tgt, opts=None): ''' Runs the compound target check ''' if not opts: opts = __opts__ nodegroups = opts.get('nodegroups', {}) matchers = salt.loader.matchers(opts) if not isinstance(tgt, six.string_types) and not isinstance(tgt, (list, tuple)): log.error('Compound t...
Runs the compound target check
def autofit(ts, maxp=5, maxd=2, maxq=5, sc=None): """ Utility function to help in fitting an automatically selected ARIMA model based on approximate Akaike Information Criterion (AIC) values. The model search is based on the heuristic developed by Hyndman and Khandakar (2008) and described in [[http://w...
Utility function to help in fitting an automatically selected ARIMA model based on approximate Akaike Information Criterion (AIC) values. The model search is based on the heuristic developed by Hyndman and Khandakar (2008) and described in [[http://www.jstatsoft .org/v27/i03/paper]]. In contrast to the algo...
def _record_field_to_json(fields, row_value): """Convert a record/struct field to its JSON representation. Args: fields ( \ Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`], \ ): The :class:`~google.cloud.bigquery.schema.SchemaField`s of the recor...
Convert a record/struct field to its JSON representation. Args: fields ( \ Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`], \ ): The :class:`~google.cloud.bigquery.schema.SchemaField`s of the record's subfields to use for type conversion and field na...
async def handle_user_exception(self, error: Exception) -> Response: """Handle an exception that has been raised. This should forward :class:`~quart.exception.HTTPException` to :meth:`handle_http_exception`, then attempt to handle the error. If it cannot it should reraise the error. ...
Handle an exception that has been raised. This should forward :class:`~quart.exception.HTTPException` to :meth:`handle_http_exception`, then attempt to handle the error. If it cannot it should reraise the error.
def excepthook (self, etype, evalue, etb): """Handle an uncaught exception. We always forward the exception on to whatever `sys.excepthook` was present upon setup. However, if the exception is a KeyboardInterrupt, we additionally kill ourselves with an uncaught SIGINT, so that invoking p...
Handle an uncaught exception. We always forward the exception on to whatever `sys.excepthook` was present upon setup. However, if the exception is a KeyboardInterrupt, we additionally kill ourselves with an uncaught SIGINT, so that invoking programs know what happened.
def _maybe_parse_configurable_reference(self): """Try to parse a configurable reference (@[scope/name/]fn_name[()]).""" if self._current_token.value != '@': return False, None location = self._current_location() self._advance_one_token() scoped_name = self._parse_selector(allow_periods_in_sco...
Try to parse a configurable reference (@[scope/name/]fn_name[()]).
def size(dtype): """Returns the number of bytes to represent this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'size'): return dtype.size return np.dtype(dtype).itemsize
Returns the number of bytes to represent this `dtype`.
def process_nxml_str(nxml_str, citation=None, offline=False, output_fname=default_output_fname): """Return a ReachProcessor by processing the given NXML string. NXML is the format used by PubmedCentral for papers in the open access subset. Parameters ---------- nxml_str : ...
Return a ReachProcessor by processing the given NXML string. NXML is the format used by PubmedCentral for papers in the open access subset. Parameters ---------- nxml_str : str The NXML string to be processed. citation : Optional[str] A PubMed ID passed to be used in the eviden...
def loudest_triggers_from_cli(opts, coinc_parameters=None, sngl_parameters=None, bank_parameters=None): """ Parses the CLI options related to find the loudest coincident or single detector triggers. Parameters ---------- opts : object Result of parsing the CLI ...
Parses the CLI options related to find the loudest coincident or single detector triggers. Parameters ---------- opts : object Result of parsing the CLI with OptionParser. coinc_parameters : list List of datasets in statmap file to retrieve. sngl_parameters : list List o...
def do_alarm_definition_patch(mc, args): '''Patch the alarm definition.''' fields = {} fields['alarm_id'] = args.id if args.name: fields['name'] = args.name if args.description: fields['description'] = args.description if args.expression: fields['expression'] = args.expre...
Patch the alarm definition.
def _connect(self): "Create a Unix domain socket connection" sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.socket_timeout) sock.connect(self.path) return sock
Create a Unix domain socket connection
def der_cert(der_data): """ Load a DER encoded certificate :param der_data: DER-encoded certificate :return: A cryptography.x509.certificate instance """ if isinstance(der_data, str): der_data = bytes(der_data, 'utf-8') return x509.load_der_x509_certificate(der_data, default_backend...
Load a DER encoded certificate :param der_data: DER-encoded certificate :return: A cryptography.x509.certificate instance
def shutil_rmtree_onerror(func: Callable[[str], None], path: str, exc_info: EXC_INFO_TYPE) -> None: """ Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. ...
Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. If the error is for another reason it re-raises the error. Usage: ``shutil.rmtree(path, onerror=shutil_rmtree_onerror)`` See https://stackove...
def output(self,pin,value): """Set the specified pin the provided high/low value. Value should be either 1 (ON or HIGH), or 0 (OFF or LOW) or a boolean. """ self.mraa_gpio.Gpio.write(self.mraa_gpio.Gpio(pin), value)
Set the specified pin the provided high/low value. Value should be either 1 (ON or HIGH), or 0 (OFF or LOW) or a boolean.
def console_get_default_background(con: tcod.console.Console) -> Color: """Return this consoles default background color. .. deprecated:: 8.5 Use :any:`Console.default_bg` instead. """ return Color._new_from_cdata( lib.TCOD_console_get_default_background(_console(con)) )
Return this consoles default background color. .. deprecated:: 8.5 Use :any:`Console.default_bg` instead.
def check_for_rerun_user_task(self): """ Checks that the user task needs to re-run. If necessary, current task and pre task's states are changed and re-run. If wf_meta not in data(there is no user interaction from pre-task) and last completed task type is user task and current st...
Checks that the user task needs to re-run. If necessary, current task and pre task's states are changed and re-run. If wf_meta not in data(there is no user interaction from pre-task) and last completed task type is user task and current step is not EndEvent and there is no lane change, t...
def mag_cal_progress_encode(self, compass_id, cal_mask, cal_status, attempt, completion_pct, completion_mask, direction_x, direction_y, direction_z): ''' Reports progress of compass calibration. compass_id : Compass being calibrated (uint8_t) ...
Reports progress of compass calibration. compass_id : Compass being calibrated (uint8_t) cal_mask : Bitmask of compasses being calibrated (uint8_t) cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t) atte...
def middleware_in_executor(middleware): '''Use this middleware to run a synchronous middleware in the event loop executor. Useful when using synchronous web-frameworks such as :django:`django <>`. ''' @wraps(middleware) def _(environ, start_response): loop = get_event_loop() ret...
Use this middleware to run a synchronous middleware in the event loop executor. Useful when using synchronous web-frameworks such as :django:`django <>`.
def and_terms(*args): """ Connect given term strings or list(s) of term strings with an AND operator for querying. Args: An arbitrary number of either strings or lists of strings representing query terms. Returns A query string consisting of argument terms and'ed together. ...
Connect given term strings or list(s) of term strings with an AND operator for querying. Args: An arbitrary number of either strings or lists of strings representing query terms. Returns A query string consisting of argument terms and'ed together.
def filter_by_pattern(self, pattern): """Filter the Data Collection based on a list of booleans. Args: pattern: A list of True/False values. Typically, this is a list with a length matching the length of the Data Collections values but it can also be a patte...
Filter the Data Collection based on a list of booleans. Args: pattern: A list of True/False values. Typically, this is a list with a length matching the length of the Data Collections values but it can also be a pattern to be repeated over the Data Collection. ...
def openXmlDocument(path=None, file_=None, data=None, url=None, mime_type=None): """**Factory function** Will guess what document type is best suited and return the appropriate document type. User must provide either ``path``, ``file_``, ``data`` or ``url`` parameter. :param path: file path in the...
**Factory function** Will guess what document type is best suited and return the appropriate document type. User must provide either ``path``, ``file_``, ``data`` or ``url`` parameter. :param path: file path in the local filesystem to a document. :param file_: a file (like) object to a document (m...
def _compute_base_term(self, C, rup, dists): """ Compute and return base model term, that is the first term in equation 1, page 74. The calculation of this term is explained in paragraph 'Base Model', page 75. """ c1 = self.CONSTS['c1'] R = np.sqrt(dists.rrup ** 2...
Compute and return base model term, that is the first term in equation 1, page 74. The calculation of this term is explained in paragraph 'Base Model', page 75.
def p_generate_if_woelse(self, p): 'generate_if : IF LPAREN cond RPAREN gif_true_item' p[0] = IfStatement(p[3], p[5], None, lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
generate_if : IF LPAREN cond RPAREN gif_true_item
def add_x509_key_descriptors(metadata, cert=None, add_encryption=True): """ Adds the x509 descriptors (sign/encryption) to the metadata The same cert will be used for sign/encrypt :param metadata: SAML Metadata XML :type metadata: string :param cert: x509 cert :...
Adds the x509 descriptors (sign/encryption) to the metadata The same cert will be used for sign/encrypt :param metadata: SAML Metadata XML :type metadata: string :param cert: x509 cert :type cert: string :param add_encryption: Determines if the KeyDescriptor[use="encry...
def __getitem_slice(self, slce): """Return a range which represents the requested slce of the sequence represented by this range. """ scaled_indices = (self._step * n for n in slce.indices(self._len)) start_offset, stop_offset, new_step = scaled_indices return newrange(se...
Return a range which represents the requested slce of the sequence represented by this range.
def validate_config(cls, config): """ Validates a config dictionary parsed from a cluster config file. Checks that a discovery method is defined and that at least one of the balancers in the config are installed and available. """ if "discovery" not in config: ...
Validates a config dictionary parsed from a cluster config file. Checks that a discovery method is defined and that at least one of the balancers in the config are installed and available.
def start(token, control=False, trigger='!', groups=None, groups_pillar_name=None, fire_all=False, tag='salt/engines/slack'): ''' Listen to slack events and forward them to salt, new version ''' if (not token) or (not token.startswith('xoxb'))...
Listen to slack events and forward them to salt, new version
def comparable(self): """str: comparable representation of the path specification.""" string_parts = [] if self.location is not None: string_parts.append('location: {0:s}'.format(self.location)) if self.store_index is not None: string_parts.append('store index: {0:d}'.format(self.store_inde...
str: comparable representation of the path specification.
def set_value(self, dry_wet: LeakSensorState): """Set the state to wet or dry.""" if dry_wet == LeakSensorState.DRY: self._update_subscribers(0x11) else: self._update_subscribers(0x13)
Set the state to wet or dry.
def replace_namespaced_deployment_scale(self, name, namespace, body, **kwargs): """ replace scale of the specified Deployment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespa...
replace scale of the specified Deployment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_deployment_scale(name, namespace, body, async_req=True) >>> result = thread.get() ...
def set_encode_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64): """Set the value based on the type of encoding supported by RSA.""" if store_type == PUBLIC_KEY_STORE_TYPE_PEM: PublicKeyBase.set_encode_key_value(self, value.exportKey('PEM').decode(), store_type) else: ...
Set the value based on the type of encoding supported by RSA.
def _segment_index(self, recarr, existing_index, start, new_segments): """ Generate index of datetime64 -> item offset. Parameters: ----------- new_data: new data being written (or appended) existing_index: index field from the versions document of the previous version ...
Generate index of datetime64 -> item offset. Parameters: ----------- new_data: new data being written (or appended) existing_index: index field from the versions document of the previous version start: first (0-based) offset of the new data segments: list of offsets. Eac...
def parse_py(s, **kwargs): """Parse a string into a (nbformat, string) tuple.""" nbf = current_nbformat nbm = current_nbformat_minor pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>' m = re.search(pattern,s) if m is not None: digits = m.group('nbformat').split('.') ...
Parse a string into a (nbformat, string) tuple.
def next_page(self, max_=None): """ Return a query set which requests the page after this response. :param max_: Maximum number of items to return. :type max_: :class:`int` or :data:`None` :rtype: :class:`ResultSetMetadata` :return: A new request set up to request the ne...
Return a query set which requests the page after this response. :param max_: Maximum number of items to return. :type max_: :class:`int` or :data:`None` :rtype: :class:`ResultSetMetadata` :return: A new request set up to request the next page. Must be called on a result set whi...
def create(self, friendly_name=values.unset, sync_service_sid=values.unset): """ Create a new DeploymentInstance :param unicode friendly_name: A human readable description for this Deployment. :param unicode sync_service_sid: The unique identifier of the Sync service instance. ...
Create a new DeploymentInstance :param unicode friendly_name: A human readable description for this Deployment. :param unicode sync_service_sid: The unique identifier of the Sync service instance. :returns: Newly created DeploymentInstance :rtype: twilio.rest.preview.deployed_devices.f...
def migrate_database(adapter): """Migrate an old loqusdb instance to 1.0 Args: adapter Returns: nr_updated(int): Number of variants that where updated """ all_variants = adapter.get_variants() nr_variants = all_variants.count() nr_updated = 0 with progressb...
Migrate an old loqusdb instance to 1.0 Args: adapter Returns: nr_updated(int): Number of variants that where updated
async def subscribe(self, *args, **kwargs): """ Subscribe to channels. Channels supplied as keyword arguments expect a channel name as the key and a callable as the value. A channel's callable will be invoked automatically when a message is received on that channel rather than pr...
Subscribe to channels. Channels supplied as keyword arguments expect a channel name as the key and a callable as the value. A channel's callable will be invoked automatically when a message is received on that channel rather than producing a message via ``listen()`` or ``get_message()``.
def calculateHurst(self, series, exponent=None): ''' :type series: List :type exponent: int :rtype: float ''' rescaledRange = list() sizeRange = list() rescaledRangeMean = list() if(exponent is None): exponent = self.bestExponent(len(s...
:type series: List :type exponent: int :rtype: float
def no_ssl_verification(self): """ Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release.""" try: from functools import partialmethod except ImportError: # Python 2 fallback: https://gist.github.com/carymrobbins/8940382 ...
Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release.
def train(self, ftrain): '''Trains the polynomial expansion. :param numpy.ndarray/function ftrain: output values corresponding to the quadrature points given by the getQuadraturePoints method to which the expansion should be trained. Or a function that should be evaluated ...
Trains the polynomial expansion. :param numpy.ndarray/function ftrain: output values corresponding to the quadrature points given by the getQuadraturePoints method to which the expansion should be trained. Or a function that should be evaluated at the quadrature points to gi...
def warning(self, message, *args, **kwargs): """Log warning event. Compatible with logging.warning signature. """ self.system.warning(message, *args, **kwargs)
Log warning event. Compatible with logging.warning signature.
def searchTriples(expnums,ccd): """Given a list of exposure numbers, find all the KBOs in that set of exposures""" import MOPfits,os import MOPdbaccess if len(expnums)!=3: return(-1) mysql=MOPdbaccess.connect('bucket','cfhls','MYSQL') bucket=mysql.cursor() ### Some pro...
Given a list of exposure numbers, find all the KBOs in that set of exposures
def sort_index(self, **kwargs): """Sorts the data with respect to either the columns or the indices. Returns: DataManager containing the data sorted by columns or indices. """ axis = kwargs.pop("axis", 0) index = self.columns if axis else self.index # sort_i...
Sorts the data with respect to either the columns or the indices. Returns: DataManager containing the data sorted by columns or indices.
def __record(self, oid=None): """Reads and returns a dbf record row as a list of values.""" f = self.__getFileObj(self.dbf) recordContents = self.__recStruct.unpack(f.read(self.__recStruct.size)) if recordContents[0] != b' ': # deleted record return None ...
Reads and returns a dbf record row as a list of values.
def get_song(self, netease=False): """ 获取歌曲, 对外统一接口 """ song = self._playlist.get(True) self.hash_sid[song['sid']] = True # 去重 self.get_netease_song(song, netease) # 判断是否网易320k self._playingsong = song return song
获取歌曲, 对外统一接口
def serve_forever(self): """Wrapper to the serve_forever function.""" loop = True while loop: loop = self.__serve_forever() self.end()
Wrapper to the serve_forever function.
def find(cls, *args, **kwargs): """Same as ``collection.find``, returns model object instead of dict.""" return cls.from_cursor(cls.collection.find(*args, **kwargs))
Same as ``collection.find``, returns model object instead of dict.
def create(self, fields): """ Create the object only once. So, you need loop to usage. :param `fields` is dictionary fields. """ try: # Cleaning the fields, and check if has `ForeignKey` type. cleaned_fields = {} for key, value in fiel...
Create the object only once. So, you need loop to usage. :param `fields` is dictionary fields.
def transfer(self, receiver_address, amount, sender_account): """ Transfer a number of tokens from `sender_account` to `receiver_address` :param receiver_address: hex str ethereum address to receive this transfer of tokens :param amount: int number of tokens to transfer :param s...
Transfer a number of tokens from `sender_account` to `receiver_address` :param receiver_address: hex str ethereum address to receive this transfer of tokens :param amount: int number of tokens to transfer :param sender_account: Account instance to take the tokens from :return: bool
def createMemoryParserCtxt(buffer, size): """Create a parser context for an XML in-memory document. """ ret = libxml2mod.xmlCreateMemoryParserCtxt(buffer, size) if ret is None:raise parserError('xmlCreateMemoryParserCtxt() failed') return parserCtxt(_obj=ret)
Create a parser context for an XML in-memory document.
def luks_cleartext_holder(self): """Get wrapper to the unlocked luks cleartext device.""" if not self.is_luks: return None for device in self._daemon: if device.luks_cleartext_slave == self: return device return None
Get wrapper to the unlocked luks cleartext device.
def run(self, verbose=False): """ Del user modules to force Python to deeply reload them Do not del modules which are considered as system modules, i.e. modules installed in subdirectories of Python interpreter's binary Do not del C modules """ log = [] m...
Del user modules to force Python to deeply reload them Do not del modules which are considered as system modules, i.e. modules installed in subdirectories of Python interpreter's binary Do not del C modules
def _cleanup(self, kill, verbose): """Look for dead components (weight=0) and remove them if enabled by ``kill``. Resize storage. Recompute determinant and covariance. """ if kill: removed_indices = self.g.prune() self.nout -= len(removed_indices) ...
Look for dead components (weight=0) and remove them if enabled by ``kill``. Resize storage. Recompute determinant and covariance.
def receive_message( sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE): """Receive a raw BSON message or raise socket.error.""" header = _receive_data_on_socket(sock, 16) length = _UNPACK_INT(header[:4])[0] actual_op = _UNPACK_INT(header[12:])[0] if operation != actual_op: ...
Receive a raw BSON message or raise socket.error.
def convert_sqlite_to_mysql( self): """*copy the contents of the sqlite database into the mysql database* See class docstring for usage """ from fundamentals.renderer import list_of_dictionaries from fundamentals.mysql import directory_script_runner self.log....
*copy the contents of the sqlite database into the mysql database* See class docstring for usage
def loglike(self): ''' The summed log-probability of all stochastic variables that depend on self.stochastics, with self.stochastics removed. ''' sum = logp_of_set(self.children) if self.verbose > 2: print_('\t' + self._id + ' Current log-likelihood ', sum) ...
The summed log-probability of all stochastic variables that depend on self.stochastics, with self.stochastics removed.
def _extract_sender( message: Message, resent_dates: List[Union[str, Header]] = None ) -> str: """ Extract the sender from the message object given. """ if resent_dates: sender_header = "Resent-Sender" from_header = "Resent-From" else: sender_header = "Sender" fro...
Extract the sender from the message object given.
def grouped_insert(t, value): """Insert value into the target tree 't' with correct grouping.""" collator = Collator.createInstance(Locale(t.lang) if t.lang else Locale()) if value.tail is not None: val_prev = value.getprevious() if val_prev is not None: val_prev.tail = (val_prev...
Insert value into the target tree 't' with correct grouping.
def start(self): """Start the daemon""" if self._already_running(): message = 'pid file %s already exists. Daemon already running?\n' sys.stderr.write(message % self.pid_file) return 0 self.set_gid() self.set_uid() # Create log files (if config...
Start the daemon
def retrieve(self, id) : """ Retrieve a single task Returns a single task available to the user according to the unique task ID provided If the specified task does not exist, this query will return an error :calls: ``get /tasks/{id}`` :param int id: Unique identifier of...
Retrieve a single task Returns a single task available to the user according to the unique task ID provided If the specified task does not exist, this query will return an error :calls: ``get /tasks/{id}`` :param int id: Unique identifier of a Task. :return: Dictionary that sup...
def generic_html(self, result, errors): """ Try to display any object in sensible HTML. """ h1 = htmlize(type(result)) out = [] result = pre_process_json(result) if not hasattr(result, 'items'): # result is a non-container header = "<tr><t...
Try to display any object in sensible HTML.
def _flush(self): """ Returns a list of all current data """ if self._recording: raise Exception("Cannot flush data queue while recording!") if self._saving_cache: logging.warn("Flush when using cache means unsaved data will be lost and not returned!") self._c...
Returns a list of all current data
async def sort(self, request, reverse=False): """Sort collection.""" return sorted( self.collection, key=lambda o: getattr(o, self.columns_sort, 0), reverse=reverse)
Sort collection.
def execute(self, query_string, params=None): """Executes a query. Returns the resulting cursor. :query_string: the parameterized query string :params: can be either a tuple or a dictionary, and must match the parameterization style of the query :return: a cursor object """ cr = se...
Executes a query. Returns the resulting cursor. :query_string: the parameterized query string :params: can be either a tuple or a dictionary, and must match the parameterization style of the query :return: a cursor object