code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def check_backend() -> bool: """Check if the backend is available.""" try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True except ImportError as importerror: _LOGGER.error('bluepy not found: %s', str(importerror)) return Fal...
Check if the backend is available.
Below is the the instruction that describes the task: ### Input: Check if the backend is available. ### Response: def check_backend() -> bool: """Check if the backend is available.""" try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True ex...
def angle_subtended(ell, **kwargs): """ Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin """ retu...
Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin
Below is the the instruction that describes the task: ### Input: Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to or...
def editText(self, y, x, w, record=True, **kwargs): 'Wrap global editText with `preedit` and `postedit` hooks.' v = self.callHook('preedit') if record else None if not v or v[0] is None: with EnableCursor(): v = editText(self.scr, y, x, w, **kwargs) else: ...
Wrap global editText with `preedit` and `postedit` hooks.
Below is the the instruction that describes the task: ### Input: Wrap global editText with `preedit` and `postedit` hooks. ### Response: def editText(self, y, x, w, record=True, **kwargs): 'Wrap global editText with `preedit` and `postedit` hooks.' v = self.callHook('preedit') if record else None ...
def _sign(self, certificate_request, password): """ Respond to a request to sign a CSR for a user or agent located within our domain. """ if self.service.portal is None: raise BadCertificateRequest("This agent cannot sign certificates.") subj = certificate_re...
Respond to a request to sign a CSR for a user or agent located within our domain.
Below is the the instruction that describes the task: ### Input: Respond to a request to sign a CSR for a user or agent located within our domain. ### Response: def _sign(self, certificate_request, password): """ Respond to a request to sign a CSR for a user or agent located within ...
def write(self, chunk, offset): """ Write chunk to file at specified position Return 0 if OK, else -1 """ return lib.zfile_write(self._as_parameter_, chunk, offset)
Write chunk to file at specified position Return 0 if OK, else -1
Below is the the instruction that describes the task: ### Input: Write chunk to file at specified position Return 0 if OK, else -1 ### Response: def write(self, chunk, offset): """ Write chunk to file at specified position Return 0 if OK, else -1 """ return lib.zfile_write(self._as_...
def transform(self, crs): """ Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox """ new_crs = CRS(crs) return BBox((transform_point(self.lower_left, self.crs, ne...
Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox
Below is the the instruction that describes the task: ### Input: Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox ### Response: def transform(self, crs): """ Transforms BBox from ...
def _get_uri(self): """ Will return the uri for an existing instance. """ if not self.service.exists(): logging.warning("Service does not yet exist.") return self.service.settings.data['uri']
Will return the uri for an existing instance.
Below is the the instruction that describes the task: ### Input: Will return the uri for an existing instance. ### Response: def _get_uri(self): """ Will return the uri for an existing instance. """ if not self.service.exists(): logging.warning("Service does not yet exis...
def _stream_vagrant_command(self, args): """ Execute a vagrant command, returning a generator of the output lines. Caller should consume the entire generator to avoid the hanging the subprocess. :param args: Arguments for the Vagrant command. :return: generator that yiel...
Execute a vagrant command, returning a generator of the output lines. Caller should consume the entire generator to avoid the hanging the subprocess. :param args: Arguments for the Vagrant command. :return: generator that yields each line of the command stdout. :rtype: generator...
Below is the the instruction that describes the task: ### Input: Execute a vagrant command, returning a generator of the output lines. Caller should consume the entire generator to avoid the hanging the subprocess. :param args: Arguments for the Vagrant command. :return: generator t...
def start (self): ''' Starts (Subscribes) the client. ''' self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback)
Starts (Subscribes) the client.
Below is the the instruction that describes the task: ### Input: Starts (Subscribes) the client. ### Response: def start (self): ''' Starts (Subscribes) the client. ''' self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback)
def get_bank_admin_session(self): """Gets the OsidSession associated with the bank administration service. return: (osid.assessment.BankAdminSession) - a ``BankAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_adm...
Gets the OsidSession associated with the bank administration service. return: (osid.assessment.BankAdminSession) - a ``BankAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_admin() is false`` *compliance: optional...
Below is the the instruction that describes the task: ### Input: Gets the OsidSession associated with the bank administration service. return: (osid.assessment.BankAdminSession) - a ``BankAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplement...
def connectionStats(self) -> ConnectionStats: """ Get statistics about the connection. """ if not self.isReady(): raise ConnectionError('Not connected') return ConnectionStats( self._startTime, time.time() - self._startTime, self._n...
Get statistics about the connection.
Below is the the instruction that describes the task: ### Input: Get statistics about the connection. ### Response: def connectionStats(self) -> ConnectionStats: """ Get statistics about the connection. """ if not self.isReady(): raise ConnectionError('Not connected') ...
def has_gocomics_comic(name): """Test if comic name already exists.""" cname = "Gocomics/%s" % name for scraperclass in get_scraperclasses(): lname = scraperclass.getName().lower() if lname == cname.lower(): return True return False
Test if comic name already exists.
Below is the the instruction that describes the task: ### Input: Test if comic name already exists. ### Response: def has_gocomics_comic(name): """Test if comic name already exists.""" cname = "Gocomics/%s" % name for scraperclass in get_scraperclasses(): lname = scraperclass.getName().lower() ...
def upload_entities(namespace, workspace, entity_data): """Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.or...
Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.org/#!/Entities/importEntities
Below is the the instruction that describes the task: ### Input: Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecl...
def Y_less(self): """Decrease the scaling.""" self.parent.value('y_scale', self.parent.value('y_scale') / 2) self.parent.traces.display()
Decrease the scaling.
Below is the the instruction that describes the task: ### Input: Decrease the scaling. ### Response: def Y_less(self): """Decrease the scaling.""" self.parent.value('y_scale', self.parent.value('y_scale') / 2) self.parent.traces.display()
def get_weights(model_hparams, vocab_size, hidden_dim=None): """Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a lis...
Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a list of num_shards Tensors.
Below is the the instruction that describes the task: ### Input: Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a ...
def merge_dependency(self, item, resolve_parent, parents): """ Merge dependencies of element with further dependencies. First parent dependencies are checked, and then immediate dependencies of the current element should be added to the list, but without duplicating any entries. :param ...
Merge dependencies of element with further dependencies. First parent dependencies are checked, and then immediate dependencies of the current element should be added to the list, but without duplicating any entries. :param item: Item. :param resolve_parent: Function to resolve parent dependenc...
Below is the the instruction that describes the task: ### Input: Merge dependencies of element with further dependencies. First parent dependencies are checked, and then immediate dependencies of the current element should be added to the list, but without duplicating any entries. :param item: Item...
def reboot(env, identifier, hard): """Reboot an active server.""" hardware_server = env.client['Hardware_Server'] mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This wi...
Reboot an active server.
Below is the the instruction that describes the task: ### Input: Reboot an active server. ### Response: def reboot(env, identifier, hard): """Reboot an active server.""" hardware_server = env.client['Hardware_Server'] mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resol...
def object_exists_in_project(obj_id, proj_id): ''' :param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project. ''' if obj_id is None: raise ValueError("Expected obj_...
:param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project.
Below is the the instruction that describes the task: ### Input: :param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project. ### Response: def object_exists_in_project(obj_id, proj_id)...
def write(self, oprot): ''' Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage ''' opro...
Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
Below is the the instruction that describes the task: ### Input: Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage ...
def security(self): """ Creates a reference to the Security operations for Portal """ url = self._url + "/security" return _Security(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, ...
Creates a reference to the Security operations for Portal
Below is the the instruction that describes the task: ### Input: Creates a reference to the Security operations for Portal ### Response: def security(self): """ Creates a reference to the Security operations for Portal """ url = self._url + "/security" return _Security(url=u...
def fillna( self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs ): """Fill NA/NaN values using the specified method. Args: value: Value to use to fill holes. This value ...
Fill NA/NaN values using the specified method. Args: value: Value to use to fill holes. This value cannot be a list. method: Method to use for filling holes in reindexed Series pad. ffill: propagate last valid observation forward to next valid bac...
Below is the the instruction that describes the task: ### Input: Fill NA/NaN values using the specified method. Args: value: Value to use to fill holes. This value cannot be a list. method: Method to use for filling holes in reindexed Series pad. ffill: propag...
def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ try: self._data[self._position] = item except IndexError: self._grow() self._data[self._position] = item self._posit...
append a single item to the array, growing the wrapped numpy array if necessary
Below is the the instruction that describes the task: ### Input: append a single item to the array, growing the wrapped numpy array if necessary ### Response: def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ ...
def sort_points(self, points): """Take points (z,x,q) and sort by increasing z""" new_points = [] z_lookup = {} for z, x, Q in points: z_lookup[z] = (z, x, Q) z_keys = z_lookup.keys() z_keys.sort() for key in z_keys: new_points.append(z_l...
Take points (z,x,q) and sort by increasing z
Below is the the instruction that describes the task: ### Input: Take points (z,x,q) and sort by increasing z ### Response: def sort_points(self, points): """Take points (z,x,q) and sort by increasing z""" new_points = [] z_lookup = {} for z, x, Q in points: z_lookup[z] ...
def p_sens_empty(self, p): 'senslist : empty' p[0] = SensList( (Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
senslist : empty
Below is the the instruction that describes the task: ### Input: senslist : empty ### Response: def p_sens_empty(self, p): 'senslist : empty' p[0] = SensList( (Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def extract_attributes(element, prefix_key_char='@', dict_constructor=dict): """ Given an XML node, extract a dictionary of attribute key-value pairs. Optional arguments: - prefix_key_char: if a character is given, the attributes keys in the resulting dictionary are prefixed with that character. ...
Given an XML node, extract a dictionary of attribute key-value pairs. Optional arguments: - prefix_key_char: if a character is given, the attributes keys in the resulting dictionary are prefixed with that character. - dict_constructor: the class used to create the resulting dictionary. Default...
Below is the the instruction that describes the task: ### Input: Given an XML node, extract a dictionary of attribute key-value pairs. Optional arguments: - prefix_key_char: if a character is given, the attributes keys in the resulting dictionary are prefixed with that character. - dict_construc...
def dump(obj): "Recursive convert a live GUI object to a resource list/dict" from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec import decimal, datetime from .font import Font from .graphic import Bitmap, Color from . import registry ret = {'type': obj.__class__.__name_...
Recursive convert a live GUI object to a resource list/dict
Below is the the instruction that describes the task: ### Input: Recursive convert a live GUI object to a resource list/dict ### Response: def dump(obj): "Recursive convert a live GUI object to a resource list/dict" from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec import decimal,...
def inspect(self, w): """ Get the value of a wirevector in the last simulation cycle. :param w: the name of the WireVector to inspect (passing in a WireVector instead of a name is deprecated) :return: value of w in the current step of simulation Will throw KeyError if w is ...
Get the value of a wirevector in the last simulation cycle. :param w: the name of the WireVector to inspect (passing in a WireVector instead of a name is deprecated) :return: value of w in the current step of simulation Will throw KeyError if w is not being tracked in the simulatio...
Below is the the instruction that describes the task: ### Input: Get the value of a wirevector in the last simulation cycle. :param w: the name of the WireVector to inspect (passing in a WireVector instead of a name is deprecated) :return: value of w in the current step of simulation ...
def _signature_hash(self, tx_out_script, unsigned_txs_out_idx, hash_type): """ Return the canonical hash for a transaction. We need to remove references to the signature, since it's a signature of the hash before the signature is applied. :param tx_out_script: the script the coi...
Return the canonical hash for a transaction. We need to remove references to the signature, since it's a signature of the hash before the signature is applied. :param tx_out_script: the script the coins for unsigned_txs_out_idx are coming from :param unsigned_txs_out_idx: where to put t...
Below is the the instruction that describes the task: ### Input: Return the canonical hash for a transaction. We need to remove references to the signature, since it's a signature of the hash before the signature is applied. :param tx_out_script: the script the coins for unsigned_txs_out_id...
def reboot(name, call=None, session=None): ''' Reboot a vm .. code-block:: bash salt-cloud -a reboot xenvm01 ''' if call == 'function': raise SaltCloudException( 'The show_instnce function must be called with -a or --action.' ) if session is None: s...
Reboot a vm .. code-block:: bash salt-cloud -a reboot xenvm01
Below is the the instruction that describes the task: ### Input: Reboot a vm .. code-block:: bash salt-cloud -a reboot xenvm01 ### Response: def reboot(name, call=None, session=None): ''' Reboot a vm .. code-block:: bash salt-cloud -a reboot xenvm01 ''' if call == 'func...
def fetch_sampling_rules(self): """ Use X-Ray botocore client to get the centralized sampling rules from X-Ray service. The call is proxied and signed by X-Ray Daemon. """ new_rules = [] resp = self._xray_client.get_sampling_rules() records = resp['SamplingRuleRe...
Use X-Ray botocore client to get the centralized sampling rules from X-Ray service. The call is proxied and signed by X-Ray Daemon.
Below is the the instruction that describes the task: ### Input: Use X-Ray botocore client to get the centralized sampling rules from X-Ray service. The call is proxied and signed by X-Ray Daemon. ### Response: def fetch_sampling_rules(self): """ Use X-Ray botocore client to get the central...
def create_legacy_graph_tasks(): """Create tasks to recursively parse the legacy graph.""" return [ transitive_hydrated_targets, transitive_hydrated_target, hydrated_targets, hydrate_target, find_owners, hydrate_sources, hydrate_bundles, RootRule(OwnersRequest), ]
Create tasks to recursively parse the legacy graph.
Below is the the instruction that describes the task: ### Input: Create tasks to recursively parse the legacy graph. ### Response: def create_legacy_graph_tasks(): """Create tasks to recursively parse the legacy graph.""" return [ transitive_hydrated_targets, transitive_hydrated_target, hydrated_ta...
def auto(cls, syslog=None, stderr=None, level=None, extended=None, server=None): """Tries to guess a sound logging configuration. """ level = norm_level(level) or logging.INFO if syslog is None and stderr is None: if sys.stderr.isatty() or syslog_path() is None: ...
Tries to guess a sound logging configuration.
Below is the the instruction that describes the task: ### Input: Tries to guess a sound logging configuration. ### Response: def auto(cls, syslog=None, stderr=None, level=None, extended=None, server=None): """Tries to guess a sound logging configuration. """ level = norm_level(...
def _av_weight(W1, W2): """ Function to convert from two seisan weights (0-4) to one hypoDD \ weight(0-1). :type W1: str :param W1: Seisan input weight (0-4) :type W2: str :param W2: Seisan input weight (0-4) :returns: str .. rubric:: Example >>> print(_av_weight(1, 4)) 0....
Function to convert from two seisan weights (0-4) to one hypoDD \ weight(0-1). :type W1: str :param W1: Seisan input weight (0-4) :type W2: str :param W2: Seisan input weight (0-4) :returns: str .. rubric:: Example >>> print(_av_weight(1, 4)) 0.3750 >>> print(_av_weight(0, 0))...
Below is the the instruction that describes the task: ### Input: Function to convert from two seisan weights (0-4) to one hypoDD \ weight(0-1). :type W1: str :param W1: Seisan input weight (0-4) :type W2: str :param W2: Seisan input weight (0-4) :returns: str .. rubric:: Example >...
def line_cap_type(self): """Cap type, one of `butt`, `round`, `square`.""" key = self._data.get(b'strokeStyleLineCapType').enum return self.STROKE_STYLE_LINE_CAP_TYPES.get(key, str(key))
Cap type, one of `butt`, `round`, `square`.
Below is the the instruction that describes the task: ### Input: Cap type, one of `butt`, `round`, `square`. ### Response: def line_cap_type(self): """Cap type, one of `butt`, `round`, `square`.""" key = self._data.get(b'strokeStyleLineCapType').enum return self.STROKE_STYLE_LINE_CAP_TYPES....
def _check_with_socket(self, sock_info): """Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure. """ start = _time() try: return (sock_info.ismaster(self._pool.opts.metadata, self._topology.max_cl...
Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure.
Below is the the instruction that describes the task: ### Input: Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure. ### Response: def _check_with_socket(self, sock_info): """Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailu...
def add_output(self, line): """ Appends {line} of output to the output instantly. (directly hits the database) :param line: the line of text to append :return: None """ Deployment.objects.filter(pk=self.id).update(output=CF('output')+line)
Appends {line} of output to the output instantly. (directly hits the database) :param line: the line of text to append :return: None
Below is the the instruction that describes the task: ### Input: Appends {line} of output to the output instantly. (directly hits the database) :param line: the line of text to append :return: None ### Response: def add_output(self, line): """ Appends {line} of output to the output ...
def activate(self, uid=None): """ Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNo...
Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNotOpen: if the client connection is unusable ...
Below is the the instruction that describes the task: ### Input: Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ...
def staff_mo(I,T,N,J,S,c,b): """ staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: sub...
staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: subset of shifts that must be kept at least ...
Below is the the instruction that describes the task: ### Input: staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift...
async def restore_networking_configuration(self): """ Restore machine's networking configuration to its initial state. """ self._data = await self._handler.restore_networking_configuration( system_id=self.system_id)
Restore machine's networking configuration to its initial state.
Below is the the instruction that describes the task: ### Input: Restore machine's networking configuration to its initial state. ### Response: async def restore_networking_configuration(self): """ Restore machine's networking configuration to its initial state. """ self._data = awa...
def conj(self, out=None): """Complex conjugate of this element. Parameters ---------- out : `DiscreteLpElement`, optional Element to which the complex conjugate is written. Must be an element of this element's space. Returns ------- out :...
Complex conjugate of this element. Parameters ---------- out : `DiscreteLpElement`, optional Element to which the complex conjugate is written. Must be an element of this element's space. Returns ------- out : `DiscreteLpElement` The ...
Below is the the instruction that describes the task: ### Input: Complex conjugate of this element. Parameters ---------- out : `DiscreteLpElement`, optional Element to which the complex conjugate is written. Must be an element of this element's space. Retur...
def as_colr( self, label_args=None, type_args=None, type_val_args=None, value_args=None, spec_args=None): """ Like __str__, except it returns a colorized Colr instance. """ label_args = label_args or {'fore': 'red'} type_args = type_args or {'fore': 'yellow'} type...
Like __str__, except it returns a colorized Colr instance.
Below is the the instruction that describes the task: ### Input: Like __str__, except it returns a colorized Colr instance. ### Response: def as_colr( self, label_args=None, type_args=None, type_val_args=None, value_args=None, spec_args=None): """ Like __str__, except it returns a c...
def add_cpds(self, *cpds): """ Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with the model Exam...
Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with the model Examples -------- >>> from pgmpy.mo...
Below is the the instruction that describes the task: ### Input: Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with t...
def internal_model_from_file( self, file_name, encoding='utf-8', debug=None, pre_ref_resolution_callback=None, is_main_model=True): """ Instantiates model from the given file. :param pre_ref_resolution_callback: called before references are resolved. This c...
Instantiates model from the given file. :param pre_ref_resolution_callback: called before references are resolved. This can be useful to manage models distributed across files (scoping)
Below is the the instruction that describes the task: ### Input: Instantiates model from the given file. :param pre_ref_resolution_callback: called before references are resolved. This can be useful to manage models distributed across files (scoping) ### Response: def internal...
def format_error(error): """Serialise exception""" formatted = {"message": str(error)} if hasattr(error, "traceback"): fname, line_no, func, exc = error.traceback formatted.update({ "fname": fname, "line_number": line_no, "func": func, "exc": ...
Serialise exception
Below is the the instruction that describes the task: ### Input: Serialise exception ### Response: def format_error(error): """Serialise exception""" formatted = {"message": str(error)} if hasattr(error, "traceback"): fname, line_no, func, exc = error.traceback formatted.update({ ...
def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Langu...
Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model.
Below is the the instruction that describes the task: ### Input: Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language...
def random(self, cascadeFetch=False): ''' Random - Returns a random record in current filterset. @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @return - Instance of M...
Random - Returns a random record in current filterset. @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @return - Instance of Model object, or None if no items math current f...
Below is the the instruction that describes the task: ### Input: Random - Returns a random record in current filterset. @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @...
def vm_trace(ext, msg, compustate, opcode, pushcache, tracer=log_vm_op): """ This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack' """ op, in_arg...
This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack'
Below is the the instruction that describes the task: ### Input: This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack' ### Response: def vm_trace(ext, msg, c...
def getaddress(self, address: str) -> dict: '''Returns information for given address.''' return cast(dict, self.ext_fetch('getaddress/' + address))
Returns information for given address.
Below is the the instruction that describes the task: ### Input: Returns information for given address. ### Response: def getaddress(self, address: str) -> dict: '''Returns information for given address.''' return cast(dict, self.ext_fetch('getaddress/' + address))
def predictor(self, (i, j, A, alpha, Bb)): "Add to chart any rules for B that could help extend this edge." B = Bb[0] if B in self.grammar.rules: for rhs in self.grammar.rewrites_for(B): self.add_edge([j, j, B, [], rhs])
Add to chart any rules for B that could help extend this edge.
Below is the the instruction that describes the task: ### Input: Add to chart any rules for B that could help extend this edge. ### Response: def predictor(self, (i, j, A, alpha, Bb)): "Add to chart any rules for B that could help extend this edge." B = Bb[0] if B in self.grammar.rules: ...
def has(selfie, self, args, kwargs): """This is called 'has' but is called indirectly. Each Property sub-class is installed with this function which replaces their __new__. It is called 'has', because it runs during property declaration, processes the arguments and is responsible for returning an appr...
This is called 'has' but is called indirectly. Each Property sub-class is installed with this function which replaces their __new__. It is called 'has', because it runs during property declaration, processes the arguments and is responsible for returning an appropriate Property subclass. As such it i...
Below is the the instruction that describes the task: ### Input: This is called 'has' but is called indirectly. Each Property sub-class is installed with this function which replaces their __new__. It is called 'has', because it runs during property declaration, processes the arguments and is responsi...
def _set_ldp_fec_prefix_prefix(self, v, load=False): """ Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefix_prefix is considered as a priv...
Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefix_prefix is considered as a private method. Backends looking to populate this variable should...
Below is the the instruction that describes the task: ### Input: Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefix_prefix is considered as a ...
def remaining_time(self): """ estimates the time remaining until script is finished """ elapsed_time = (datetime.datetime.now() - self.start_time).total_seconds() # safety to avoid devision by zero if self.progress == 0: self.progress = 1 estimated_to...
estimates the time remaining until script is finished
Below is the the instruction that describes the task: ### Input: estimates the time remaining until script is finished ### Response: def remaining_time(self): """ estimates the time remaining until script is finished """ elapsed_time = (datetime.datetime.now() - self.start_time).tot...
def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` """ target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', N...
Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None``
Below is the the instruction that describes the task: ### Input: Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` ### Response: def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadRetur...
def unpack_bitstring(length, is_float, is_signed, bits): # type: (int, bool, bool, typing.Any) -> typing.Union[float, int] """ returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_si...
returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_signed: value is signed :return:
Below is the the instruction that describes the task: ### Input: returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_signed: value is signed :return: ### Response: def unpack_bitstring...
def enc(self, byts, asscd=None): ''' Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted). Returns: bytes: T...
Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted). Returns: bytes: The encrypted message. This is a msgpacked dictionary ...
Below is the the instruction that describes the task: ### Input: Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted). Returns: ...
def getFilesForName(name): """Get a list of module files for a filename, a module or package name, or a directory. """ if not os.path.exists(name): # check for glob chars if containsAny(name, "*?[]"): files = glob.glob(name) list = [] for file in files...
Get a list of module files for a filename, a module or package name, or a directory.
Below is the the instruction that describes the task: ### Input: Get a list of module files for a filename, a module or package name, or a directory. ### Response: def getFilesForName(name): """Get a list of module files for a filename, a module or package name, or a directory. """ if not os.pa...
def worker_thread(self): """ The primary worker thread--this thread pulls from the monitor queue and runs the monitor, submitting the results to the handler queue. Calls a sub method based on type of monitor. """ self.thread_debug("Starting monitor thread") while...
The primary worker thread--this thread pulls from the monitor queue and runs the monitor, submitting the results to the handler queue. Calls a sub method based on type of monitor.
Below is the the instruction that describes the task: ### Input: The primary worker thread--this thread pulls from the monitor queue and runs the monitor, submitting the results to the handler queue. Calls a sub method based on type of monitor. ### Response: def worker_thread(self): """ ...
def render(self, **kwargs): """Renders the HTML representation of the element.""" self.json = json.dumps(self.data) self._parent.html.add_child(Element(Template(""" <div id="{{this.get_name()}}"></div> """).render(this=self, kwargs=kwargs)), name=self.get_name()) ...
Renders the HTML representation of the element.
Below is the the instruction that describes the task: ### Input: Renders the HTML representation of the element. ### Response: def render(self, **kwargs): """Renders the HTML representation of the element.""" self.json = json.dumps(self.data) self._parent.html.add_child(Element(Template(""...
def _matches_filters(self, obj, filter_args): """ Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the res...
Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the resource properties from the HMC. Parameters: obj...
Below is the the instruction that describes the task: ### Input: Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the ...
def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle ...
Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, ...
Below is the the instruction that describes the task: ### Input: Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type req...
def estimate_K_knee(self, th=.015, maxK=12): """Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC.""" # Sweep K-means if self.X.shape[0] < maxK: maxK = self.X.shape[0] if maxK < 2: maxK = 2 K = np.arange(...
Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC.
Below is the the instruction that describes the task: ### Input: Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC. ### Response: def estimate_K_knee(self, th=.015, maxK=12): """Estimates the K using K-means and BIC, by sweeping various K and ...
def multiple_replace(d: Dict[str, str], text: str) -> str: """ Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html """ # Create a regular expression from all of the dictionary keys regex = re.compile("|".join(m...
Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
Below is the the instruction that describes the task: ### Input: Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html ### Response: def multiple_replace(d: Dict[str, str], text: str) -> str: """ Performs string repla...
def list(self, bank): ''' Lists entries stored in the specified bank. :param bank: The name of the location inside the cache which will hold the key and its associated data. :return: An iterable object containing all bank entries. Returns an empty ...
Lists entries stored in the specified bank. :param bank: The name of the location inside the cache which will hold the key and its associated data. :return: An iterable object containing all bank entries. Returns an empty iterator if the bank doesn't exi...
Below is the the instruction that describes the task: ### Input: Lists entries stored in the specified bank. :param bank: The name of the location inside the cache which will hold the key and its associated data. :return: An iterable object containing all bank e...
def set_content(self, data): """ handle the content from the data :param data: contains the data from the provider :type data: dict :rtype: string """ content = self._get_content(data, 'content') if content == '': content = sel...
handle the content from the data :param data: contains the data from the provider :type data: dict :rtype: string
Below is the the instruction that describes the task: ### Input: handle the content from the data :param data: contains the data from the provider :type data: dict :rtype: string ### Response: def set_content(self, data): """ handle the content from the data ...
def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'charset_size': if v not in (1, 2, 4): raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v)) elif k == 'wide_charset_size...
Validate options.
Below is the the instruction that describes the task: ### Input: Validate options. ### Response: def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'charset_size': if v not in (1, 2, 4): raise ValueError("{}: '{}' is...
def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5): """ Wait for the virtual OS to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'up' or 'down', case sensitive Maximum attempts to wait for desired st...
Wait for the virtual OS to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'up' or 'down', case sensitive Maximum attempts to wait for desired state before giving up Sleep duration between waits Output: Dictionar...
Below is the the instruction that describes the task: ### Input: Wait for the virtual OS to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'up' or 'down', case sensitive Maximum attempts to wait for desired state before giving...
def search(self): """Return list of cells to be removed.""" matches = [] for index, cell in enumerate(self.cells): for pattern in Config.patterns: if ismatch(cell, pattern): matches.append(index) break return matches
Return list of cells to be removed.
Below is the the instruction that describes the task: ### Input: Return list of cells to be removed. ### Response: def search(self): """Return list of cells to be removed.""" matches = [] for index, cell in enumerate(self.cells): for pattern in Config.patterns: ...
def check_slice_perms(self, slice_id): """ Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method. """ form_data, slc = get_form_data(slice_id, use_slice_data=True) datasource_type = slc.datas...
Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method.
Below is the the instruction that describes the task: ### Input: Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method. ### Response: def check_slice_perms(self, slice_id): """ Check if user can acce...
def determine_metadata(self, request, view): """Adds `properties` and `features` to the metadata response.""" metadata = super( DynamicMetadata, self).determine_metadata( request, view) metadata['features'] = getattr(view, 'features', []) i...
Adds `properties` and `features` to the metadata response.
Below is the the instruction that describes the task: ### Input: Adds `properties` and `features` to the metadata response. ### Response: def determine_metadata(self, request, view): """Adds `properties` and `features` to the metadata response.""" metadata = super( DynamicMetadata, ...
def filename_command(): """ Executor for `globus config filename` """ try: config = get_config_obj(file_error=True) except IOError as e: safeprint(e, write_to_stderr=True) click.get_current_context().exit(1) else: safeprint(config.filename)
Executor for `globus config filename`
Below is the the instruction that describes the task: ### Input: Executor for `globus config filename` ### Response: def filename_command(): """ Executor for `globus config filename` """ try: config = get_config_obj(file_error=True) except IOError as e: safeprint(e, write_to_std...
def actor(fn=None, *, actor_class=Actor, actor_name=None, queue_name="default", priority=0, broker=None, **options): """Declare an actor. Examples: >>> import dramatiq >>> @dramatiq.actor ... def add(x, y): ... print(x + y) ... >>> add Actor(<function add at 0x10...
Declare an actor. Examples: >>> import dramatiq >>> @dramatiq.actor ... def add(x, y): ... print(x + y) ... >>> add Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add') >>> add(1, 2) 3 >>> add.send(1, 2) Message( ...
Below is the the instruction that describes the task: ### Input: Declare an actor. Examples: >>> import dramatiq >>> @dramatiq.actor ... def add(x, y): ... print(x + y) ... >>> add Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add') ...
def _list_images(self, root): """ Description : generate list for lip images """ self.labels = [] self.items = [] valid_unseen_sub_idx = [1, 2, 20, 22] skip_sub_idx = [21] if self._mode == 'train': sub_idx = ['s' + str(i) for i in range(1, 35...
Description : generate list for lip images
Below is the the instruction that describes the task: ### Input: Description : generate list for lip images ### Response: def _list_images(self, root): """ Description : generate list for lip images """ self.labels = [] self.items = [] valid_unseen_sub_idx = [1, 2, ...
def joinpath(self, *args): """ Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object. """ return self.__class__(os.path.join(self, *args))
Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object.
Below is the the instruction that describes the task: ### Input: Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object. ### Response: def joinpath(self, *args): """ Join two or more path components, adding a separator character...
def write(self, data): """Write data. Args: data: actual data yielded from handler. Type is writer-specific. """ ctx = context.get() if len(data) != 2: logging.error("Got bad tuple of length %d (2-tuple expected): %s", len(data), data) try: key = str(data[...
Write data. Args: data: actual data yielded from handler. Type is writer-specific.
Below is the the instruction that describes the task: ### Input: Write data. Args: data: actual data yielded from handler. Type is writer-specific. ### Response: def write(self, data): """Write data. Args: data: actual data yielded from handler. Type is writer-specific. """ ctx = ...
def ArchiveProcessedFile(filePath, archiveDir): """ Move file from given file path to archive directory. Note the archive directory is relative to the file path directory. Parameters ---------- filePath : string File path archiveDir : string Name of archive directory """ targetDir = ...
Move file from given file path to archive directory. Note the archive directory is relative to the file path directory. Parameters ---------- filePath : string File path archiveDir : string Name of archive directory
Below is the the instruction that describes the task: ### Input: Move file from given file path to archive directory. Note the archive directory is relative to the file path directory. Parameters ---------- filePath : string File path archiveDir : string Name of archive directory ### Res...
def stop(self): """ Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop. """ super(Multi, self).stop() self.monitor_thread.join() logging.info("Multi-plugin health m...
Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop.
Below is the the instruction that describes the task: ### Input: Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop. ### Response: def stop(self): """ Stop the monitoring thread of the plugin. ...
def val2dzn(val, wrap=True): """Serializes a value into its dzn representation. The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``. Parameters ---------- val The value to serialize wrap : bool Whether to wrap the serialized value. Returns ------- ...
Serializes a value into its dzn representation. The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``. Parameters ---------- val The value to serialize wrap : bool Whether to wrap the serialized value. Returns ------- str The serialized dzn r...
Below is the the instruction that describes the task: ### Input: Serializes a value into its dzn representation. The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``. Parameters ---------- val The value to serialize wrap : bool Whether to wrap the serialized...
def delete_by_field(self, field_name, field_value, **options): """ Deletes first record to match provided ``field_name`` and ``field_value``. >>> record = airtable.delete_by_field('Employee Id', 'DD13332454') Args: field_name (``str``): Name of field to mat...
Deletes first record to match provided ``field_name`` and ``field_value``. >>> record = airtable.delete_by_field('Employee Id', 'DD13332454') Args: field_name (``str``): Name of field to match (column name). field_value (``str``): Value of field to match. ...
Below is the the instruction that describes the task: ### Input: Deletes first record to match provided ``field_name`` and ``field_value``. >>> record = airtable.delete_by_field('Employee Id', 'DD13332454') Args: field_name (``str``): Name of field to match (column name)...
def bbox_str(bbox, pad=4, sep=', '): r""" makes a string from an integer bounding box """ if bbox is None: return 'None' fmtstr = sep.join(['%' + six.text_type(pad) + 'd'] * 4) return '(' + fmtstr % tuple(bbox) + ')'
r""" makes a string from an integer bounding box
Below is the the instruction that describes the task: ### Input: r""" makes a string from an integer bounding box ### Response: def bbox_str(bbox, pad=4, sep=', '): r""" makes a string from an integer bounding box """ if bbox is None: return 'None' fmtstr = sep.join(['%' + six.text_type(pad) + ...
def results_decorator(func): """ Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned. """ # Wrap function to maintian...
Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned.
Below is the the instruction that describes the task: ### Input: Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned. ### Respons...
def paginate_index(self, bucket, index, startkey, endkey=None, max_results=1000, return_terms=None, continuation=None, timeout=None, term_regex=None): """ Iterates over a paginated index query. This is equivalent to calling :meth:`get_index` and then...
Iterates over a paginated index query. This is equivalent to calling :meth:`get_index` and then successively calling :meth:`~riak.client.index_page.IndexPage.next_page` until all results are exhausted. Because limiting the result set is necessary to invoke pagination, the ``max_...
Below is the the instruction that describes the task: ### Input: Iterates over a paginated index query. This is equivalent to calling :meth:`get_index` and then successively calling :meth:`~riak.client.index_page.IndexPage.next_page` until all results are exhausted. Because limiting...
def _create_network_adapters(network_interfaces, parent=None): ''' Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the interfaces to be created for a virtual machine network_interfaces List of network interfaces and properties parent Parent object reference ...
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the interfaces to be created for a virtual machine network_interfaces List of network interfaces and properties parent Parent object reference .. code-block: bash interfaces: adapter: 'Network ad...
Below is the the instruction that describes the task: ### Input: Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the interfaces to be created for a virtual machine network_interfaces List of network interfaces and properties parent Parent object reference .....
def __cqt_filter_fft(sr, fmin, n_bins, bins_per_octave, tuning, filter_scale, norm, sparsity, hop_length=None, window='hann'): '''Generate the frequency domain constant-Q filter basis.''' basis, lengths = filters.constant_q(sr, f...
Generate the frequency domain constant-Q filter basis.
Below is the the instruction that describes the task: ### Input: Generate the frequency domain constant-Q filter basis. ### Response: def __cqt_filter_fft(sr, fmin, n_bins, bins_per_octave, tuning, filter_scale, norm, sparsity, hop_length=None, window='hann'): '''Gener...
def json2space(in_x, name=ROOT): """ Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX. """ out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): ...
Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX.
Below is the the instruction that describes the task: ### Input: Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX. ### Response: def json2space(in_x, name=ROOT): "...
def find_common_beginning(string_list, boundary_char = None): """Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char. ...
Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char.
Below is the the instruction that describes the task: ### Input: Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char. ...
def redirect(location, code=302): """Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a r...
Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since...
Below is the the instruction that describes the task: ### Input: Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the a...
def __extend_with_api_ref(raw_testinfo): """ extend with api reference Raises: exceptions.ApiNotFound: api not found """ api_name = raw_testinfo["api"] # api maybe defined in two types: # 1, individual file: each file is corresponding to one api definition # 2, api sets file: one ...
extend with api reference Raises: exceptions.ApiNotFound: api not found
Below is the the instruction that describes the task: ### Input: extend with api reference Raises: exceptions.ApiNotFound: api not found ### Response: def __extend_with_api_ref(raw_testinfo): """ extend with api reference Raises: exceptions.ApiNotFound: api not found """ api_...
def database_remove_types(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/removeTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes """ return DXHTTPRequest('/%s/removeTypes...
Invokes the /database-xxxx/removeTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes
Below is the the instruction that describes the task: ### Input: Invokes the /database-xxxx/removeTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes ### Response: def database_remove_types(object_id, input_params={}, always_...
def vsearch_dereplicate_exact_seqs( fasta_filepath, output_filepath, output_uc=False, working_dir=None, strand="both", maxuniquesize=None, minuniquesize=None, sizein=False, sizeout=True, log_name="derep.log", HALT_EXEC=False): """ Generates clusters and fasta file of ...
Generates clusters and fasta file of dereplicated subsequences Parameters ---------- fasta_filepath : string input filepath of fasta file to be dereplicated output_filepath : string write the dereplicated sequences to output_filepath working_dir : ...
Below is the the instruction that describes the task: ### Input: Generates clusters and fasta file of dereplicated subsequences Parameters ---------- fasta_filepath : string input filepath of fasta file to be dereplicated output_filepath : string write...
def hardware_connector_sfp_breakout(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") connector = ET.SubElement(hardware, "connector") name_key = ET.SubElem...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def hardware_connector_sfp_breakout(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:b...
def enqueue_command(self, command_name, args, options): """Enqueue a new command into this pipeline.""" assert_open(self) promise = Promise() self.commands.append((command_name, args, options, promise)) return promise
Enqueue a new command into this pipeline.
Below is the the instruction that describes the task: ### Input: Enqueue a new command into this pipeline. ### Response: def enqueue_command(self, command_name, args, options): """Enqueue a new command into this pipeline.""" assert_open(self) promise = Promise() self.commands.append...
def create_package_level_rst_index_file( package_name, max_depth, modules, inner_packages=None): """Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth:...
Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in the package. :type modules: list :return: A text for the co...
Below is the the instruction that describes the task: ### Input: Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in...
def client_args_for_bank(bank_info, ofx_version): """ Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent headers...
Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent headers (or no User-Agent header). :param bank_info: OFXHome ban...
Below is the the instruction that describes the task: ### Input: Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent ...
def get_namespace(fn: Callable, namespace: Optional[str]) -> str: """ Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace ...
Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args: fn: a function namespace: an optional namespace, whi...
Below is the the instruction that describes the task: ### Input: Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args:...
def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() # Clear proxy data self.driver_args['service_args'] = self.default_service_args # Clear headers self.dcap = dict(webdriver...
Kills old session and creates a new one with no proxies or headers
Below is the the instruction that describes the task: ### Input: Kills old session and creates a new one with no proxies or headers ### Response: def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() ...
def search_observations(self, search): """ Search for :class:`meteorpi_model.Observation` entities :param search: an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from the DB :return: a structure of ...
Search for :class:`meteorpi_model.Observation` entities :param search: an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from the DB :return: a structure of {count:int total rows of an unrestricted search, observatio...
Below is the the instruction that describes the task: ### Input: Search for :class:`meteorpi_model.Observation` entities :param search: an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from the DB :return: a str...
def uncancel_confirmation(self, confirmation_id): """ Uncancelles an confirmation :param confirmation_id: the confirmation id """ return self._create_put_request( resource=CONFIRMATIONS, billomat_id=confirmation_id, command=UNCANCEL, )
Uncancelles an confirmation :param confirmation_id: the confirmation id
Below is the the instruction that describes the task: ### Input: Uncancelles an confirmation :param confirmation_id: the confirmation id ### Response: def uncancel_confirmation(self, confirmation_id): """ Uncancelles an confirmation :param confirmation_id: the confirmation id ...
def Descargar(self, url=URL, filename="padron.txt", proxy=None): "Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado" proxies = {} if proxy: proxies['http'] = proxy proxies['https'] = proxy proxy_handler = urllib2.ProxyHandler(proxies) ...
Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado
Below is the the instruction that describes the task: ### Input: Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado ### Response: def Descargar(self, url=URL, filename="padron.txt", proxy=None): "Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado" proxies = {} ...
def unregister_service(self, registration): # type: (ServiceRegistration) -> bool """ Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference """ # Get the Service Reference ...
Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference
Below is the the instruction that describes the task: ### Input: Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference ### Response: def unregister_service(self, registration): # type: (ServiceRegistr...
def handle_args(args): """ Handle command line arguments Raises: Exception if the config path wasn't explicitly state and dead reckoning based on script location fails """ parser = argparse.ArgumentParser() parser.add_argument("configpath", default=None, nargs="?", help="/path/to/c...
Handle command line arguments Raises: Exception if the config path wasn't explicitly state and dead reckoning based on script location fails
Below is the the instruction that describes the task: ### Input: Handle command line arguments Raises: Exception if the config path wasn't explicitly state and dead reckoning based on script location fails ### Response: def handle_args(args): """ Handle command line arguments Raises: Exception if t...