code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def match_column_labels(self, match_value_or_fct, levels=None, max_matches=0, empty_res=1): """Check the original DataFrame's column labels to find a subset of the current region :param match_value_or_fct: value or function(hdr_value) which returns True for match :param levels: [None, scalar, in...
Check the original DataFrame's column labels to find a subset of the current region :param match_value_or_fct: value or function(hdr_value) which returns True for match :param levels: [None, scalar, indexer] :param max_matches: maximum number of columns to return :return:
def begin(self, *args, **kwargs): """Indicate the beginning of a transaction. During a transaction, connections won't be transparently replaced, and all errors will be raised to the application. If the underlying driver supports this method, it will be called with the given par...
Indicate the beginning of a transaction. During a transaction, connections won't be transparently replaced, and all errors will be raised to the application. If the underlying driver supports this method, it will be called with the given parameters (e.g. for distributed transactions).
def run(self, records): """Runs the batch upload :param records: an iterable containing queue entries """ self_name = type(self).__name__ for i, batch in enumerate(grouper(records, self.BATCH_SIZE, skip_missing=True), 1): self.logger.info('%s processing batch %d', se...
Runs the batch upload :param records: an iterable containing queue entries
def get_logging_file_handler(logger=None, file=None, formatter=LOGGING_DEFAULT_FORMATTER): """ Adds a logging file handler to given logger or default logger using given file. :param logger: Logger to add the handler to. :type logger: Logger :param file: File to verbose into. :type file: unicode...
Adds a logging file handler to given logger or default logger using given file. :param logger: Logger to add the handler to. :type logger: Logger :param file: File to verbose into. :type file: unicode :param formatter: Handler formatter. :type formatter: Formatter :return: Added handler. ...
def absent( name, region=None, key=None, keyid=None, profile=None, ): ''' Ensure the named sqs queue is deleted. name Name of the SQS queue. region Region to connect to. key Secret key to be used. keyid Access key to be ...
Ensure the named sqs queue is deleted. name Name of the SQS queue. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with r...
def _validate_string(self, input_string, path_to_root, object_title=''): ''' a helper method for validating properties of a string :return: input_string ''' rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) input_criteria = self.keyMap[rules_path_to_root]...
a helper method for validating properties of a string :return: input_string
def savePkeyPem(self, pkey, path): ''' Save a private key in PEM format to a file outside the certdir. ''' with s_common.genfile(path) as fd: fd.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
Save a private key in PEM format to a file outside the certdir.
def imshow(image, backend=IMSHOW_BACKEND_DEFAULT): """ Shows an image in a window. dtype support:: * ``uint8``: yes; not tested * ``uint16``: ? * ``uint32``: ? * ``uint64``: ? * ``int8``: ? * ``int16``: ? * ``int32``: ? * ``int64``: ? ...
Shows an image in a window. dtype support:: * ``uint8``: yes; not tested * ``uint16``: ? * ``uint32``: ? * ``uint64``: ? * ``int8``: ? * ``int16``: ? * ``int32``: ? * ``int64``: ? * ``float16``: ? * ``float32``: ? * ``float64`...
def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = c...
Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole
def _get_view_method(self, request): """Get view method.""" if hasattr(self, 'action'): return self.action if self.action else None return request.method.lower()
Get view method.
def get_arr_desc(arr): """Get array description, in the form '<array type> <array shape>'""" type_ = type(arr).__name__ # see also __qualname__ shape = getattr(arr, 'shape', None) if shape is not None: desc = '{type_} {shape}' else: desc = '{type_} <no shape>' return desc.format...
Get array description, in the form '<array type> <array shape>
def coinc(self, s0, s1, slide, step): """ Calculate the coincident detection statistic. Parameters ---------- s0: numpy.ndarray Single detector ranking statistic for the first detector. s1: numpy.ndarray Single detector ranking statistic for the s...
Calculate the coincident detection statistic. Parameters ---------- s0: numpy.ndarray Single detector ranking statistic for the first detector. s1: numpy.ndarray Single detector ranking statistic for the second detector. slide: numpy.ndarray A...
def put(self, obj): """Put request into queue. Args: obj (cheroot.server.HTTPConnection): HTTP connection waiting to be processed """ self._queue.put(obj, block=True, timeout=self._queue_put_timeout) if obj is _SHUTDOWNREQUEST: return
Put request into queue. Args: obj (cheroot.server.HTTPConnection): HTTP connection waiting to be processed
def copy(self, filename=None): """Puts on destination as a temp file, renames on the destination. """ dst = os.path.join(self.dst_path, filename) src = os.path.join(self.src_path, filename) dst_tmp = os.path.join(self.dst_tmp, filename) self.put(src=src, dst=dst_t...
Puts on destination as a temp file, renames on the destination.
def put(self, pid, record): """Handle the sort of the files through the PUT deposit files. Expected input in body PUT: .. code-block:: javascript [ { "id": 1 }, { "id": 2 }, ...
Handle the sort of the files through the PUT deposit files. Expected input in body PUT: .. code-block:: javascript [ { "id": 1 }, { "id": 2 }, ... } ...
def unperturbed_hamiltonian(states): r"""Return the unperturbed atomic hamiltonian for given states. We calcualte the atomic hamiltonian in the basis of the ground states of \ rubidium 87 (in GHz). >>> g = State("Rb", 87, 5, 0, 1/Integer(2)) >>> magnetic_states = make_list_of_states([g], "magnetic"...
r"""Return the unperturbed atomic hamiltonian for given states. We calcualte the atomic hamiltonian in the basis of the ground states of \ rubidium 87 (in GHz). >>> g = State("Rb", 87, 5, 0, 1/Integer(2)) >>> magnetic_states = make_list_of_states([g], "magnetic") >>> print(np.diag(unperturbed_hamil...
def __cost(self, params, phase, X): """Computes activation, cost function, and derivative.""" params = self.__roll(params) a = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1) # This is a1 calculated_a = [a] # a1 is at index 0, a_n is at index n-1 calculated_z = [0] # There ...
Computes activation, cost function, and derivative.
def command_for_func(func): """Create a command that calls the given function.""" class FuncCommand(BaseCommand): def run(self): func() update_package_data(self.distribution) return FuncCommand
Create a command that calls the given function.
def evaluateplanarR2derivs(Pot,R,phi=None,t=0.): """ NAME: evaluateplanarR2derivs PURPOSE: evaluate the second radial derivative of a (list of) planarPotential instance(s) INPUT: Pot - (list of) planarPotential instance(s) R - Cylindrical radius (can be Quantity) ...
NAME: evaluateplanarR2derivs PURPOSE: evaluate the second radial derivative of a (list of) planarPotential instance(s) INPUT: Pot - (list of) planarPotential instance(s) R - Cylindrical radius (can be Quantity) phi= azimuth (optional; can be Quantity) t= time (o...
def view_focused_activity(self) -> str: '''View focused activity.''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'dumpsys', 'activity', 'activities') return re.findall(r'mFocusedActivity: .+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)', output)[0]
View focused activity.
def movie(args): """ %prog movie input.bed scaffolds.fasta chr1 Visualize history of scaffold OO. The history is contained within the tourfile, generated by path(). For each historical scaffold OO, the program plots a separate PDF file. The plots can be combined to show the progression as a lit...
%prog movie input.bed scaffolds.fasta chr1 Visualize history of scaffold OO. The history is contained within the tourfile, generated by path(). For each historical scaffold OO, the program plots a separate PDF file. The plots can be combined to show the progression as a little animation. The third argu...
def order_transforms(transforms): """Orders transforms to ensure proper chaining. For example, if `transforms = [B, A, C]`, and `A` produces outputs needed by `B`, the transforms will be re-rorderd to `[A, B, C]`. Parameters ---------- transforms : list List of transform instances to o...
Orders transforms to ensure proper chaining. For example, if `transforms = [B, A, C]`, and `A` produces outputs needed by `B`, the transforms will be re-rorderd to `[A, B, C]`. Parameters ---------- transforms : list List of transform instances to order. Outputs ------- list :...
def remove_option(self, section, name, value=None): """Remove an option from a unit Args: section (str): The section to remove from. name (str): The item to remove. value (str, optional): If specified, only the option matching this value will be removed ...
Remove an option from a unit Args: section (str): The section to remove from. name (str): The item to remove. value (str, optional): If specified, only the option matching this value will be removed If not specified, all options with ``name...
def stub_request(self, expected_url, filename, status=None, body=None): """Stub a web request for testing.""" self.fake_web = True self.faker = get_faker(expected_url, filename, status, body)
Stub a web request for testing.
def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None): """ Writes a single packet to the pcap file. :param packet: Packet, or bytes for a single packet :type packet: Packet or bytes :param sec: time the packet was captured, in seco...
Writes a single packet to the pcap file. :param packet: Packet, or bytes for a single packet :type packet: Packet or bytes :param sec: time the packet was captured, in seconds since epoch. If not supplied, defaults to now. :type sec: int or long :param usec: ...
def conference_mute(self, call_params): """REST Conference Mute helper """ path = '/' + self.api_version + '/ConferenceMute/' method = 'POST' return self.request(path, method, call_params)
REST Conference Mute helper
def get_window_forecasts(self): """ Aggregate the forecasts within the specified time windows. """ for model_name in self.model_names: self.window_forecasts[model_name] = {} for size_threshold in self.size_thresholds: self.window_forecasts[model_na...
Aggregate the forecasts within the specified time windows.
def create_asset(self, ): """Create a asset and store it in the self.asset :returns: None :rtype: None :raises: None """ name = self.name_le.text() if not name: self.name_le.setPlaceholderText("Please enter a name!") return desc = ...
Create a asset and store it in the self.asset :returns: None :rtype: None :raises: None
def enable_global_typelogged_profiler(flag = True): """Enables or disables global typelogging mode via a profiler. See flag global_typelogged_profiler. Does not work if typelogging_enabled is false. """ global global_typelogged_profiler, _global_type_agent, global_typechecked_profiler global_typ...
Enables or disables global typelogging mode via a profiler. See flag global_typelogged_profiler. Does not work if typelogging_enabled is false.
def subscribeToDeviceCommands(self, typeId="+", deviceId="+", commandId="+", msgFormat="+"): """ Subscribe to device command messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceI...
Subscribe to device command messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceId for the subscription, optional. Defaults to all devices (MQTT `+` wildcard) commandId (string): comman...
def remove(self, child): '''Remove a ``child`` from the list of :attr:`children`.''' try: self.children.remove(child) if isinstance(child, String): child._parent = None except ValueError: pass
Remove a ``child`` from the list of :attr:`children`.
def visit_keyword(self, node): """return an astroid.Keyword node as string""" if node.arg is None: return "**%s" % node.value.accept(self) return "%s=%s" % (node.arg, node.value.accept(self))
return an astroid.Keyword node as string
def setup(service_manager, conf, reload_method="reload"): """Load services configuration from oslo config object. It reads ServiceManager and Service configuration options from an oslo_config.ConfigOpts() object. Also It registers a ServiceManager hook to reload the configuration file on reload in the ...
Load services configuration from oslo config object. It reads ServiceManager and Service configuration options from an oslo_config.ConfigOpts() object. Also It registers a ServiceManager hook to reload the configuration file on reload in the master process and in all children. And then when each child ...
def rts_smoother(cls,state_dim, p_dynamic_callables, filter_means, filter_covars): """ This function implements Rauch–Tung–Striebel(RTS) smoother algorithm based on the results of kalman_filter_raw. These notations are the same: x_{k} = A_{k} * x_{k...
This function implements Rauch–Tung–Striebel(RTS) smoother algorithm based on the results of kalman_filter_raw. These notations are the same: x_{k} = A_{k} * x_{k-1} + q_{k-1}; q_{k-1} ~ N(0, Q_{k-1}) y_{k} = H_{k} * x_{k} + r_{k}; r_{k-1} ~ N(0, R_{k}) ...
def runblast(self, assembly, allele, sample): """ Run the BLAST analyses :param assembly: assembly path/file :param allele: combined allele file :param sample: sample object :return: """ genome = os.path.split(assembly)[1].split('.')[0] # Run the B...
Run the BLAST analyses :param assembly: assembly path/file :param allele: combined allele file :param sample: sample object :return:
def job_status(job_id, show_job_key=False, ignore_auth=False): '''Show a specific job. **Results:** :rtype: A dictionary with the following keys :param status: Status of job (complete, error) :type status: string :param sent_data: Input data for job :type sent_data: json encodable data ...
Show a specific job. **Results:** :rtype: A dictionary with the following keys :param status: Status of job (complete, error) :type status: string :param sent_data: Input data for job :type sent_data: json encodable data :param job_id: An identifier for the job :type job_id: string ...
def read_config(self, correlation_id, parameters): """ Reads configuration and parameterize it with given values. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuration or null to skip parameteri...
Reads configuration and parameterize it with given values. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuration or null to skip parameterization. :return: ConfigParams configuration.
def register_callback_subscribed(self, callback): """ Register a callback for new subscription. This gets called whenever one of *your* things subscribes to something else. `Note` it is not called when whenever something else subscribes to your thing. The payload passed to your...
Register a callback for new subscription. This gets called whenever one of *your* things subscribes to something else. `Note` it is not called when whenever something else subscribes to your thing. The payload passed to your callback is either a [RemoteControl](RemotePoint.m.html#Iotic...
def parse_line(self, line, lineno): """Parse a single line of the log. We have to handle both buildbot style logs as well as Taskcluster logs. The latter attempt to emulate the buildbot logs, but don't accurately do so, partly due to the way logs are generated in Taskcluster (ie: on the...
Parse a single line of the log. We have to handle both buildbot style logs as well as Taskcluster logs. The latter attempt to emulate the buildbot logs, but don't accurately do so, partly due to the way logs are generated in Taskcluster (ie: on the workers themselves). Buildbot logs: ...
def _intersection_with_dsis(self, dsis): """ Intersection with another :class:`DiscreteStridedIntervalSet`. :param dsis: The other operand. :return: """ new_si_set = set() for si in dsis._si_set: r = self._intersection_with_si(si) if ...
Intersection with another :class:`DiscreteStridedIntervalSet`. :param dsis: The other operand. :return:
def build_managers(app, conf): """ Takes in a config file as outlined in job_managers.ini.sample and builds a dictionary of job manager objects from them. """ # Load default options from config file that apply to all # managers. default_options = _get_default_options(conf) manager_descr...
Takes in a config file as outlined in job_managers.ini.sample and builds a dictionary of job manager objects from them.
def _init_objaartall(self): """Get background database info for making ASCII art.""" kws = { 'sortgo':lambda nt: [nt.NS, nt.dcnt], # fmtgo=('{p_fdr_bh:8.2e} {GO} ' # Formatting for GO terms in grouped GO list 'fmtgo':('{hdr1usr01:2} {NS} {GO} {s_fdr_bh:8} ...
Get background database info for making ASCII art.
def get_program(name, config, ptype="cmd", default=None): """Retrieve program information from the configuration. This handles back compatible location specification in input YAML. The preferred location for program information is in `resources` but the older `program` tag is also supported. """ ...
Retrieve program information from the configuration. This handles back compatible location specification in input YAML. The preferred location for program information is in `resources` but the older `program` tag is also supported.
def _get_error_message(response): """Attempt to extract an error message from response body""" try: data = response.json() if "error_description" in data: return data['error_description'] if "error" in data: return data['error'] except Exception: pass ...
Attempt to extract an error message from response body
def p_annotation_spdx_id_1(self, p): """annotation_spdx_id : ANNOTATION_SPDX_ID LINE""" try: if six.PY2: value = p[2].decode(encoding='utf-8') else: value = p[2] self.builder.set_annotation_spdx_id(self.document, value) except C...
annotation_spdx_id : ANNOTATION_SPDX_ID LINE
def track_time(self, name, description='', max_rows=None): """ Create a Timer object in the Tracker. """ if name in self._tables: raise TableConflictError(name) if max_rows is None: max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE self.register_...
Create a Timer object in the Tracker.
def save_as_pil(self, fname, pixel_array=None): """ This method saves the image from a numpy array using Pillow (PIL fork) :param fname: Location and name of the image file to be saved. :param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value This method will retur...
This method saves the image from a numpy array using Pillow (PIL fork) :param fname: Location and name of the image file to be saved. :param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value This method will return True if successful
def get_opener(self, protocol): # type: (Text) -> Opener """Get the opener class associated to a given protocol. Arguments: protocol (str): A filesystem protocol. Returns: Opener: an opener instance. Raises: ~fs.opener.errors.UnsupportedProt...
Get the opener class associated to a given protocol. Arguments: protocol (str): A filesystem protocol. Returns: Opener: an opener instance. Raises: ~fs.opener.errors.UnsupportedProtocol: If no opener could be found for the given protocol. ...
def delete_all_but(self, prefix, name): """ :param prefix: INDEX MUST HAVE THIS AS A PREFIX AND THE REMAINDER MUST BE DATE_TIME :param name: INDEX WITH THIS NAME IS NOT DELETED :return: """ if prefix == name: Log.note("{{index_name}} will not be deleted", {"in...
:param prefix: INDEX MUST HAVE THIS AS A PREFIX AND THE REMAINDER MUST BE DATE_TIME :param name: INDEX WITH THIS NAME IS NOT DELETED :return:
def get_undefined_namespaces(graph: BELGraph) -> Set[str]: """Get all namespaces that are used in the BEL graph aren't actually defined.""" return { exc.namespace for _, exc, _ in graph.warnings if isinstance(exc, UndefinedNamespaceWarning) }
Get all namespaces that are used in the BEL graph aren't actually defined.
def cons(self, i): """ True iff b[i] is a consonant """ if self.b[i] in 'aeiou': return False elif self.b[i] == 'y': return True if i == 0 else not self.cons(i-1) return True
True iff b[i] is a consonant
def load(ctx, variant_source, family_file, family_type, root): """ Load a variant source into the database. If no database was found run puzzle init first. 1. VCF: If a vcf file is used it can be loaded with a ped file 2. GEMINI: Ped information will be retreived from the gemini db """ roo...
Load a variant source into the database. If no database was found run puzzle init first. 1. VCF: If a vcf file is used it can be loaded with a ped file 2. GEMINI: Ped information will be retreived from the gemini db
def parse(text): """Parse the given text into metadata and strip it for a Markdown parser. :param text: text to be parsed """ rv = {} m = META.match(text) while m: key = m.group(1) value = m.group(2) value = INDENTATION.sub('\n', value.strip()) rv[key] = value ...
Parse the given text into metadata and strip it for a Markdown parser. :param text: text to be parsed
def allFileExists(fileList): """Check that all file exists. :param fileList: the list of file to check. :type fileList: list Check if all the files in ``fileList`` exists. """ allExists = True for fileName in fileList: allExists = allExists and os.path.isfile(fileName) return...
Check that all file exists. :param fileList: the list of file to check. :type fileList: list Check if all the files in ``fileList`` exists.
def rpc_name(rpc_id): """Map an RPC id to a string name. This function looks the RPC up in a map of all globally declared RPCs, and returns a nice name string. if the RPC is not found in the global name map, returns a generic name string such as 'rpc 0x%04X'. Args: rpc_id (int): The id of...
Map an RPC id to a string name. This function looks the RPC up in a map of all globally declared RPCs, and returns a nice name string. if the RPC is not found in the global name map, returns a generic name string such as 'rpc 0x%04X'. Args: rpc_id (int): The id of the RPC that we wish to look...
def _handshake(self): """ Perform an initial TLS handshake """ session_context = None ssl_policy_ref = None crl_search_ref = None crl_policy_ref = None ocsp_search_ref = None ocsp_policy_ref = None policy_array_ref = None try: ...
Perform an initial TLS handshake
def reorderChild(self, parent, newitem): """Reorder a list to match target by moving a sequence at a time. Written for QtAbstractItemModel.moveRows. """ source = self.getItem(parent).childItems target = newitem.childItems i = 0 while i < len(source): ...
Reorder a list to match target by moving a sequence at a time. Written for QtAbstractItemModel.moveRows.
def set_duplicated_flag(self): """ For all package set flag duplicated, if it's not unique package :return: """ package_by_name = defaultdict(list) for package1 in self._root_package.all_packages: if package1 is None: continue pkg_...
For all package set flag duplicated, if it's not unique package :return:
def theme_color(self): """ A member of :ref:`MsoThemeColorIndex` or |None| if no theme color is specified. When :attr:`type` is `MSO_COLOR_TYPE.THEME`, the value of this property will always be a member of :ref:`MsoThemeColorIndex`. When :attr:`type` has any other value, the valu...
A member of :ref:`MsoThemeColorIndex` or |None| if no theme color is specified. When :attr:`type` is `MSO_COLOR_TYPE.THEME`, the value of this property will always be a member of :ref:`MsoThemeColorIndex`. When :attr:`type` has any other value, the value of this property is |None|. ...
def add_program(self, name=None): """Create a program and add it to this MultiProgram. It is the caller's responsibility to keep a reference to the returned program. The *name* must be unique, but is otherwise arbitrary and used for debugging purposes. ...
Create a program and add it to this MultiProgram. It is the caller's responsibility to keep a reference to the returned program. The *name* must be unique, but is otherwise arbitrary and used for debugging purposes.
def _coerce_dtype(self, other_dtype): """Possibly change the bin content type to allow correct operations with other operand. Parameters ---------- other_dtype : np.dtype or type """ if self._dtype is None: new_dtype = np.dtype(other_dtype) else: ...
Possibly change the bin content type to allow correct operations with other operand. Parameters ---------- other_dtype : np.dtype or type
def check_overlap(self, other, wavelengths=None, threshold=0.01): """Check for wavelength overlap between two spectra. Only wavelengths where ``self`` throughput is non-zero are considered. Example of full overlap:: |---------- other ----------| |------ self...
Check for wavelength overlap between two spectra. Only wavelengths where ``self`` throughput is non-zero are considered. Example of full overlap:: |---------- other ----------| |------ self ------| Examples of partial overlap:: |---------- self...
def pyeapi_config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' .. versionadded:: 2019.2.0 Configures the Arista switch with th...
.. versionadded:: 2019.2.0 Configures the Arista switch with the specified commands, via the ``pyeapi`` library. This function forwards the existing connection details to the :mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>` execution function. commands The list of config...
def show_xticklabels(self, row, column): """Show the x-axis tick labels for a subplot. :param row,column: specify the subplot. """ subplot = self.get_subplot_at(row, column) subplot.show_xticklabels()
Show the x-axis tick labels for a subplot. :param row,column: specify the subplot.
def env_string(name, required=False, default=empty): """Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: ...
Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable i...
def load_spectrum(path, smoothing=181, DF=-8.): """Load a Phoenix model atmosphere spectrum. path : string The file path to load. smoothing : integer Smoothing to apply. If None, do not smooth. If an integer, smooth with a Hamming window. Otherwise, the variable is assumed to be a differe...
Load a Phoenix model atmosphere spectrum. path : string The file path to load. smoothing : integer Smoothing to apply. If None, do not smooth. If an integer, smooth with a Hamming window. Otherwise, the variable is assumed to be a different smoothing window, and the data will be convolv...
def get_bool(_bytearray, byte_index, bool_index): """ Get the boolean value from location in bytearray """ index_value = 1 << bool_index byte_value = _bytearray[byte_index] current_value = byte_value & index_value return current_value == index_value
Get the boolean value from location in bytearray
def format_status(self, width=None, label_width=None, progress_width=None, summary_width=None): """Generate the formatted status bar string.""" if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] ...
Generate the formatted status bar string.
def split_address(address): """ Returns (host, port) with an integer port from the specified address string. (None, None) is returned if the address is invalid. """ invalid = None, None if not address and address != 0: return invalid components = str(address).split(':') if len(...
Returns (host, port) with an integer port from the specified address string. (None, None) is returned if the address is invalid.
def send_terrain_data(self): '''send some terrain data''' for bit in range(56): if self.current_request.mask & (1<<bit) and self.sent_mask & (1<<bit) == 0: self.send_terrain_data_bit(bit) return # no bits to send self.current_request = None ...
send some terrain data
def capture_termination_signal(please_stop): """ WILL SIGNAL please_stop WHEN THIS AWS INSTANCE IS DUE FOR SHUTDOWN """ def worker(please_stop): seen_problem = False while not please_stop: request_time = (time.time() - timer.START)/60 # MINUTES try: ...
WILL SIGNAL please_stop WHEN THIS AWS INSTANCE IS DUE FOR SHUTDOWN
def MACRO_DEFINITION(self, cursor): """ Parse MACRO_DEFINITION, only present if the TranslationUnit is used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD. """ # TODO: optionalize macro parsing. It takes a LOT of time. # ignore system macro if (not hasattr(...
Parse MACRO_DEFINITION, only present if the TranslationUnit is used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD.
def get_persistent_boot_device(self): """Get current persistent boot device set for the host :returns: persistent boot device for the system :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) # Return boot device if it ...
Get current persistent boot device set for the host :returns: persistent boot device for the system :raises: IloError, on an error from iLO.
def libvlc_video_get_adjust_float(p_mi, option): '''Get float adjust option. @param p_mi: libvlc media player instance. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later. ''' f = _Cfunctions.get('libvlc_video_get_adjust_float', None) or...
Get float adjust option. @param p_mi: libvlc media player instance. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later.
def port_profile_domain_profile_profile_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile_domain = ET.SubElement(config, "port-profile-domain", xmlns="urn:brocade.com:mgmt:brocade-port-profile") port_profile_domain_name_key = ET.SubElemen...
Auto Generated Code
def empirical_sinkhorn_divergence(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Compute the sinkhorn divergence loss from empirical data The function solves the following optimization problems and return the sinkhorn diverg...
Compute the sinkhorn divergence loss from empirical data The function solves the following optimization problems and return the sinkhorn divergence :math:`S`: .. math:: W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_...
def set_attribute(self, key, value): ''' Add or update the value of an attribute. ''' if isinstance(key, int): self.children[key] = value elif isinstance(key, basestring): self.attributes[key] = value else: raise TypeError('Only integer and string types are valid for assigning ...
Add or update the value of an attribute.
def get_voltage(self, channel): """ channel: 1=OP1, 2=OP2, AUX is not supported""" ret = self.ask("V%dO?" % channel) if ret[-1] != "V": print("ttiQl355tp.get_voltage() format error", ret) return None return float(ret[:-1])
channel: 1=OP1, 2=OP2, AUX is not supported
def dialog_mode(self, dialog_mode): """Switch on/off the speaker's dialog mode. :param dialog_mode: Enable or disable dialog mode :type dialog_mode: bool :raises NotSupportedException: If the device does not support dialog mode. """ if not self.is_soundbar: ...
Switch on/off the speaker's dialog mode. :param dialog_mode: Enable or disable dialog mode :type dialog_mode: bool :raises NotSupportedException: If the device does not support dialog mode.
def n_point_crossover(random, mom, dad, args): """Return the offspring of n-point crossover on the candidates. This function performs n-point crossover (NPX). It selects *n* random points without replacement at which to 'cut' the candidate solutions and recombine them. .. Arguments: rando...
Return the offspring of n-point crossover on the candidates. This function performs n-point crossover (NPX). It selects *n* random points without replacement at which to 'cut' the candidate solutions and recombine them. .. Arguments: random -- the random number generator object mom -- ...
def _get_function_transitions(self, expression: Union[str, List], expected_type: PredicateType) -> Tuple[List[str], PredicateType, ...
A helper method for ``_get_transitions``. This gets the transitions for the predicate itself in a function call. If we only had simple functions (e.g., "(add 2 3)"), this would be pretty straightforward and we wouldn't need a separate method to handle it. We split it out into its own method b...
def scan(self, string): """ Returns True if search(Sentence(string)) may yield matches. If is often faster to scan prior to creating a Sentence and searching it. """ # In the following example, first scan the string for "good" and "bad": # p = Pattern.fromstring("good|bad NN"...
Returns True if search(Sentence(string)) may yield matches. If is often faster to scan prior to creating a Sentence and searching it.
def replace(state, host, name, match, replace, flags=None): ''' A simple shortcut for replacing text in files with sed. + name: target remote file to edit + match: text/regex to match for + replace: text to replace with + flags: list of flaggs to pass to sed ''' yield sed_replace(name,...
A simple shortcut for replacing text in files with sed. + name: target remote file to edit + match: text/regex to match for + replace: text to replace with + flags: list of flaggs to pass to sed
async def georadius(self, name, longitude, latitude, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None): """ Return the members of the specified key identified by the ``name`` arg...
Return the members of the specified key identified by the ``name`` argument which are within the borders of the area specified with the ``latitude`` and ``longitude`` location and the maximum distance from the center specified by the ``radius`` value. The units must be one of the follow...
def create_file_combobox(self, text, choices, option, default=NoDefault, tip=None, restart=False, filters=None, adjust_to_contents=False, default_line_edit=False): """choices: couples (name, key)""" combobox = Fi...
choices: couples (name, key)
def address_from_public_key(pk_bytes): """Returns the base32-encoded version of pk_bytes (G...) """ final_bytes = bytearray() # version final_bytes.append(6 << 3) # public key final_bytes.extend(pk_bytes) # checksum final_bytes.extend(struct.pack("<H", _crc16_checksum(final_bytes)))...
Returns the base32-encoded version of pk_bytes (G...)
def get_metrics(self): """Calculate ratio_comment_to_code and return with the other values""" if(self.sloc == 0): if(self.comments == 0): ratio_comment_to_code = 0.00 else: ratio_comment_to_code = 1.00 else: ratio_comment_to_cod...
Calculate ratio_comment_to_code and return with the other values
def write_backreferences(seen_backrefs, gallery_conf, target_dir, fname, snippet): """Writes down back reference files, which include a thumbnail list of examples using a certain module""" if gallery_conf['backreferences_dir'] is None: return example_file = os.path.join...
Writes down back reference files, which include a thumbnail list of examples using a certain module
def DeregisterMountPoint(cls, mount_point): """Deregisters a path specification mount point. Args: mount_point (str): mount point identifier. Raises: KeyError: if the corresponding mount point is not set. """ if mount_point not in cls._mount_points: raise KeyError('Mount point: {...
Deregisters a path specification mount point. Args: mount_point (str): mount point identifier. Raises: KeyError: if the corresponding mount point is not set.
def f_add_parameter(self, *args, **kwargs): """ Adds a parameter under the current node. There are two ways to add a new parameter either by adding a parameter instance: >>> new_parameter = Parameter('group1.group2.myparam', data=42, comment='Example!') >>> traj.f_add_parameter(new_par...
Adds a parameter under the current node. There are two ways to add a new parameter either by adding a parameter instance: >>> new_parameter = Parameter('group1.group2.myparam', data=42, comment='Example!') >>> traj.f_add_parameter(new_parameter) Or by passing the values directly to th...
def load_file(folder_path, idx, corpus): """ Load speaker, file, utterance, labels for the file with the given id. """ xml_path = os.path.join(folder_path, '{}.xml'.format(idx)) wav_paths = glob.glob(os.path.join(folder_path, '{}_*.wav'.format(idx))) if len(wav_paths) ==...
Load speaker, file, utterance, labels for the file with the given id.
def get_gene_disease(self, direct_evidence=None, inference_chemical_name=None, inference_score=None, gene_name=None, gene_symbol=None, gene_id=None, disease_name=None, disease_id=None, disease_definition=None, limit=None, as_df=False): """Get gene–disease associ...
Get gene–disease associations :param bool as_df: if set to True result returns as `pandas.DataFrame` :param int gene_id: gene identifier :param str gene_symbol: gene symbol :param str gene_name: gene name :param str direct_evidence: direct evidence :param str inference_...
def replace(old, new): """ A simple way to replace one element node with another. """ parent = old.getparent() parent.replace(old, new)
A simple way to replace one element node with another.
def order_vertices(self): """Order vertices in the graph such that parents always have a lower index than children.""" ordered = False while ordered == False: for i in range(len(self.vertices)): ordered = True for parent in self.vertices[i].pa...
Order vertices in the graph such that parents always have a lower index than children.
def auth_user_remote_user(self, username): """ REMOTE_USER user Authentication :param username: user's username for remote auth :type self: User model """ user = self.find_user(username=username) # User does not exist, create one if auto user registr...
REMOTE_USER user Authentication :param username: user's username for remote auth :type self: User model
def zip_file(fn, mode="r"): """ returns either a zipfile.ZipFile instance or an ExplodedZipFile instance, depending on whether fn is the name of a valid zip file, or a directory. """ if isdir(fn): return ExplodedZipFile(fn) elif is_zipfile(fn): return ZipFile(fn, mode) e...
returns either a zipfile.ZipFile instance or an ExplodedZipFile instance, depending on whether fn is the name of a valid zip file, or a directory.
def next_except_jump(self, start): """ Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or None if not found. """ if self.code[start] == self.opc.DUP_TOP: except_match = self.first_instr(start, len(self.cod...
Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or None if not found.
def request_data(key, url, file, string_content, start, end, fix_apple): """ Request data, update local data cache and remove this Thread form queue. :param key: key for data source to get result later :param url: iCal URL :param file: iCal file path :param string_content: iCal content as strin...
Request data, update local data cache and remove this Thread form queue. :param key: key for data source to get result later :param url: iCal URL :param file: iCal file path :param string_content: iCal content as string :param start: start date :param end: end date :param fix_apple: fix kno...
def get_stp_mst_detail_output_msti_port_configured_root_guard(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
Auto Generated Code
def get_compounds(identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs): """Retrieve the specified compound records from PubChem. :param identifier: The compound identifier to use as a search query. :param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi...
Retrieve the specified compound records from PubChem. :param identifier: The compound identifier to use as a search query. :param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi, inchikey or formula. :param searchtype: (optional) The advanced search type, one of substructure...