code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def Serth_HEDH(D, sigma, Hvap, rhol, rhog): r'''Calculates critical heat flux for nucleic boiling of a tube bundle according to [2]_, citing [3]_, and using [1]_ as the original form. .. math:: q_c = KH_{vap} \rho_g^{0.5}\left[\sigma g (\rho_L-\rho_g)\right]^{0.25} K = 0.123 (R^*)^{-0.25} ...
r'''Calculates critical heat flux for nucleic boiling of a tube bundle according to [2]_, citing [3]_, and using [1]_ as the original form. .. math:: q_c = KH_{vap} \rho_g^{0.5}\left[\sigma g (\rho_L-\rho_g)\right]^{0.25} K = 0.123 (R^*)^{-0.25} \text{ for 0.12 < R* < 1.17} K = 0.118 ...
Below is the the instruction that describes the task: ### Input: r'''Calculates critical heat flux for nucleic boiling of a tube bundle according to [2]_, citing [3]_, and using [1]_ as the original form. .. math:: q_c = KH_{vap} \rho_g^{0.5}\left[\sigma g (\rho_L-\rho_g)\right]^{0.25} K =...
def delete(self, pk=None, fail_on_missing=False, **kwargs): """Remove the given notification template. Note here configuration-related fields like 'notification_configuration' and 'channels' will not be used even provided. If `fail_on_missing` is True, then the object's not bei...
Remove the given notification template. Note here configuration-related fields like 'notification_configuration' and 'channels' will not be used even provided. If `fail_on_missing` is True, then the object's not being found is considered a failure; otherwise, a success with no ...
Below is the the instruction that describes the task: ### Input: Remove the given notification template. Note here configuration-related fields like 'notification_configuration' and 'channels' will not be used even provided. If `fail_on_missing` is True, then the object's not being...
def get_subdomain_ops_at_txid(txid, proxy=None, hostport=None): """ Get the list of subdomain operations added by a txid Returns the list of operations ([{...}]) on success Returns {'error': ...} on failure """ assert proxy or hostport, 'Need proxy or hostport' if proxy is None: prox...
Get the list of subdomain operations added by a txid Returns the list of operations ([{...}]) on success Returns {'error': ...} on failure
Below is the the instruction that describes the task: ### Input: Get the list of subdomain operations added by a txid Returns the list of operations ([{...}]) on success Returns {'error': ...} on failure ### Response: def get_subdomain_ops_at_txid(txid, proxy=None, hostport=None): """ Get the list ...
def remove_handler(self, handler): """ Removes a previously added event handler. """ while handler in self.handlers: self.handlers.remove(handler)
Removes a previously added event handler.
Below is the the instruction that describes the task: ### Input: Removes a previously added event handler. ### Response: def remove_handler(self, handler): """ Removes a previously added event handler. """ while handler in self.handlers: self.handlers.remove(handler)
def drop_duplicates(self, keep="first", inplace=False, **kwargs): """Return DataFrame with duplicate rows removed, optionally only considering certain columns Args: subset : column label or sequence of labels, optional Only consider certain columns for ident...
Return DataFrame with duplicate rows removed, optionally only considering certain columns Args: subset : column label or sequence of labels, optional Only consider certain columns for identifying duplicates, by default use all of the columns ...
Below is the the instruction that describes the task: ### Input: Return DataFrame with duplicate rows removed, optionally only considering certain columns Args: subset : column label or sequence of labels, optional Only consider certain columns for identifying du...
def traverseShowClassIdTextContentDescriptionAndScreenshot(view): ''' Shows the View class, id, text if available and unique id and takes the screenshot. This function can be used as a transform function to L{ViewClient.traverse()} @type view: I{View} @param view: the View ...
Shows the View class, id, text if available and unique id and takes the screenshot. This function can be used as a transform function to L{ViewClient.traverse()} @type view: I{View} @param view: the View @return: the string containing class, id, and text if available and the content des...
Below is the the instruction that describes the task: ### Input: Shows the View class, id, text if available and unique id and takes the screenshot. This function can be used as a transform function to L{ViewClient.traverse()} @type view: I{View} @param view: the View @return: the s...
def _align_method_FRAME(left, right, axis): """ convert rhs to meet lhs dims if input is list, tuple or np.ndarray """ def to_series(right): msg = ('Unable to coerce to Series, length must be {req_len}: ' 'given {given_len}') if axis is not None and left._get_axis_name(axis) == '...
convert rhs to meet lhs dims if input is list, tuple or np.ndarray
Below is the the instruction that describes the task: ### Input: convert rhs to meet lhs dims if input is list, tuple or np.ndarray ### Response: def _align_method_FRAME(left, right, axis): """ convert rhs to meet lhs dims if input is list, tuple or np.ndarray """ def to_series(right): msg = ('Una...
def Zg(self): r'''Compressibility factor of the chemical in the gas phase at the current temperature and pressure, [dimensionless]. Utilizes the object oriented interface and :obj:`thermo.volume.VolumeGas` to perform the actual calculation of molar volume. Examples ...
r'''Compressibility factor of the chemical in the gas phase at the current temperature and pressure, [dimensionless]. Utilizes the object oriented interface and :obj:`thermo.volume.VolumeGas` to perform the actual calculation of molar volume. Examples -------- >...
Below is the the instruction that describes the task: ### Input: r'''Compressibility factor of the chemical in the gas phase at the current temperature and pressure, [dimensionless]. Utilizes the object oriented interface and :obj:`thermo.volume.VolumeGas` to perform the actual calculation ...
def do_time(self, params): """ \x1b[1mNAME\x1b[0m time - Measures elapsed seconds after running commands \x1b[1mSYNOPSIS\x1b[0m time <cmd1> <cmd2> ... <cmdN> \x1b[1mEXAMPLES\x1b[0m > time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"' Took 0.05585 seconds ...
\x1b[1mNAME\x1b[0m time - Measures elapsed seconds after running commands \x1b[1mSYNOPSIS\x1b[0m time <cmd1> <cmd2> ... <cmdN> \x1b[1mEXAMPLES\x1b[0m > time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"' Took 0.05585 seconds
Below is the the instruction that describes the task: ### Input: \x1b[1mNAME\x1b[0m time - Measures elapsed seconds after running commands \x1b[1mSYNOPSIS\x1b[0m time <cmd1> <cmd2> ... <cmdN> \x1b[1mEXAMPLES\x1b[0m > time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"' ...
def encrypt(self, data, unique_identifier=None, cryptographic_parameters=None, iv_counter_nonce=None, credential=None): """ Encrypt data using the specified encryption key and parameters. Args: data (byt...
Encrypt data using the specified encryption key and parameters. Args: data (bytes): The bytes to encrypt. Required. unique_identifier (string): The unique ID of the encryption key to use. Optional, defaults to None. cryptographic_parameters (CryptographicPara...
Below is the the instruction that describes the task: ### Input: Encrypt data using the specified encryption key and parameters. Args: data (bytes): The bytes to encrypt. Required. unique_identifier (string): The unique ID of the encryption key to use. Optional, defa...
def path(self, p): """ Inserts a path to the context. This path is striped by the base_url, so for example: A path BASE_URL/ENDPOINT_URL, would be inserted as only ENDPOINT_URL https://localhost:8092/sso/redirect -> sso/redirect :type p: str :param p: A ...
Inserts a path to the context. This path is striped by the base_url, so for example: A path BASE_URL/ENDPOINT_URL, would be inserted as only ENDPOINT_URL https://localhost:8092/sso/redirect -> sso/redirect :type p: str :param p: A path to an endpoint. :return: N...
Below is the the instruction that describes the task: ### Input: Inserts a path to the context. This path is striped by the base_url, so for example: A path BASE_URL/ENDPOINT_URL, would be inserted as only ENDPOINT_URL https://localhost:8092/sso/redirect -> sso/redirect :typ...
def match_url(self, request): """ Match the request against a file in the adapter directory :param request: The request :type request: :class:`requests.Request` :return: Path to the file :rtype: ``str`` """ parsed_url = urlparse(request.path_url) ...
Match the request against a file in the adapter directory :param request: The request :type request: :class:`requests.Request` :return: Path to the file :rtype: ``str``
Below is the the instruction that describes the task: ### Input: Match the request against a file in the adapter directory :param request: The request :type request: :class:`requests.Request` :return: Path to the file :rtype: ``str`` ### Response: def match_url(self, request): ...
def add_argument(self, dest, nargs=1, obj=None): """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest self._args.append(Argume...
Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser.
Below is the the instruction that describes the task: ### Input: Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. ### Response: def add_argument(self, dest, nargs=1, obj=None): """Adds a ...
def check(self) -> z3.CheckSatResult: """Returns z3 smt check result. Also suppresses the stdout when running z3 library's check() to avoid unnecessary output :return: The evaluated result which is either of sat, unsat or unknown """ old_stdout = sys.stdout sys.stdout = o...
Returns z3 smt check result. Also suppresses the stdout when running z3 library's check() to avoid unnecessary output :return: The evaluated result which is either of sat, unsat or unknown
Below is the the instruction that describes the task: ### Input: Returns z3 smt check result. Also suppresses the stdout when running z3 library's check() to avoid unnecessary output :return: The evaluated result which is either of sat, unsat or unknown ### Response: def check(self) -> z3.CheckSatR...
def ismount(self, path): """Return true if the given path is a mount point. Args: path: Path to filesystem object to be checked Returns: `True` if path is a mount point added to the fake file system. Under Windows also returns True for drive and UNC roots ...
Return true if the given path is a mount point. Args: path: Path to filesystem object to be checked Returns: `True` if path is a mount point added to the fake file system. Under Windows also returns True for drive and UNC roots (independent of their exis...
Below is the the instruction that describes the task: ### Input: Return true if the given path is a mount point. Args: path: Path to filesystem object to be checked Returns: `True` if path is a mount point added to the fake file system. Under Windows also return...
def _covert_to_hashable(data): r""" Args: data (?): Returns: ?: CommandLine: python -m utool.util_hash _covert_to_hashable Example: >>> # DISABLE_DOCTEST >>> from utool.util_hash import * # NOQA >>> from utool.util_hash import _covert_to_hashable ...
r""" Args: data (?): Returns: ?: CommandLine: python -m utool.util_hash _covert_to_hashable Example: >>> # DISABLE_DOCTEST >>> from utool.util_hash import * # NOQA >>> from utool.util_hash import _covert_to_hashable # NOQA >>> import utool as ...
Below is the the instruction that describes the task: ### Input: r""" Args: data (?): Returns: ?: CommandLine: python -m utool.util_hash _covert_to_hashable Example: >>> # DISABLE_DOCTEST >>> from utool.util_hash import * # NOQA >>> from utool.util...
def findViewsWithAttribute(self, attr, val, root="ROOT"): ''' Finds the Views with the specified attribute and value. This allows you to see all items that match your criteria in the view hierarchy Usage: buttons = v.findViewsWithAttribute("class", "android.widget.Button") ...
Finds the Views with the specified attribute and value. This allows you to see all items that match your criteria in the view hierarchy Usage: buttons = v.findViewsWithAttribute("class", "android.widget.Button")
Below is the the instruction that describes the task: ### Input: Finds the Views with the specified attribute and value. This allows you to see all items that match your criteria in the view hierarchy Usage: buttons = v.findViewsWithAttribute("class", "android.widget.Button") ### Response...
def _ops_bool_to_prog(ops_bool: Tuple[bool], qubits: List[int]) -> Program: """ :param ops_bool: tuple of booleans specifying the operation to be carried out on `qubits` :param qubits: list specifying the qubits to be carried operations on :return: Program with the operations specified in `ops_bool` on ...
:param ops_bool: tuple of booleans specifying the operation to be carried out on `qubits` :param qubits: list specifying the qubits to be carried operations on :return: Program with the operations specified in `ops_bool` on the qubits specified in `qubits`
Below is the the instruction that describes the task: ### Input: :param ops_bool: tuple of booleans specifying the operation to be carried out on `qubits` :param qubits: list specifying the qubits to be carried operations on :return: Program with the operations specified in `ops_bool` on the qubits specifie...
def get_sos_step_steps(stmt): ''' Extract sos_step(x) from statement ''' opt_values = get_param_of_function( 'sos_step', stmt, extra_dict=env.sos_dict.dict()) for value in opt_values: if len(value) != 1: raise ValueError('sos_step only accept one and only one parameter') ...
Extract sos_step(x) from statement
Below is the the instruction that describes the task: ### Input: Extract sos_step(x) from statement ### Response: def get_sos_step_steps(stmt): ''' Extract sos_step(x) from statement ''' opt_values = get_param_of_function( 'sos_step', stmt, extra_dict=env.sos_dict.dict()) for value in o...
def add_join_conditions(self, conditions: Dict[str, Any]) -> None: """Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query...
Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query doesn't already generate the initial join in the first place.
Below is the the instruction that describes the task: ### Input: Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query doesn't ...
def set_membind(nodemask): """ Sets the memory allocation mask. The thread will only allocate memory from the nodes set in nodemask. @param nodemask: node mask @type nodemask: C{set} """ mask = set_to_numa_nodemask(nodemask) tmp = bitmask_t() tmp.maskp = cast(byref(mask), POINTER(...
Sets the memory allocation mask. The thread will only allocate memory from the nodes set in nodemask. @param nodemask: node mask @type nodemask: C{set}
Below is the the instruction that describes the task: ### Input: Sets the memory allocation mask. The thread will only allocate memory from the nodes set in nodemask. @param nodemask: node mask @type nodemask: C{set} ### Response: def set_membind(nodemask): """ Sets the memory allocation mask...
def norm_attr(self): """ Normalize attr state """ if not self.HAS_ATTR: return self.HAS_ATTR = False self.emit('call', 'COPY_ATTR', 0) backend.REQUIRES.add('copy_attr.asm')
Normalize attr state
Below is the the instruction that describes the task: ### Input: Normalize attr state ### Response: def norm_attr(self): """ Normalize attr state """ if not self.HAS_ATTR: return self.HAS_ATTR = False self.emit('call', 'COPY_ATTR', 0) backend.REQUIRES.ad...
def get_candidate_votes(self, candidate): """ Get all votes attached to a CandidateElection for a Candidate in this election. """ candidate_election = CandidateElection.objects.get( candidate=candidate, election=self ) return candidate_election.votes....
Get all votes attached to a CandidateElection for a Candidate in this election.
Below is the the instruction that describes the task: ### Input: Get all votes attached to a CandidateElection for a Candidate in this election. ### Response: def get_candidate_votes(self, candidate): """ Get all votes attached to a CandidateElection for a Candidate in this election...
def update(self, pbar): 'Updates the widget to show the ETA or total time when finished.' self.n_refresh += 1 if pbar.currval == 0: return 'ETA: --:--:--' elif pbar.finished: return 'Time: %s' % self.format_time(pbar.seconds_elapsed) else: ela...
Updates the widget to show the ETA or total time when finished.
Below is the the instruction that describes the task: ### Input: Updates the widget to show the ETA or total time when finished. ### Response: def update(self, pbar): 'Updates the widget to show the ETA or total time when finished.' self.n_refresh += 1 if pbar.currval == 0: retu...
def MergeMessage( self, source, destination, replace_message, replace_repeated): """Merge all fields specified by this tree from source to destination.""" _MergeMessage( self._root, source, destination, replace_message, replace_repeated)
Merge all fields specified by this tree from source to destination.
Below is the the instruction that describes the task: ### Input: Merge all fields specified by this tree from source to destination. ### Response: def MergeMessage( self, source, destination, replace_message, replace_repeated): """Merge all fields specified by this tree from source to destination."...
def suspend(self): """ Suspends execution on all threads of the process. @raise WindowsError: On error an exception is raised. """ self.scan_threads() # force refresh the snapshot suspended = list() try: for aThread in self.iter_threads(): ...
Suspends execution on all threads of the process. @raise WindowsError: On error an exception is raised.
Below is the the instruction that describes the task: ### Input: Suspends execution on all threads of the process. @raise WindowsError: On error an exception is raised. ### Response: def suspend(self): """ Suspends execution on all threads of the process. @raise WindowsError: On e...
def sieve(self, name=None, sample_rate=None, sample_range=None, exact_match=False, **others): """Find all `Channels <Channel>` in this list matching the specified criteria. Parameters ---------- name : `str`, or regular expression any part of the channe...
Find all `Channels <Channel>` in this list matching the specified criteria. Parameters ---------- name : `str`, or regular expression any part of the channel name against which to match (or full name if `exact_match=False` is given) sample_rate : `float` ...
Below is the the instruction that describes the task: ### Input: Find all `Channels <Channel>` in this list matching the specified criteria. Parameters ---------- name : `str`, or regular expression any part of the channel name against which to match (or full...
def registration_error(self, stanza): """Handle in-band registration error. [client only] :Parameters: - `stanza`: the error stanza received or `None` on timeout. :Types: - `stanza`: `pyxmpp.stanza.Stanza`""" self.lock.acquire() try: ...
Handle in-band registration error. [client only] :Parameters: - `stanza`: the error stanza received or `None` on timeout. :Types: - `stanza`: `pyxmpp.stanza.Stanza`
Below is the the instruction that describes the task: ### Input: Handle in-band registration error. [client only] :Parameters: - `stanza`: the error stanza received or `None` on timeout. :Types: - `stanza`: `pyxmpp.stanza.Stanza` ### Response: def registration_erro...
def validate_flavor_data(self, expected, actual): """Validate flavor data. Validate a list of actual flavors vs a list of expected flavors. """ self.log.debug('Validating flavor data...') self.log.debug('actual: {}'.format(repr(actual))) act = [a.name for a in actu...
Validate flavor data. Validate a list of actual flavors vs a list of expected flavors.
Below is the the instruction that describes the task: ### Input: Validate flavor data. Validate a list of actual flavors vs a list of expected flavors. ### Response: def validate_flavor_data(self, expected, actual): """Validate flavor data. Validate a list of actual flavors vs a lis...
def _update_alignment(self, alignment): """Updates vertical text alignment button Parameters ---------- alignment: String in ["top", "middle", "right"] \tSwitches button to untoggled if False and toggled if True """ states = {"top": 2, "middle": 0, "bottom": 1...
Updates vertical text alignment button Parameters ---------- alignment: String in ["top", "middle", "right"] \tSwitches button to untoggled if False and toggled if True
Below is the the instruction that describes the task: ### Input: Updates vertical text alignment button Parameters ---------- alignment: String in ["top", "middle", "right"] \tSwitches button to untoggled if False and toggled if True ### Response: def _update_alignment(self, align...
def control_valve_noise_g_2011(m, P1, P2, T1, rho, gamma, MW, Kv, d, Di, t_pipe, Fd, FL, FLP=None, FP=None, rho_pipe=7800.0, c_pipe=5000.0, P_air=101325.0, rho_air=1.2, c_air=343.0, An=-3.8, St...
r'''Calculates the sound made by a gas flowing through a control valve according to the standard IEC 60534-8-3 (2011) [1]_. Parameters ---------- m : float Mass flow rate of gas through the control valve, [kg/s] P1 : float Inlet pressure of the gas before valves and reducers [Pa] ...
Below is the the instruction that describes the task: ### Input: r'''Calculates the sound made by a gas flowing through a control valve according to the standard IEC 60534-8-3 (2011) [1]_. Parameters ---------- m : float Mass flow rate of gas through the control valve, [kg/s] P1 : float...
def update_group_states_for_vifs(self, vifs, ack): """Updates security groups by setting the ack field""" vif_keys = [self.vif_key(vif.device_id, vif.mac_address) for vif in vifs] self.set_fields(vif_keys, SECURITY_GROUP_ACK, ack)
Updates security groups by setting the ack field
Below is the the instruction that describes the task: ### Input: Updates security groups by setting the ack field ### Response: def update_group_states_for_vifs(self, vifs, ack): """Updates security groups by setting the ack field""" vif_keys = [self.vif_key(vif.device_id, vif.mac_address) ...
def set_suggested_sort(self, sort='blank'): """Set 'Suggested Sort' for the comments of the submission. Comments can be sorted in one of (confidence, top, new, hot, controversial, old, random, qa, blank). :returns: The json response from the server. """ url = self.redd...
Set 'Suggested Sort' for the comments of the submission. Comments can be sorted in one of (confidence, top, new, hot, controversial, old, random, qa, blank). :returns: The json response from the server.
Below is the the instruction that describes the task: ### Input: Set 'Suggested Sort' for the comments of the submission. Comments can be sorted in one of (confidence, top, new, hot, controversial, old, random, qa, blank). :returns: The json response from the server. ### Response: def set...
def bindings(self, queue, virtual_host='/'): """Get Queue bindings. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. ...
Get Queue bindings. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
Below is the the instruction that describes the task: ### Input: Get Queue bindings. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connect...
def dump_public_key(public_key, encoding='pem'): """ Serializes a public key object into a byte string :param public_key: An oscrypto.asymmetric.PublicKey or asn1crypto.keys.PublicKeyInfo object :param encoding: A unicode string of "pem" or "der" :return: A byte string of ...
Serializes a public key object into a byte string :param public_key: An oscrypto.asymmetric.PublicKey or asn1crypto.keys.PublicKeyInfo object :param encoding: A unicode string of "pem" or "der" :return: A byte string of the encoded public key
Below is the the instruction that describes the task: ### Input: Serializes a public key object into a byte string :param public_key: An oscrypto.asymmetric.PublicKey or asn1crypto.keys.PublicKeyInfo object :param encoding: A unicode string of "pem" or "der" :return: A byte st...
def retry_when_service_down(func): """ Decorator that will retry a function while it fails with status code 503 Assumes the first argument to the fuction will be an object with a set_status_message method. :param func: function: will be called until it doesn't fail with DataServiceError status 503 :...
Decorator that will retry a function while it fails with status code 503 Assumes the first argument to the fuction will be an object with a set_status_message method. :param func: function: will be called until it doesn't fail with DataServiceError status 503 :return: value returned by func
Below is the the instruction that describes the task: ### Input: Decorator that will retry a function while it fails with status code 503 Assumes the first argument to the fuction will be an object with a set_status_message method. :param func: function: will be called until it doesn't fail with DataService...
def split_input(cls, mapper_spec, _reader=blobstore.BlobReader): """Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Must contain 'blob_keys' parameter with one or more blob keys. _reader: a callable that returns a file-like objec...
Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Must contain 'blob_keys' parameter with one or more blob keys. _reader: a callable that returns a file-like object for reading blobs. Used for dependency injection. Retur...
Below is the the instruction that describes the task: ### Input: Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Must contain 'blob_keys' parameter with one or more blob keys. _reader: a callable that returns a file-like object f...
def deleteAttachment(self, oid, attachment_id): """ removes an attachment from a feature service feature Input: oid - integer or string - id of feature attachment_id - integer - id of attachment to erase Output: JSON response """ ...
removes an attachment from a feature service feature Input: oid - integer or string - id of feature attachment_id - integer - id of attachment to erase Output: JSON response
Below is the the instruction that describes the task: ### Input: removes an attachment from a feature service feature Input: oid - integer or string - id of feature attachment_id - integer - id of attachment to erase Output: JSON response ### Respon...
def sample( self, iter, burn=0, thin=1, tune_interval=1000, tune_throughout=True, save_interval=None, burn_till_tuned=False, stop_tuning_after=5, verbose=0, progress_bar=True): """ sample(iter, burn, thin, tune_interval, tune_throughout, save_interval, verbose, progress_bar) ...
sample(iter, burn, thin, tune_interval, tune_throughout, save_interval, verbose, progress_bar) Initialize traces, run sampling loop, clean up afterward. Calls _loop. :Parameters: - iter : int Total number of iterations to do - burn : int Variables will not b...
Below is the the instruction that describes the task: ### Input: sample(iter, burn, thin, tune_interval, tune_throughout, save_interval, verbose, progress_bar) Initialize traces, run sampling loop, clean up afterward. Calls _loop. :Parameters: - iter : int Total number of ite...
def compile(self, source_code, post_treatment=''.join): """Compile given source code. Return object code, modified by given post treatment. """ # read structure structure = self._structure(source_code) values = self._struct_to_values(structure, source_code) # c...
Compile given source code. Return object code, modified by given post treatment.
Below is the the instruction that describes the task: ### Input: Compile given source code. Return object code, modified by given post treatment. ### Response: def compile(self, source_code, post_treatment=''.join): """Compile given source code. Return object code, modified by given post tr...
def to_lines(s): """ Like `str.splitlines()`, except that an empty string results in a one-element list and a trailing newline results in a trailing empty string (and all without re-implementing Python's changing line-splitting algorithm). >>> to_lines('') [''] >>> to_lines('\\n') [...
Like `str.splitlines()`, except that an empty string results in a one-element list and a trailing newline results in a trailing empty string (and all without re-implementing Python's changing line-splitting algorithm). >>> to_lines('') [''] >>> to_lines('\\n') ['', ''] >>> to_lines('foo...
Below is the the instruction that describes the task: ### Input: Like `str.splitlines()`, except that an empty string results in a one-element list and a trailing newline results in a trailing empty string (and all without re-implementing Python's changing line-splitting algorithm). >>> to_lines(''...
def validate_catalog(catalog, only_errors=False, fmt="dict", export_path=None, validator=None): """Analiza un data.json registrando los errores que encuentra. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la ...
Analiza un data.json registrando los errores que encuentra. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: catalog (str o dict): Catálogo (dict, JSON o XLSX) a ser validado. ...
Below is the the instruction that describes the task: ### Input: Analiza un data.json registrando los errores que encuentra. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: ...
def stop(self): """Stop the daemon.""" if self.pidfile is None: raise DaemonError('Cannot stop daemon without PID file') pid = self._read_pidfile() if pid is None: # I don't think this should be a fatal error self._emit_warning('{prog} is not running'...
Stop the daemon.
Below is the the instruction that describes the task: ### Input: Stop the daemon. ### Response: def stop(self): """Stop the daemon.""" if self.pidfile is None: raise DaemonError('Cannot stop daemon without PID file') pid = self._read_pidfile() if pid is None: ...
def get_instances(self): """ Returns a flat list of the names of services created in this space. """ services = [] for resource in self._get_instances(): services.append(resource['entity']['name']) return services
Returns a flat list of the names of services created in this space.
Below is the the instruction that describes the task: ### Input: Returns a flat list of the names of services created in this space. ### Response: def get_instances(self): """ Returns a flat list of the names of services created in this space. """ services = [] ...
def clear(self): """Resets the object at its initial (empty) state.""" self._deque.clear() self._total_length = 0 self._has_view = False
Resets the object at its initial (empty) state.
Below is the the instruction that describes the task: ### Input: Resets the object at its initial (empty) state. ### Response: def clear(self): """Resets the object at its initial (empty) state.""" self._deque.clear() self._total_length = 0 self._has_view = False
def table(schema, arg): """A table argument. Parameters ---------- schema : Union[sch.Schema, List[Tuple[str, dt.DataType]] A validator for the table's columns. Only column subset validators are currently supported. Accepts any arguments that `sch.schema` accepts. See the exampl...
A table argument. Parameters ---------- schema : Union[sch.Schema, List[Tuple[str, dt.DataType]] A validator for the table's columns. Only column subset validators are currently supported. Accepts any arguments that `sch.schema` accepts. See the example for usage. arg : The vali...
Below is the the instruction that describes the task: ### Input: A table argument. Parameters ---------- schema : Union[sch.Schema, List[Tuple[str, dt.DataType]] A validator for the table's columns. Only column subset validators are currently supported. Accepts any arguments that `sch.s...
def mode_new_collection(): """ Create a new collection of items with common attributes. """ print globals()['mode_new_collection'].__doc__ collection_name = raw_input("Collection name: ") item_attr_list = [] collection_node_id = None if collection_name: collection_node_id = inse...
Create a new collection of items with common attributes.
Below is the the instruction that describes the task: ### Input: Create a new collection of items with common attributes. ### Response: def mode_new_collection(): """ Create a new collection of items with common attributes. """ print globals()['mode_new_collection'].__doc__ collection_name = r...
def download_object(self, container, obj, directory, structure=True): """ Fetches the object from storage, and writes it to the specified directory. The directory must exist before calling this method. If the object name represents a nested folder structure, such as "foo/bar/baz...
Fetches the object from storage, and writes it to the specified directory. The directory must exist before calling this method. If the object name represents a nested folder structure, such as "foo/bar/baz.txt", that folder structure will be created in the target directory by default. I...
Below is the the instruction that describes the task: ### Input: Fetches the object from storage, and writes it to the specified directory. The directory must exist before calling this method. If the object name represents a nested folder structure, such as "foo/bar/baz.txt", that folder st...
def output_sector_netcdf(self,netcdf_path,out_path,patch_radius,config): """ Segment patches of forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: netcdf_path (str): Path to the full CONUS netcdf patch file. ...
Segment patches of forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: netcdf_path (str): Path to the full CONUS netcdf patch file. out_path (str): Path to output new segmented netcdf files. patch_radius (int):...
Below is the the instruction that describes the task: ### Input: Segment patches of forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: netcdf_path (str): Path to the full CONUS netcdf patch file. out_path (str): Path ...
def _crossover(chromosomes): """! @brief Crossover procedure. """ # Get pairs to Crossover pairs_to_crossover = np.array(range(len(chromosomes))) # Set random pairs np.random.shuffle(pairs_to_crossover) # Index offset ( pairs_to_crossover split...
! @brief Crossover procedure.
Below is the the instruction that describes the task: ### Input: ! @brief Crossover procedure. ### Response: def _crossover(chromosomes): """! @brief Crossover procedure. """ # Get pairs to Crossover pairs_to_crossover = np.array(range(len(chromosomes))) ...
def zipdir(src_path, target_path, wrapdir=''): """ Zips the pat :param path: the path to the directory :param ziph: the zipfile handle :param wrapdir: wrap all contents in an additional dir :return: """ zipf = zipfile.ZipFile(target_path, 'w', zipfile.ZIP_DEFLATED) for root, dirs, ...
Zips the pat :param path: the path to the directory :param ziph: the zipfile handle :param wrapdir: wrap all contents in an additional dir :return:
Below is the the instruction that describes the task: ### Input: Zips the pat :param path: the path to the directory :param ziph: the zipfile handle :param wrapdir: wrap all contents in an additional dir :return: ### Response: def zipdir(src_path, target_path, wrapdir=''): """ Zips the pat ...
def _advapi32_decrypt(private_key, ciphertext, rsa_oaep_padding=False): """ Encrypts a value using an RSA private key via CryptoAPI :param private_key: A PrivateKey instance to decrypt with :param ciphertext: A byte string of the data to decrypt :param rsa_oaep_padding: If...
Encrypts a value using an RSA private key via CryptoAPI :param private_key: A PrivateKey instance to decrypt with :param ciphertext: A byte string of the data to decrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError...
Below is the the instruction that describes the task: ### Input: Encrypts a value using an RSA private key via CryptoAPI :param private_key: A PrivateKey instance to decrypt with :param ciphertext: A byte string of the data to decrypt :param rsa_oaep_padding: If OAEP padding s...
def exit(self): """Quits this octave session and cleans up. """ if self._engine: self._engine.repl.terminate() self._engine = None
Quits this octave session and cleans up.
Below is the the instruction that describes the task: ### Input: Quits this octave session and cleans up. ### Response: def exit(self): """Quits this octave session and cleans up. """ if self._engine: self._engine.repl.terminate() self._engine = None
def XYZ_to_lbd(X,Y,Z,degree=False): """ NAME: XYZ_to_lbd PURPOSE: transform from rectangular Galactic coordinates to spherical Galactic coordinates (works with vector inputs) INPUT: X - component towards the Galactic Center (in kpc; though this obviously does not matter)) ...
NAME: XYZ_to_lbd PURPOSE: transform from rectangular Galactic coordinates to spherical Galactic coordinates (works with vector inputs) INPUT: X - component towards the Galactic Center (in kpc; though this obviously does not matter)) Y - component in the direction of Galactic ro...
Below is the the instruction that describes the task: ### Input: NAME: XYZ_to_lbd PURPOSE: transform from rectangular Galactic coordinates to spherical Galactic coordinates (works with vector inputs) INPUT: X - component towards the Galactic Center (in kpc; though this obviously do...
def all_group_experiments(self): """ Similar to group_experiments, but uses the default manager to return archived experiments as well. """ from db.models.experiments import Experiment if self.is_selection: return Experiment.all.filter(selections=self) ...
Similar to group_experiments, but uses the default manager to return archived experiments as well.
Below is the the instruction that describes the task: ### Input: Similar to group_experiments, but uses the default manager to return archived experiments as well. ### Response: def all_group_experiments(self): """ Similar to group_experiments, but uses the default manager to return...
def mlstreporter(self): """ Parse the results into a report""" logging.info('Writing reports') # Initialise variables header_row = str() combinedrow = str() combined_header_row = str() reportdirset = set() mlst_dict = dict() # Populate a set of all...
Parse the results into a report
Below is the the instruction that describes the task: ### Input: Parse the results into a report ### Response: def mlstreporter(self): """ Parse the results into a report""" logging.info('Writing reports') # Initialise variables header_row = str() combinedrow = str() ...
def find_executable(name, names=None, required=True): """Utility function to find an executable in PATH name: program to find. Use given value if absolute path names: list of additional names. For instance >>> find_executable('sed', names=['gsed']) required: If True, then the function raises a...
Utility function to find an executable in PATH name: program to find. Use given value if absolute path names: list of additional names. For instance >>> find_executable('sed', names=['gsed']) required: If True, then the function raises an Exception if the program is not found else the function...
Below is the the instruction that describes the task: ### Input: Utility function to find an executable in PATH name: program to find. Use given value if absolute path names: list of additional names. For instance >>> find_executable('sed', names=['gsed']) required: If True, then the function ...
def add_web_servers(self, listen_addrs, debug=False, **ssl_args): """Add WebSocketServer for each (host, port) in listen_addrs.""" self.servers.extend( self.get_web_server(listen_addr, debug=debug, **ssl_args) for listen_addr in listen_addrs )
Add WebSocketServer for each (host, port) in listen_addrs.
Below is the the instruction that describes the task: ### Input: Add WebSocketServer for each (host, port) in listen_addrs. ### Response: def add_web_servers(self, listen_addrs, debug=False, **ssl_args): """Add WebSocketServer for each (host, port) in listen_addrs.""" self.servers.extend( ...
def qos_map_dscp_mutation_dscp_mutation_map_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") dscp_mutation = ET.SubElement(map, "dscp...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def qos_map_dscp_mutation_dscp_mutation_map_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgm...
def demux_adaptor(stream_id, data): """ Utility to demultiplex stdout and stderr when reading frames from the socket. """ if stream_id == STDOUT: return (data, None) elif stream_id == STDERR: return (None, data) else: raise ValueError('{0} is not a valid stream'.forma...
Utility to demultiplex stdout and stderr when reading frames from the socket.
Below is the the instruction that describes the task: ### Input: Utility to demultiplex stdout and stderr when reading frames from the socket. ### Response: def demux_adaptor(stream_id, data): """ Utility to demultiplex stdout and stderr when reading frames from the socket. """ if stream_id...
def vcf_writer(parser, keep, extract, args): """Writes the data in VCF format.""" # The output output = sys.stdout if args.output == "-" else open(args.output, "w") try: # Getting the samples samples = np.array(parser.get_samples(), dtype=str) k = _get_sample_select(samples=samp...
Writes the data in VCF format.
Below is the the instruction that describes the task: ### Input: Writes the data in VCF format. ### Response: def vcf_writer(parser, keep, extract, args): """Writes the data in VCF format.""" # The output output = sys.stdout if args.output == "-" else open(args.output, "w") try: # Getting ...
def _change_kind(self, post_uid): ''' To modify the category of the post, and kind. ''' post_data = self.get_post_data() logger.info('admin post update: {0}'.format(post_data)) MPost.update_misc(post_uid, kind=post_data['kcat']) # self.update_category(post_uid)...
To modify the category of the post, and kind.
Below is the the instruction that describes the task: ### Input: To modify the category of the post, and kind. ### Response: def _change_kind(self, post_uid): ''' To modify the category of the post, and kind. ''' post_data = self.get_post_data() logger.info('admin post upd...
def update(self, webhook_method=values.unset, webhook_filters=values.unset, pre_webhook_url=values.unset, post_webhook_url=values.unset, pre_webhook_retry_count=values.unset, post_webhook_retry_count=values.unset, target=values.unset): """ Update the WebhookI...
Update the WebhookInstance :param unicode webhook_method: The HTTP method to be used when sending a webhook request. :param unicode webhook_filters: The list of webhook event triggers that are enabled for this Service. :param unicode pre_webhook_url: The absolute url the pre-event webhook reque...
Below is the the instruction that describes the task: ### Input: Update the WebhookInstance :param unicode webhook_method: The HTTP method to be used when sending a webhook request. :param unicode webhook_filters: The list of webhook event triggers that are enabled for this Service. :param ...
def terminate(self): """Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate() will be called immediately.""" self.close() # Clearing the job queue try: while 1: self._...
Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate() will be called immediately.
Below is the the instruction that describes the task: ### Input: Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate() will be called immediately. ### Response: def terminate(self): """Stops the worker processes imm...
def write_default_config_file(self, output, comments=True): """This method write a sample file, with attributes, descriptions, sample values, required flags, using the configuration object properties. """ if self.use_config_file: # pylint: disable-msg=W0621 ...
This method write a sample file, with attributes, descriptions, sample values, required flags, using the configuration object properties.
Below is the the instruction that describes the task: ### Input: This method write a sample file, with attributes, descriptions, sample values, required flags, using the configuration object properties. ### Response: def write_default_config_file(self, output, comments=True): """This method...
def dict_from_locals(self, name, params: List[Parameter], not_specified_literal=Constants.VALUE_NOT_SET): """ Generate code for a dictionary of locals whose value is not the specified literal. """ code = self.block(f"{name} = {{}}") for p in params: code.add( ...
Generate code for a dictionary of locals whose value is not the specified literal.
Below is the the instruction that describes the task: ### Input: Generate code for a dictionary of locals whose value is not the specified literal. ### Response: def dict_from_locals(self, name, params: List[Parameter], not_specified_literal=Constants.VALUE_NOT_SET): """ Generate code for a diction...
def evaluate(self, reference_event_list, estimated_event_list): """Evaluate file pair (reference and estimated) Parameters ---------- reference_event_list : event list Reference event list estimated_event_list : event list Estimated event list ...
Evaluate file pair (reference and estimated) Parameters ---------- reference_event_list : event list Reference event list estimated_event_list : event list Estimated event list Returns ------- self
Below is the the instruction that describes the task: ### Input: Evaluate file pair (reference and estimated) Parameters ---------- reference_event_list : event list Reference event list estimated_event_list : event list Estimated event list Return...
def main(): ''' Parse argv for options and arguments, and start schema generation. ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path...]", formatter=optparse.TitledHelpFormatter()) parser....
Parse argv for options and arguments, and start schema generation.
Below is the the instruction that describes the task: ### Input: Parse argv for options and arguments, and start schema generation. ### Response: def main(): ''' Parse argv for options and arguments, and start schema generation. ''' parser = optparse.OptionParser(usage="%prog [options] <model_path>...
def js_on_click(self, handler): ''' Set up a JavaScript handler for button or menu item clicks. ''' self.js_on_event(ButtonClick, handler) self.js_on_event(MenuItemClick, handler)
Set up a JavaScript handler for button or menu item clicks.
Below is the the instruction that describes the task: ### Input: Set up a JavaScript handler for button or menu item clicks. ### Response: def js_on_click(self, handler): ''' Set up a JavaScript handler for button or menu item clicks. ''' self.js_on_event(ButtonClick, handler) self.js_on_ev...
def make_processitem_username(username, condition='contains', negate=False, preserve_case=False): """ Create a node for ProcessItem/Username :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/Username' content_type = 'string' c...
Create a node for ProcessItem/Username :return: A IndicatorItem represented as an Element node
Below is the the instruction that describes the task: ### Input: Create a node for ProcessItem/Username :return: A IndicatorItem represented as an Element node ### Response: def make_processitem_username(username, condition='contains', negate=False, preserve_case=False): """ Create a node for Proc...
def addBinding(self, node, value): """ Called when a binding is altered. - `node` is the statement responsible for the change - `value` is the new value, a Binding instance """ # assert value.source in (node, node.parent): for scope in self.scopeStack[::-1]: ...
Called when a binding is altered. - `node` is the statement responsible for the change - `value` is the new value, a Binding instance
Below is the the instruction that describes the task: ### Input: Called when a binding is altered. - `node` is the statement responsible for the change - `value` is the new value, a Binding instance ### Response: def addBinding(self, node, value): """ Called when a binding is alter...
def vdp_vlan_change(self, vsw_cb_data, vdp_vlan, fail_reason): """Callback Function from VDP when provider VLAN changes. This will be called only during error cases when switch reloads or when compute reloads. """ LOG.debug("In VDP VLAN change VLAN %s" % vdp_vlan) try: ...
Callback Function from VDP when provider VLAN changes. This will be called only during error cases when switch reloads or when compute reloads.
Below is the the instruction that describes the task: ### Input: Callback Function from VDP when provider VLAN changes. This will be called only during error cases when switch reloads or when compute reloads. ### Response: def vdp_vlan_change(self, vsw_cb_data, vdp_vlan, fail_reason): """C...
def ascwl( inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types=False, basedir=None, ): """Return the ``attrs`` attribute values of *inst* as a dict. Support ``jsonldPredicate`` in a field metadata for generating mappings from lists. Adapted from ``attr._...
Return the ``attrs`` attribute values of *inst* as a dict. Support ``jsonldPredicate`` in a field metadata for generating mappings from lists. Adapted from ``attr._funcs``.
Below is the the instruction that describes the task: ### Input: Return the ``attrs`` attribute values of *inst* as a dict. Support ``jsonldPredicate`` in a field metadata for generating mappings from lists. Adapted from ``attr._funcs``. ### Response: def ascwl( inst, recurse=True, filter...
def filter_response_size(size): """Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rty...
Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rtype: function
Below is the the instruction that describes the task: ### Input: Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters ...
def res_from_obseravtion_data(observation_data): """create a generic residual dataframe filled with np.NaN for missing information Parameters ---------- observation_data : pandas.DataFrame pyemu.Pst.observation_data Returns ------- res_df : pandas.DataFrame """ res_df ...
create a generic residual dataframe filled with np.NaN for missing information Parameters ---------- observation_data : pandas.DataFrame pyemu.Pst.observation_data Returns ------- res_df : pandas.DataFrame
Below is the the instruction that describes the task: ### Input: create a generic residual dataframe filled with np.NaN for missing information Parameters ---------- observation_data : pandas.DataFrame pyemu.Pst.observation_data Returns ------- res_df : pandas.DataFrame ### Res...
def smart_decode(binary, errors="strict"): """ Automatically find the right codec to decode binary data to string. :param binary: binary data :param errors: one of 'strict', 'ignore' and 'replace' :return: string """ d = chardet.detect(binary) encoding = d["encoding"] confidence = d...
Automatically find the right codec to decode binary data to string. :param binary: binary data :param errors: one of 'strict', 'ignore' and 'replace' :return: string
Below is the the instruction that describes the task: ### Input: Automatically find the right codec to decode binary data to string. :param binary: binary data :param errors: one of 'strict', 'ignore' and 'replace' :return: string ### Response: def smart_decode(binary, errors="strict"): """ Au...
def authenticate(job_args): """Authentication For Openstack API. Pulls the full Openstack Service Catalog Credentials are the Users API Username and Key/Password. Set a DC Endpoint and Authentication URL for the OpenStack environment """ # Load any authentication plugins as needed job_arg...
Authentication For Openstack API. Pulls the full Openstack Service Catalog Credentials are the Users API Username and Key/Password. Set a DC Endpoint and Authentication URL for the OpenStack environment
Below is the the instruction that describes the task: ### Input: Authentication For Openstack API. Pulls the full Openstack Service Catalog Credentials are the Users API Username and Key/Password. Set a DC Endpoint and Authentication URL for the OpenStack environment ### Response: def authenticate(jo...
def _to_dict_with_event(cls, test_state): """Process a test state into the format we want to send to the frontend.""" original_dict, event = test_state.asdict_with_event() # This line may produce a 'dictionary changed size during iteration' error. test_state_dict = data.convert_to_base_types(original_d...
Process a test state into the format we want to send to the frontend.
Below is the the instruction that describes the task: ### Input: Process a test state into the format we want to send to the frontend. ### Response: def _to_dict_with_event(cls, test_state): """Process a test state into the format we want to send to the frontend.""" original_dict, event = test_state.asdict...
def status(self, job_ids): ''' Get the status of a list of jobs identified by their ids. Args: - job_ids (List of ids) : List of identifiers for the jobs Returns: - List of status codes. ''' logging.debug("Checking status of : {0}".format(job_ids)) ...
Get the status of a list of jobs identified by their ids. Args: - job_ids (List of ids) : List of identifiers for the jobs Returns: - List of status codes.
Below is the the instruction that describes the task: ### Input: Get the status of a list of jobs identified by their ids. Args: - job_ids (List of ids) : List of identifiers for the jobs Returns: - List of status codes. ### Response: def status(self, job_ids): '''...
def all(self): """ Returns all layout objects of first level of depth """ self._check_layout() return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1))
Returns all layout objects of first level of depth
Below is the the instruction that describes the task: ### Input: Returns all layout objects of first level of depth ### Response: def all(self): """ Returns all layout objects of first level of depth """ self._check_layout() return LayoutSlice(self.layout, slice(0, len(self....
def draw_time_marker(self): """Draw the time marker on the TimeLine Canvas""" self._time_marker_image = self._canvas_ticks.create_image((2, 16), image=self._time_marker) self._time_marker_line = self._timeline.create_line( (2, 0, 2, self._timeline.winfo_height()), fill="#016dc9", wid...
Draw the time marker on the TimeLine Canvas
Below is the the instruction that describes the task: ### Input: Draw the time marker on the TimeLine Canvas ### Response: def draw_time_marker(self): """Draw the time marker on the TimeLine Canvas""" self._time_marker_image = self._canvas_ticks.create_image((2, 16), image=self._time_marker) ...
def notifyBlock(self, queue, blocked): ''' Internal notify for sub-queues been blocked ''' if blocked: if self.prioritySet[-1] == queue.priority: self.prioritySet.pop() else: pindex = bisect_left(self.prioritySet, queue.priority) ...
Internal notify for sub-queues been blocked
Below is the the instruction that describes the task: ### Input: Internal notify for sub-queues been blocked ### Response: def notifyBlock(self, queue, blocked): ''' Internal notify for sub-queues been blocked ''' if blocked: if self.prioritySet[-1] == queue.priority: ...
def forum_topic(self): """ | Comment: The topic this ticket originated from, if any """ if self.api and self.forum_topic_id: return self.api._get_topic(self.forum_topic_id)
| Comment: The topic this ticket originated from, if any
Below is the the instruction that describes the task: ### Input: | Comment: The topic this ticket originated from, if any ### Response: def forum_topic(self): """ | Comment: The topic this ticket originated from, if any """ if self.api and self.forum_topic_id: return s...
def ebrisk(rupgetter, srcfilter, param, monitor): """ :param rupgetter: a RuptureGetter instance :param srcfilter: a SourceFilter instance :param param: a dictionary of parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: ...
:param rupgetter: a RuptureGetter instance :param srcfilter: a SourceFilter instance :param param: a dictionary of parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: an ArrayWrapper with shape (E, L, T, ...)
Below is the the instruction that describes the task: ### Input: :param rupgetter: a RuptureGetter instance :param srcfilter: a SourceFilter instance :param param: a dictionary of parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :retu...
def get_dialogs_with_user(user_1, user_2): """ gets the dialog between user_1 and user_2 :param user_1: the first user in dialog (owner or opponent) :param user_2: the second user in dialog (owner or opponent) :return: queryset which include dialog between user_1 and user_2 (queryset can be empty) ...
gets the dialog between user_1 and user_2 :param user_1: the first user in dialog (owner or opponent) :param user_2: the second user in dialog (owner or opponent) :return: queryset which include dialog between user_1 and user_2 (queryset can be empty)
Below is the the instruction that describes the task: ### Input: gets the dialog between user_1 and user_2 :param user_1: the first user in dialog (owner or opponent) :param user_2: the second user in dialog (owner or opponent) :return: queryset which include dialog between user_1 and user_2 (queryset c...
def get_list(self): """ Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response """ field = self.FIELD_NAME query = ElasticQuery.get_agg(field=field, date_field=se...
Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response
Below is the the instruction that describes the task: ### Input: Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response ### Response: def get_list(self): """ Extract from a DSL aggregated response the values for each b...
def to_pwm(self, precision=4, extra_str=""): """Return pwm as string. Parameters ---------- precision : int, optional, default 4 Floating-point precision. extra_str |: str, optional Extra text to include with motif id line. Retur...
Return pwm as string. Parameters ---------- precision : int, optional, default 4 Floating-point precision. extra_str |: str, optional Extra text to include with motif id line. Returns ------- motif_str : str M...
Below is the the instruction that describes the task: ### Input: Return pwm as string. Parameters ---------- precision : int, optional, default 4 Floating-point precision. extra_str |: str, optional Extra text to include with motif id line. ...
def mappable(obj): """return whether an object is mappable or not.""" if isinstance(obj, (tuple,list)): return True for m in arrayModules: if isinstance(obj,m['type']): return True return False
return whether an object is mappable or not.
Below is the the instruction that describes the task: ### Input: return whether an object is mappable or not. ### Response: def mappable(obj): """return whether an object is mappable or not.""" if isinstance(obj, (tuple,list)): return True for m in arrayModules: if isinstance(obj,m['typ...
def is_file_excluded(self, repo_abspath, repo_file_path): """ Checks whether file at a given path is excluded. @param repo_abspath: Absolute path to the git repository. @type repo_abspath: str @param repo_file_path: Path to a file relative to repo_abspath. @type repo_fi...
Checks whether file at a given path is excluded. @param repo_abspath: Absolute path to the git repository. @type repo_abspath: str @param repo_file_path: Path to a file relative to repo_abspath. @type repo_file_path: str @return: True if file should be excluded. Otherwise Fals...
Below is the the instruction that describes the task: ### Input: Checks whether file at a given path is excluded. @param repo_abspath: Absolute path to the git repository. @type repo_abspath: str @param repo_file_path: Path to a file relative to repo_abspath. @type repo_file_path: ...
def delete_tables_partitions(self, ds): """Fast delete of all of a datasets codes, columns, partitions and tables""" from ambry.orm import Code, Column, Table, Partition, ColumnStat, Process ssq = self.session.query ssq(Process).filter(Process.d_vid == ds.vid).delete() ssq(Code...
Fast delete of all of a datasets codes, columns, partitions and tables
Below is the the instruction that describes the task: ### Input: Fast delete of all of a datasets codes, columns, partitions and tables ### Response: def delete_tables_partitions(self, ds): """Fast delete of all of a datasets codes, columns, partitions and tables""" from ambry.orm import Code, Colu...
def add_row(self, list_or_dict, key=None): """ Adds a list or dict as a row in the FVM data structure :param str key: key used when rows is a dict rather than an array :param list_or_dict: a feature list or dict """ if isinstance(list_or_dict, list): self._add_list_r...
Adds a list or dict as a row in the FVM data structure :param str key: key used when rows is a dict rather than an array :param list_or_dict: a feature list or dict
Below is the the instruction that describes the task: ### Input: Adds a list or dict as a row in the FVM data structure :param str key: key used when rows is a dict rather than an array :param list_or_dict: a feature list or dict ### Response: def add_row(self, list_or_dict, key=None): """...
def _get_known_noncoding_het_snp(data_dict): '''If ref is coding, return None. If the data dict has a known snp, and samtools made a call, then return the string ref_name_change and the % of reads supporting the variant type. If noncoding, but no samtools call, then return None'...
If ref is coding, return None. If the data dict has a known snp, and samtools made a call, then return the string ref_name_change and the % of reads supporting the variant type. If noncoding, but no samtools call, then return None
Below is the the instruction that describes the task: ### Input: If ref is coding, return None. If the data dict has a known snp, and samtools made a call, then return the string ref_name_change and the % of reads supporting the variant type. If noncoding, but no samtools call, then...
def _build_volume(self, volume): """ Given a generic volume definition, create the volumes element """ self.volumes[self._build_volume_name(volume.get('host'))] = { 'name': self._build_volume_name(volume.get('host')), 'hostPath': { 'path': volume.g...
Given a generic volume definition, create the volumes element
Below is the the instruction that describes the task: ### Input: Given a generic volume definition, create the volumes element ### Response: def _build_volume(self, volume): """ Given a generic volume definition, create the volumes element """ self.volumes[self._build_volume_name(vo...
def extract_notebook_metatab(nb_path: Path): """Extract the metatab lines from a notebook and return a Metapack doc """ from metatab.rowgenerators import TextRowGenerator import nbformat with nb_path.open() as f: nb = nbformat.read(f, as_version=4) lines = '\n'.join(['Declare: metatab-lat...
Extract the metatab lines from a notebook and return a Metapack doc
Below is the the instruction that describes the task: ### Input: Extract the metatab lines from a notebook and return a Metapack doc ### Response: def extract_notebook_metatab(nb_path: Path): """Extract the metatab lines from a notebook and return a Metapack doc """ from metatab.rowgenerators import TextR...
def write_users(dburl): """Write users to the DB.""" data = { 'username': 'admin', 'realname': 'Website Administrator', 'email': 'coil@example.com', 'password': r'$bcrypt-sha256$2a,12$NNtd2TC9mZO6.EvLwEwlLO$axojD34/iE8x' r'QitQnCCOGPhofgmjNdq', } ...
Write users to the DB.
Below is the the instruction that describes the task: ### Input: Write users to the DB. ### Response: def write_users(dburl): """Write users to the DB.""" data = { 'username': 'admin', 'realname': 'Website Administrator', 'email': 'coil@example.com', 'password': ...
def flatten(iterable): """ flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). :param sequence: any object that implements iterable protocol (see: :ref:`typeiter`) :return: li...
flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). :param sequence: any object that implements iterable protocol (see: :ref:`typeiter`) :return: list Examples: >>> from adm...
Below is the the instruction that describes the task: ### Input: flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). :param sequence: any object that implements iterable protocol (see...
def _writeSuperJunctions(self, superJunctions, fileObject): """ Write SuperJunctions to File Method """ for sjunc in superJunctions: fileObject.write('SJUNC %s %.2f %.2f %.6f %s %s %s %.6f %.6f\n' % ( sjunc.sjuncNumber, sjunc.groundSur...
Write SuperJunctions to File Method
Below is the the instruction that describes the task: ### Input: Write SuperJunctions to File Method ### Response: def _writeSuperJunctions(self, superJunctions, fileObject): """ Write SuperJunctions to File Method """ for sjunc in superJunctions: fileObject.write('SJUNC...
def get_connection(path=None, fail_silently=False, **kwargs): """ Load an sms backend and return an instance of it. :param string path: backend python path. Default: sendsms.backends.console.SmsBackend :param bool fail_silently: Flag to not throw exceptions on error. Default: False :returns: backen...
Load an sms backend and return an instance of it. :param string path: backend python path. Default: sendsms.backends.console.SmsBackend :param bool fail_silently: Flag to not throw exceptions on error. Default: False :returns: backend class instance. :rtype: :py:class:`~sendsms.backends.base.BaseSmsBac...
Below is the the instruction that describes the task: ### Input: Load an sms backend and return an instance of it. :param string path: backend python path. Default: sendsms.backends.console.SmsBackend :param bool fail_silently: Flag to not throw exceptions on error. Default: False :returns: backend cla...
def get_price(self): """ Shortcut to self.get_ticks(lookback=1, as_dict=True)['last'] """ tick = self.get_ticks(lookback=1, as_dict=True) return None if tick is None else tick['last']
Shortcut to self.get_ticks(lookback=1, as_dict=True)['last']
Below is the the instruction that describes the task: ### Input: Shortcut to self.get_ticks(lookback=1, as_dict=True)['last'] ### Response: def get_price(self): """ Shortcut to self.get_ticks(lookback=1, as_dict=True)['last'] """ tick = self.get_ticks(lookback=1, as_dict=True) return None i...
def main(): """ Example application that prints messages from the panel to the terminal. """ try: # Retrieve the first USB device device = AlarmDecoder(USBDevice.find()) # Set up an event handler and open the device device.on_message += handle_message with device...
Example application that prints messages from the panel to the terminal.
Below is the the instruction that describes the task: ### Input: Example application that prints messages from the panel to the terminal. ### Response: def main(): """ Example application that prints messages from the panel to the terminal. """ try: # Retrieve the first USB device d...