code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def compute_exit_code(config, exception=None): """Compute an exit code for mutmut mutation testing The following exit codes are available for mutmut: * 0 if all mutants were killed (OK_KILLED) * 1 if a fatal error occurred * 2 if one or more mutants survived (BAD_SURVIVED) * 4 if one or mor...
Compute an exit code for mutmut mutation testing The following exit codes are available for mutmut: * 0 if all mutants were killed (OK_KILLED) * 1 if a fatal error occurred * 2 if one or more mutants survived (BAD_SURVIVED) * 4 if one or more mutants timed out (BAD_TIMEOUT) * 8 if one or m...
def _get_nd_basic_indexing(self, key): """This function is called when key is a slice, or an integer, or a tuple of slices or integers""" shape = self.shape if isinstance(key, integer_types): if key > shape[0] - 1: raise IndexError( 'index ...
This function is called when key is a slice, or an integer, or a tuple of slices or integers
def push_session(document, session_id=None, url='default', io_loop=None): ''' Create a session by pushing the given document to the server, overwriting any existing server-side document. ``session.document`` in the returned session will be your supplied document. While the connection to the server is o...
Create a session by pushing the given document to the server, overwriting any existing server-side document. ``session.document`` in the returned session will be your supplied document. While the connection to the server is open, changes made on the server side will be applied to this document, and cha...
def repr_type(obj): """ Return a string representation of a value and its type for readable error messages. """ the_type = type(obj) if (not py3compat.PY3) and the_type is InstanceType: # Old-style class. the_type = obj.__class__ msg = '%r %r' % (obj, the_type) return msg
Return a string representation of a value and its type for readable error messages.
def detect_types( field_names, field_values, field_types=DEFAULT_TYPES, skip_indexes=None, type_detector=TypeDetector, fallback_type=TextField, *args, **kwargs ): """Detect column types (or "where the magic happens")""" # TODO: look strategy of csv.Sniffer.has_header # TODO:...
Detect column types (or "where the magic happens")
def main(args): ''' surface_to_rubbon.main(args) can be given a list of arguments, such as sys.argv[1:]; these arguments may include any options and must include exactly one subject id and one output filename. Additionally one or two surface input filenames must be given. The surface files are proje...
surface_to_rubbon.main(args) can be given a list of arguments, such as sys.argv[1:]; these arguments may include any options and must include exactly one subject id and one output filename. Additionally one or two surface input filenames must be given. The surface files are projected into the ribbon and wri...
async def create_source_event_stream( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, ) -> Union[AsyncIterable[Any], ExecutionRes...
Create source even stream Implements the "CreateSourceEventStream" algorithm described in the GraphQL specification, resolving the subscription source event stream. Returns a coroutine that yields an AsyncIterable. If the client provided invalid arguments, the source stream could not be created, ...
def upload_slice_file(self, real_file_path, slice_size, file_name, offset=0, dir_name=None): """ 此分片上传代码由GitHub用户a270443177(https://github.com/a270443177)友情提供 :param real_file_path: :param slice_size: :param file_name: :param offset: :param dir_name: :ret...
此分片上传代码由GitHub用户a270443177(https://github.com/a270443177)友情提供 :param real_file_path: :param slice_size: :param file_name: :param offset: :param dir_name: :return:
def do_loop(self, params): """ \x1b[1mNAME\x1b[0m loop - Runs commands in a loop \x1b[1mSYNOPSIS\x1b[0m loop <repeat> <pause> <cmd1> <cmd2> ... <cmdN> \x1b[1mDESCRIPTION\x1b[0m Runs <cmds> <repeat> times (0 means forever), with a pause of <pause> secs inbetween each <cmd> (0 me...
\x1b[1mNAME\x1b[0m loop - Runs commands in a loop \x1b[1mSYNOPSIS\x1b[0m loop <repeat> <pause> <cmd1> <cmd2> ... <cmdN> \x1b[1mDESCRIPTION\x1b[0m Runs <cmds> <repeat> times (0 means forever), with a pause of <pause> secs inbetween each <cmd> (0 means no pause). \x1b[1mEXAMPLES\x1b[0m ...
def add_artwork_item(self, instance, item): """ Add an artwork item e.g. Shapes, Notes and Pixmaps :param instance: Hypervisor instance :param item: Item to add """ if 'interface' in self.old_top[instance][item]: pass else: (item_type, ite...
Add an artwork item e.g. Shapes, Notes and Pixmaps :param instance: Hypervisor instance :param item: Item to add
def load_user(user_email): """Returns the currently active user as an object.""" user_obj = store.user(user_email) user_inst = LoginUser(user_obj) if user_obj else None return user_inst
Returns the currently active user as an object.
def setEnabled(self, state): """ Updates the drop shadow effect for this widget on enable/disable state change. :param state | <bool> """ super(XToolButton, self).setEnabled(state) self.updateUi()
Updates the drop shadow effect for this widget on enable/disable state change. :param state | <bool>
def get_all_json_from_indexq(self): ''' Gets all data from the todo files in indexq and returns one huge list of all data. ''' files = self.get_all_as_list() out = [] for efile in files: out.extend(self._open_file(efile)) return out
Gets all data from the todo files in indexq and returns one huge list of all data.
def create_new_output_file(sampler, filename, force=False, injection_file=None, **kwargs): """Creates a new output file. If the output file already exists, an ``OSError`` will be raised. This can be overridden by setting ``force`` to ``True``. Parameters ---------- s...
Creates a new output file. If the output file already exists, an ``OSError`` will be raised. This can be overridden by setting ``force`` to ``True``. Parameters ---------- sampler : sampler instance Sampler filename : str Name of the file to create. force : bool, optional ...
def _get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): """Retrieve a server certificate Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version'...
Retrieve a server certificate Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.
def eval_detection_voc(pred_boxlists, gt_boxlists, iou_thresh=0.5, use_07_metric=False): """Evaluate on voc dataset. Args: pred_boxlists(list[BoxList]): pred boxlist, has labels and scores fields. gt_boxlists(list[BoxList]): ground truth boxlist, has labels field. iou_thresh: iou thresh ...
Evaluate on voc dataset. Args: pred_boxlists(list[BoxList]): pred boxlist, has labels and scores fields. gt_boxlists(list[BoxList]): ground truth boxlist, has labels field. iou_thresh: iou thresh use_07_metric: boolean Returns: dict represents the results
def metarate(self, func, name='values'): """ Set the values object to the function object's namespace """ setattr(func, name, self.values) return func
Set the values object to the function object's namespace
def get_snapshots(topology): """ Return the paths of any snapshot topologies :param str topology: topology file :return: list of dicts containing snapshot topologies :rtype: list """ snapshots = [] snap_dir = os.path.join(topology_dirname(topology), 'snapshots') if os.path.exists(sn...
Return the paths of any snapshot topologies :param str topology: topology file :return: list of dicts containing snapshot topologies :rtype: list
def find_version_by_string_lib(line): # type: (str)->Optional[str] """ No regex parsing. Or at least, mostly, not regex. """ if not line: return None simplified_line = simplify_line(line) version = None if simplified_line.startswith("version="): if '"' not in simplified_line...
No regex parsing. Or at least, mostly, not regex.
def on_delete(self, forced): """Session expiration callback `forced` If session item explicitly deleted, forced will be set to True. If item expired, will be set to False. """ # Do not remove connection if it was not forced and there's running connection ...
Session expiration callback `forced` If session item explicitly deleted, forced will be set to True. If item expired, will be set to False.
def ReadPreprocessingInformation(self, knowledge_base): """Reads preprocessing information. The preprocessing information contains the system configuration which contains information about various system specific configuration data, for example the user accounts. Args: knowledge_base (Knowle...
Reads preprocessing information. The preprocessing information contains the system configuration which contains information about various system specific configuration data, for example the user accounts. Args: knowledge_base (KnowledgeBase): is used to store the preprocessing informat...
def _item_to_metric(iterator, log_metric_pb): """Convert a metric protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_metric_pb: :class:`.logging_metrics_pb2.LogMetric` :param log_...
Convert a metric protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_metric_pb: :class:`.logging_metrics_pb2.LogMetric` :param log_metric_pb: Metric protobuf returned from the API. ...
def _checkDimensionsListLike(arrays): """Check that each array in a list of arrays has the same size. """ dim1 = len(arrays) dim2, dim3 = arrays[0].shape for aa in range(1, dim1): dim2_aa, dim3_aa = arrays[aa].shape if (dim2_aa != dim2) or (dim3_aa != dim3): raise _error...
Check that each array in a list of arrays has the same size.
def get_import_stacklevel(import_hook): """Returns the stacklevel value for warnings.warn() for when the warning gets emitted by an imported module, but the warning should point at the code doing the import. Pass import_hook=True if the warning gets generated by an import hook (warn() gets called i...
Returns the stacklevel value for warnings.warn() for when the warning gets emitted by an imported module, but the warning should point at the code doing the import. Pass import_hook=True if the warning gets generated by an import hook (warn() gets called in load_module(), see PEP302)
def iniedited(self, *args, **kwargs): """Set the current index of inimodel to modified :returns: None :rtype: None :raises: None """ self.inimodel.set_index_edited(self.files_lv.currentIndex(), True)
Set the current index of inimodel to modified :returns: None :rtype: None :raises: None
def call_handlers(self, msg): """ Reimplemented to emit signals instead of making callbacks. """ # Emit the generic signal. self.message_received.emit(msg) # Emit signals for specialized message types. msg_type = msg['header']['msg_type'] signal = getattr(self, ms...
Reimplemented to emit signals instead of making callbacks.
def check_ab(ab, verb): r"""Check source-receiver configuration. This check-function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a detailed description of the input parameters. Parameters ---------- ab : int Source-receiver con...
r"""Check source-receiver configuration. This check-function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a detailed description of the input parameters. Parameters ---------- ab : int Source-receiver configuration. verb : {0, ...
def system_monitor_mail_relay_domain_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") system_monitor_mail = ET.SubElement(config, "system-monitor-mail", xmlns="urn:brocade.com:mgmt:brocade-system-monitor") relay = ET.SubElement(system_monitor_mail, "...
Auto Generated Code
def initialize_tasks(self): """Load the input queue to capacity. Overfilling causes a deadlock when `queue.put` blocks when full, so further tasks are enqueued as results are returned. """ # Add a poison pill to shutdown each process. self.tasks = chain(self.iterable, [P...
Load the input queue to capacity. Overfilling causes a deadlock when `queue.put` blocks when full, so further tasks are enqueued as results are returned.
def _AssertDataIsList(key, lst): """Assert that lst contains list data and is not structured.""" # list and tuple are supported. Not supported are direct strings # and dictionary; these indicate too much or two little structure. if not isinstance(lst, list) and not isinstance(lst, tuple): raise NotAListEr...
Assert that lst contains list data and is not structured.
def get_config(repo): """ Get the config for the repo, merged with the default config. Returns the default config if no config file is found. """ files = get_files(repo) config = DEFAULT_CONFIG if "config.json" in files: # get the config file, parse JSON and merge it with the default...
Get the config for the repo, merged with the default config. Returns the default config if no config file is found.
def _generate_footer(notebook_object, notebook_type): """ Internal function that is used for generation of the notebooks footer. ---------- Parameters ---------- notebook_object : notebook object Object of "notebook" class where the header will be created. notebook_type : str ...
Internal function that is used for generation of the notebooks footer. ---------- Parameters ---------- notebook_object : notebook object Object of "notebook" class where the header will be created. notebook_type : str Notebook type: - "Main_Files_Signal_Samples" ...
def delete_external_link(self, id, **kwargs): # noqa: E501 """Delete a specific external link # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_external_...
Delete a specific external link # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_external_link(id, async_req=True) >>> result = thread.get() :pa...
def version(app, appbuilder): """ Flask-AppBuilder package version """ _appbuilder = import_application(app, appbuilder) click.echo( click.style( "F.A.B Version: {0}.".format(_appbuilder.version), bg="blue", fg="white" ) )
Flask-AppBuilder package version
def listar_por_equip(self, equip_id): """Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, 'nome_divisao': <...
Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, 'nome_divisao': < nome_divisao >, 'id_ambiente_logico'...
def stop(self, timeout=1.0): """Stop a running server (from another thread). Parameters ---------- timeout : float or None, optional Seconds to wait for server to have *started*. Returns ------- stopped : thread-safe Future Resolves when ...
Stop a running server (from another thread). Parameters ---------- timeout : float or None, optional Seconds to wait for server to have *started*. Returns ------- stopped : thread-safe Future Resolves when the server is stopped
def prepare_for_json_encoding(obj): """ Convert an arbitrary object into just JSON data types (list, dict, unicode str, int, bool, null). """ obj_type = type(obj) if obj_type == list or obj_type == tuple: return [prepare_for_json_encoding(item) for item in obj] if obj_type == dict...
Convert an arbitrary object into just JSON data types (list, dict, unicode str, int, bool, null).
def statement_after(self, i): """Return the statement after the *i*-th one, or `None`.""" k = i + 1 o = len(self.body) n = o + len(self.else_body) if k > 0: if k < o: return self.body.statement(k) if k > o and k < n: return ...
Return the statement after the *i*-th one, or `None`.
def platform_to_tags(platform, interpreter): """Splits a "platform" like linux_x86_64-36-cp-cp36m into its components. If a simple platform without hyphens is specified, we will fall back to using the current interpreter's tags. """ if platform.count('-') >= 3: tags = platform.rsplit('-', 3) else: ...
Splits a "platform" like linux_x86_64-36-cp-cp36m into its components. If a simple platform without hyphens is specified, we will fall back to using the current interpreter's tags.
def add_async_sender( self, partition=None, operation=None, send_timeout=60, keep_alive=30, auto_reconnect=True, loop=None): """ Add an async sender to the client to send ~azure.eventhub.common.EventData object to an EventHub. :param partition: Optionally specify...
Add an async sender to the client to send ~azure.eventhub.common.EventData object to an EventHub. :param partition: Optionally specify a particular partition to send to. If omitted, the events will be distributed to available partitions via round-robin. :type partition: str ...
def QA_data_day_resample(day_data, type_='w'): """日线降采样 Arguments: day_data {[type]} -- [description] Keyword Arguments: type_ {str} -- [description] (default: {'w'}) Returns: [type] -- [description] """ # return day_data_p.assign(open=day_data.open.resample(type_).fir...
日线降采样 Arguments: day_data {[type]} -- [description] Keyword Arguments: type_ {str} -- [description] (default: {'w'}) Returns: [type] -- [description]
def switch_state(request): """ Switch the default version state in the session. """ if request.session.get(SESSION_KEY): request.session[SESSION_KEY] = False else: request.session[SESSION_KEY] = True # Get redirect location # Don't go to non local paths url = reques...
Switch the default version state in the session.
def list_repos(remote=False): """ List repos Parameters ---------- remote: Flag """ mgr = plugins_get_mgr() if not remote: repomgr = mgr.get(what='repomanager', name='git') repos = repomgr.get_repo_list() repos.sort() return repos else: rais...
List repos Parameters ---------- remote: Flag
def get(context, request, resource=None, uid=None): """GET """ # We have a UID, return the record if uid and not resource: return api.get_record(uid) # we have a UID as resource, return the record if api.is_uid(resource): return api.get_record(resource) portal_type = api.r...
GET
def iter_bases(bases): """ Performs MRO linearization of a set of base classes. Yields each base class in turn. """ sequences = ([list(inspect.getmro(base)) for base in bases] + [list(bases)]) # Loop over sequences while True: s...
Performs MRO linearization of a set of base classes. Yields each base class in turn.
def _loop_use_cache(self, helper_function, num, fragment): """ Synthesize all fragments using the cache """ self.log([u"Examining fragment %d (cache)...", num]) fragment_info = (fragment.language, fragment.filtered_text) if self.cache.is_cached(fragment_info): self.log(u"Frag...
Synthesize all fragments using the cache
def shortentext(text, minlength, placeholder='...'): """ Shorten some text by replacing the last part with a placeholder (such as '...') :type text: string :param text: The text to shorten :type minlength: integer :param minlength: The minimum length before a shortening will occur :type p...
Shorten some text by replacing the last part with a placeholder (such as '...') :type text: string :param text: The text to shorten :type minlength: integer :param minlength: The minimum length before a shortening will occur :type placeholder: string :param placeholder: The text to append aft...
def form_query(self, columns, options={}): """ :param str columns: literal sql string for list of columns :param dict options: dict supporting a single key "direct" as in the constructor :return: sql string """ from_cl = 'FROM' direct = options.get('direct', self...
:param str columns: literal sql string for list of columns :param dict options: dict supporting a single key "direct" as in the constructor :return: sql string
def __get_host(node, vm_): ''' Return public IP, private IP, or hostname for the libcloud 'node' object ''' if __get_ssh_interface(vm_) == 'private_ips' or vm_['external_ip'] is None: ip_address = node.private_ips[0] log.info('Salt node data. Private_ip: %s', ip_address) else: ...
Return public IP, private IP, or hostname for the libcloud 'node' object
def shell(): ''' Return the default shell to use on this system ''' # Provides: # shell if salt.utils.platform.is_windows(): env_var = 'COMSPEC' default = r'C:\Windows\system32\cmd.exe' else: env_var = 'SHELL' default = '/bin/sh' return {'shell': os.env...
Return the default shell to use on this system
def calculate_dependencies(): """Calculate test dependencies First do a topological sorting based on the dependencies. Then sort the different dependency groups based on priorities. """ order = [] for g in toposort(merge_dicts(dependencies, soft_dependencies)): ...
Calculate test dependencies First do a topological sorting based on the dependencies. Then sort the different dependency groups based on priorities.
def Enumerate(): """See base class.""" # Init a HID manager hid_mgr = iokit.IOHIDManagerCreate(None, None) if not hid_mgr: raise errors.OsHidError('Unable to obtain HID manager reference') iokit.IOHIDManagerSetDeviceMatching(hid_mgr, None) # Get devices from HID manager device_set_ref...
See base class.
def delete_template(self, temp_id=None, params={}, callback=None, **kwargs): """ Delete a search template. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg temp_id: Template ID """ url = self.mk_url(*['_search', 'templa...
Delete a search template. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg temp_id: Template ID
def text2lm(text, output_file, vocab_file=None, text2idngram_kwargs={}, idngram2lm_kwargs={}): """ Convienience function to directly convert text (and vocabulary) into a language model. """ if vocab_file: used_vocab_file = vocab_file else: # Create temporary vocab file wi...
Convienience function to directly convert text (and vocabulary) into a language model.
def oneshot(self, query, **params): """Run a oneshot search and returns a streaming handle to the results. The ``InputStream`` object streams XML fragments from the server. To parse this stream into usable Python objects, pass the handle to :class:`splunklib.results.ResultsReader`:: ...
Run a oneshot search and returns a streaming handle to the results. The ``InputStream`` object streams XML fragments from the server. To parse this stream into usable Python objects, pass the handle to :class:`splunklib.results.ResultsReader`:: import splunklib.client as client ...
def on(self, left_speed, right_speed): """ Start rotating the motors according to ``left_speed`` and ``right_speed`` forever. Speeds can be percentages or any SpeedValue implementation. """ (left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(...
Start rotating the motors according to ``left_speed`` and ``right_speed`` forever. Speeds can be percentages or any SpeedValue implementation.
def get_nni_installation_path(): ''' Find nni lib from the following locations in order Return nni root directory if it exists ''' def try_installation_path_sequentially(*sitepackages): '''Try different installation path sequentially util nni is found. Return None if nothing is found ...
Find nni lib from the following locations in order Return nni root directory if it exists
def unlock(self): """Unlock a mutex. If the queue is not empty, call the next function with its argument.""" if self.queue: function, argument = self.queue.popleft() function(argument) else: self.locked = False
Unlock a mutex. If the queue is not empty, call the next function with its argument.
def apply_args(job, inputs, optional_inputs=None): """ This function is error checking before the job gets updated. :param job: Must be a valid job :param inputs: Must be a tuple type :param optional_inputs: optional for OptionalInputs :return: job """ _apply_args_loop(job, inputs, I...
This function is error checking before the job gets updated. :param job: Must be a valid job :param inputs: Must be a tuple type :param optional_inputs: optional for OptionalInputs :return: job
def get_resource_bin_session(self, proxy): """Gets the session for retrieving resource to bin mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceBinSession) - a ``ResourceBinSession`` raise: NullArgument - ``proxy`` is ``null`` ra...
Gets the session for retrieving resource to bin mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceBinSession) - a ``ResourceBinSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request ...
def _bin_op(instance, opnode, op, other, context, reverse=False): """Get an inference callable for a normal binary operation. If *reverse* is True, then the reflected method will be used instead. """ if reverse: method_name = protocols.REFLECTED_BIN_OP_METHOD[op] else: method_name =...
Get an inference callable for a normal binary operation. If *reverse* is True, then the reflected method will be used instead.
def bounded_by_sigmas(self, sigmas=3, square=False): """Returns a bounded subspace (SubspaceBounded) with limits given by Subspace.limits_sigma() :rtype: SubspaceBounded """ bounds = self.limits_sigma(sigmas=sigmas, square=square) return SubspaceBounded(self, bounds)
Returns a bounded subspace (SubspaceBounded) with limits given by Subspace.limits_sigma() :rtype: SubspaceBounded
def get_conn(self, urlparsed=None): """Returns an HTTPConnection based on the urlparse result given or the default Swift cluster (internal url) urlparse result. :param urlparsed: The result from urlparse.urlparse or None to use the default Swift cluster's value ...
Returns an HTTPConnection based on the urlparse result given or the default Swift cluster (internal url) urlparse result. :param urlparsed: The result from urlparse.urlparse or None to use the default Swift cluster's value
def estimate(s1, s2): """ Estimate the spacial relationship by examining the position of the bounding boxes. Parameters ---------- s1 : HandwrittenData s2 : HandwrittenData Returns ------- dict of probabilities {'bottom': 0.1, 'subscript': 0.2, 'right'...
Estimate the spacial relationship by examining the position of the bounding boxes. Parameters ---------- s1 : HandwrittenData s2 : HandwrittenData Returns ------- dict of probabilities {'bottom': 0.1, 'subscript': 0.2, 'right': 0.3, 'superscript': 0.3...
def imbalance_metrics(data): """ Computes imbalance metric for a given dataset. Imbalance metric is equal to 0 when a dataset is perfectly balanced (i.e. number of in each class is exact). :param data : pandas.DataFrame A dataset in a panda's data frame :returns int A value of imbalan...
Computes imbalance metric for a given dataset. Imbalance metric is equal to 0 when a dataset is perfectly balanced (i.e. number of in each class is exact). :param data : pandas.DataFrame A dataset in a panda's data frame :returns int A value of imbalance metric, where zero means that the ...
def get_indicator(self, resource): """Return the modification time and size of a `Resource`.""" path = resource.real_path # on dos, mtime does not change for a folder when files are added if os.name != 'posix' and os.path.isdir(path): return (os.path.getmtime(path), ...
Return the modification time and size of a `Resource`.
def j0(x, context=None): """ Return the value of the first kind Bessel function of order 0 at x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_j0, (BigFloat._implicit_convert(x),), context, )
Return the value of the first kind Bessel function of order 0 at x.
async def data( self, message: Union[str, bytes], timeout: DefaultNumType = _default ) -> SMTPResponse: """ Send an SMTP DATA command, followed by the message given. This method transfers the actual email content to the server. :raises SMTPDataError: on unexpected server res...
Send an SMTP DATA command, followed by the message given. This method transfers the actual email content to the server. :raises SMTPDataError: on unexpected server response code :raises SMTPServerDisconnected: connection lost
def cmd_slow_requests(self): """List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally. ...
List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally.
def objective_fun(theta, hamiltonian=None, quantum_resource=QVMConnection(sync_endpoint='http://localhost:5000')): """ Evaluate the Hamiltonian bny operator averaging :param theta: :param hamiltonian: :return: """ if hamiltonian is None: # Hamiltonian is Identity ...
Evaluate the Hamiltonian bny operator averaging :param theta: :param hamiltonian: :return:
def _pos(self, idx): """Convert an index into a pair (alpha, beta) that can be used to access the corresponding _lists[alpha][beta] position. Most queries require the index be built. Details of the index are described in self._build_index. Indexing requires traversing the tree ...
Convert an index into a pair (alpha, beta) that can be used to access the corresponding _lists[alpha][beta] position. Most queries require the index be built. Details of the index are described in self._build_index. Indexing requires traversing the tree to a leaf node. Each node has ...
def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\ -> InstanceNode: '''Wraps passed instance with InstanceNode''' return InstanceNode(instance, xml_node, node_globals)
Wraps passed instance with InstanceNode
def get_items_for_config_file_output(self, source_to_settings, parsed_namespace): """Converts the given settings back to a dictionary that can be passed to ConfigFormatParser.serialize(..). Args: source_to_settings: the dictionary described i...
Converts the given settings back to a dictionary that can be passed to ConfigFormatParser.serialize(..). Args: source_to_settings: the dictionary described in parse_known_args() parsed_namespace: namespace object created within parse_known_args() Returns: an ...
def decode_struct_fields(self, ins, fields, obj): """ Args: ins: An instance of the class representing the data type being decoded. The object will have its fields set. fields: A tuple of (field_name: str, field_validator: Validator) obj (dict): JSON-c...
Args: ins: An instance of the class representing the data type being decoded. The object will have its fields set. fields: A tuple of (field_name: str, field_validator: Validator) obj (dict): JSON-compatible dict that is being decoded. strict (bool): See :...
def get_data_file_attachment(self, identifier, resource_id): """Get path to attached data file with given resource identifer. If no data file with given id exists the result will be None. Raise ValueError if an image archive with the given resource identifier is attached to the model ru...
Get path to attached data file with given resource identifer. If no data file with given id exists the result will be None. Raise ValueError if an image archive with the given resource identifier is attached to the model run instead of a data file. Parameters ---------- ...
def update(ctx, migrate=False): '''Perform a development update''' msg = 'Update all dependencies' if migrate: msg += ' and migrate data' header(msg) info('Updating Python dependencies') lrun('pip install -r requirements/develop.pip') lrun('pip install -e .') info('Updating JavaS...
Perform a development update
def regularpage(foldername=None, pagename=None): """ Route not found by the other routes above. May point to a static template. """ if foldername is None and pagename is None: raise ExperimentError('page_not_found') if foldername is None and pagename is not None: return render_templa...
Route not found by the other routes above. May point to a static template.
def db_putString(self, db_name, key, value): """https://github.com/ethereum/wiki/wiki/JSON-RPC#db_putstring DEPRECATED """ warnings.warn('deprecated', DeprecationWarning) return (yield from self.rpc_call('db_putString', [db_name, key, val...
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_putstring DEPRECATED
def find_editor() -> str: """Find a reasonable editor to use by default for the system that the cmd2 application is running on.""" editor = os.environ.get('EDITOR') if not editor: if sys.platform[:3] == 'win': editor = 'notepad' else: # Favor command-line editors firs...
Find a reasonable editor to use by default for the system that the cmd2 application is running on.
def load_genomic_CDR3_anchor_pos_and_functionality(anchor_pos_file_name): """Read anchor position and functionality from file. Parameters ---------- anchor_pos_file_name : str File name for the functionality and position of a conserved residue that defines the CDR3 region for each V or...
Read anchor position and functionality from file. Parameters ---------- anchor_pos_file_name : str File name for the functionality and position of a conserved residue that defines the CDR3 region for each V or J germline sequence. Returns ------- anchor_pos_and_functio...
def _process_file(self): '''Process rebase file into dict with name and cut site information.''' print 'Processing file' with open(self._rebase_file, 'r') as f: raw = f.readlines() names = [line.strip()[3:] for line in raw if line.startswith('<1>')] seqs = [line.strip...
Process rebase file into dict with name and cut site information.
def add_additional_options(cls, parser): """ Override in subclass if required. """ group = OptionGroup(parser, "Target Engine Options", "These options are not required, but may be " "provided if a specific " ...
Override in subclass if required.
def read_stat(): """ Returns the system stat information. :returns: The system stat information. :rtype: list """ data = [] with open("/proc/stat", "rb") as stat_file: for line in stat_file: cpu_stat = line.split() if cpu_stat[0][:3] != b"cpu": ...
Returns the system stat information. :returns: The system stat information. :rtype: list
def project_closed(self, project): """ Called when a project is closed. :param project: Project instance """ yield from super().project_closed(project) hdd_files_to_close = yield from self._find_inaccessible_hdd_files() for hdd_file in hdd_files_to_close: ...
Called when a project is closed. :param project: Project instance
def sha_github_file(cls, config, repo_file, repository_api, repository_branch): """ Return the GitHub SHA for a file in the repository """ repo_file_sha = None cfg = config.get_conf() github_token = cfg['sortinghat']['identities_api_token'] headers = {"Authorization": "token " ...
Return the GitHub SHA for a file in the repository
def parse_param_signature(sig): """ Parse a parameter signature of the form: type name (= default)? """ match = PARAM_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Parameter signature invalid, got ' + sig) groups = match.groups() modifiers = groups[0].split() typ, name, _, ...
Parse a parameter signature of the form: type name (= default)?
def nz(value, none_value, strict=True): ''' This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" ...
This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" nz(x,"") --> "" y = "" ...
def get_imap_capabilities(server): """ Returns a list of an IMAP server's capabilities Args: server (imapclient.IMAPClient): An instance of imapclient.IMAPClient Returns (list): A list of capabilities """ capabilities = list(map(str, list(server.capabilities()))) for i in range(le...
Returns a list of an IMAP server's capabilities Args: server (imapclient.IMAPClient): An instance of imapclient.IMAPClient Returns (list): A list of capabilities
def quantile_for_single_value(self, **kwargs): """Returns quantile of each column or row. Returns: A new QueryCompiler object containing the quantile of each column or row. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return ...
Returns quantile of each column or row. Returns: A new QueryCompiler object containing the quantile of each column or row.
def install_package(tar_url, folder, md5_url='{tar_url}.md5', on_download=lambda: None, on_complete=lambda: None): """ Install or update a tar package that has an md5 Args: tar_url (str): URL of package to download folder (str): Location to extract tar. Will be created i...
Install or update a tar package that has an md5 Args: tar_url (str): URL of package to download folder (str): Location to extract tar. Will be created if doesn't exist md5_url (str): URL of md5 to use to check for updates on_download (Callable): Function that gets called when downlo...
def get(self, reference, country, target=datetime.date.today()): """ Get the inflation/deflation value change for the target date based on the reference date. Target defaults to today and the instance's reference and country will be used if they are not provided as parameters ...
Get the inflation/deflation value change for the target date based on the reference date. Target defaults to today and the instance's reference and country will be used if they are not provided as parameters
def ext(self): """Return the file extension for this video, e.g. 'mp4'. The extension is that from the actual filename if known. Otherwise it is the lowercase canonical extension for the video's MIME type. 'vid' is used if the MIME type is 'video/unknown'. """ if self._f...
Return the file extension for this video, e.g. 'mp4'. The extension is that from the actual filename if known. Otherwise it is the lowercase canonical extension for the video's MIME type. 'vid' is used if the MIME type is 'video/unknown'.
def is_flapping(self, alert, window=1800, count=2): """ Return true if alert severity has changed more than X times in Y seconds """ pipeline = [ {'$match': { 'environment': alert.environment, 'resource': alert.resource, 'event'...
Return true if alert severity has changed more than X times in Y seconds
def statistical_inefficiency(X, truncate_acf=True): """ Estimates the statistical inefficiency from univariate time series X The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal. Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I...
Estimates the statistical inefficiency from univariate time series X The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal. Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I \in (0,1]`, there are only :math:`I \cdot N` effective ...
def create_embedded_unclaimed_draft(self, test_mode=False, client_id=None, is_for_embedded_signing=False, requester_email_address=None, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, requesting_redirect_url=None, form_fields_per...
Creates a new Draft to be used for embedded requesting Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to True. Defaults to False. client_id (str): Cli...
def save_namespace(self, filename): """Save namespace into filename""" from spyder_kernels.utils.nsview import get_remote_data from spyder_kernels.utils.iofuncs import iofunctions ns = self._get_current_namespace() settings = self.namespace_view_settings data = get_remot...
Save namespace into filename
def raise_for_missing_namespace(self, line: str, position: int, namespace: str, name: str) -> None: """Raise an exception if the namespace is not defined.""" if not self.has_namespace(namespace): raise UndefinedNamespaceWarning(self.get_line_number(), line, position, namespace, name)
Raise an exception if the namespace is not defined.
def write(self, pack_uri, blob): """ Write *blob* to this zip package with the membername corresponding to *pack_uri*. """ self._zipf.writestr(pack_uri.membername, blob)
Write *blob* to this zip package with the membername corresponding to *pack_uri*.
def from_function(cls, function): """Create a FunctionDescriptor from a function instance. This function is used to create the function descriptor from a python function. If a function is a class function, it should not be used by this function. Args: cls: Current c...
Create a FunctionDescriptor from a function instance. This function is used to create the function descriptor from a python function. If a function is a class function, it should not be used by this function. Args: cls: Current class which is required argument for classmeth...
def param_array(self): """ Array representing the parameters of this class. There is only one copy of all parameters in memory, two during optimization. !WARNING!: setting the parameter array MUST always be done in memory: m.param_array[:] = m_copy.param_array """ ...
Array representing the parameters of this class. There is only one copy of all parameters in memory, two during optimization. !WARNING!: setting the parameter array MUST always be done in memory: m.param_array[:] = m_copy.param_array