code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def api_get(self, action, data, headers=None): """ Perform an HTTP GET request, using the shared-secret auth hash. @param action: API action call @param data: dictionary values """ return self._api_request(action, data, 'GET', headers)
Perform an HTTP GET request, using the shared-secret auth hash. @param action: API action call @param data: dictionary values
Below is the the instruction that describes the task: ### Input: Perform an HTTP GET request, using the shared-secret auth hash. @param action: API action call @param data: dictionary values ### Response: def api_get(self, action, data, headers=None): """ Perform an HTTP GET request...
def _update_repo(self, juicer_repo, pulp_repo, env, repo_diff, query='/repositories/'): """ `from_file` - JSON file of repo definitions `noop` - Boolean, if true don't actually create/update repos, just show what would have happened https://pulp-dev-guide.readthedocs.org/en/pulp-2.3/int...
`from_file` - JSON file of repo definitions `noop` - Boolean, if true don't actually create/update repos, just show what would have happened https://pulp-dev-guide.readthedocs.org/en/pulp-2.3/integration/rest-api/repo/cud.html#update-a-distributor-associated-with-a-repository https://pulp-dev-g...
Below is the the instruction that describes the task: ### Input: `from_file` - JSON file of repo definitions `noop` - Boolean, if true don't actually create/update repos, just show what would have happened https://pulp-dev-guide.readthedocs.org/en/pulp-2.3/integration/rest-api/repo/cud.html#update-...
def parent(): """Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.e...
Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.exe, then the full ...
Below is the the instruction that describes the task: ### Input: Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level ca...
def install_jspackage(package_name, version, modulesdir): """Installs a JavaScript package downloaded from npmjs.org. For example to install React:: install_jspackage('react', '0.14.8', './node_modules') To install last version provide `None` as the version. """ if not version: ve...
Installs a JavaScript package downloaded from npmjs.org. For example to install React:: install_jspackage('react', '0.14.8', './node_modules') To install last version provide `None` as the version.
Below is the the instruction that describes the task: ### Input: Installs a JavaScript package downloaded from npmjs.org. For example to install React:: install_jspackage('react', '0.14.8', './node_modules') To install last version provide `None` as the version. ### Response: def install_jspacka...
def json(self, args=None): """Return a dictionary representation of the class. Notes ----- This is meant to be used by a third-party library wanting to wrap this class into another interface. """ names = ['identifier', 'abstract', 'keywords'] out = {key: getattr...
Return a dictionary representation of the class. Notes ----- This is meant to be used by a third-party library wanting to wrap this class into another interface.
Below is the the instruction that describes the task: ### Input: Return a dictionary representation of the class. Notes ----- This is meant to be used by a third-party library wanting to wrap this class into another interface. ### Response: def json(self, args=None): """Return a di...
def apply_bios_properties_filter(settings, filter_to_be_applied): """Applies the filter to return the dict of filtered BIOS properties. :param settings: dict of BIOS settings on which filter to be applied. :param filter_to_be_applied: list of keys to be applied as filter. :returns: A dictionary of filt...
Applies the filter to return the dict of filtered BIOS properties. :param settings: dict of BIOS settings on which filter to be applied. :param filter_to_be_applied: list of keys to be applied as filter. :returns: A dictionary of filtered BIOS settings.
Below is the the instruction that describes the task: ### Input: Applies the filter to return the dict of filtered BIOS properties. :param settings: dict of BIOS settings on which filter to be applied. :param filter_to_be_applied: list of keys to be applied as filter. :returns: A dictionary of filtered...
def make_form_field(field, model=None, field_cls=None, use_default_value=True, builds_args_map=None): """ make form field according field value :param field: such as: str, Form Field instance, dict if field is str type, it'll fetch property from model or...
make form field according field value :param field: such as: str, Form Field instance, dict if field is str type, it'll fetch property from model or str is like 'model.name' it'll fetch property `name` from `model` :param model: if field is str type, it'll may use model value to fetch proper...
Below is the the instruction that describes the task: ### Input: make form field according field value :param field: such as: str, Form Field instance, dict if field is str type, it'll fetch property from model or str is like 'model.name' it'll fetch property `name` from `model` :param m...
def write(self, outfile, encoding): """Method override to create self-closing elements. https://docs.djangoproject.com/en/2.0/ref/utils/#django.utils.feedgenerator.SyndicationFeed.write https://github.com/django/django/blob/2.0/django/utils/feedgenerator.py#L216 """ try: ...
Method override to create self-closing elements. https://docs.djangoproject.com/en/2.0/ref/utils/#django.utils.feedgenerator.SyndicationFeed.write https://github.com/django/django/blob/2.0/django/utils/feedgenerator.py#L216
Below is the the instruction that describes the task: ### Input: Method override to create self-closing elements. https://docs.djangoproject.com/en/2.0/ref/utils/#django.utils.feedgenerator.SyndicationFeed.write https://github.com/django/django/blob/2.0/django/utils/feedgenerator.py#L216 ### Respon...
def connection_lost(self, exc): '''Called by asyncio when the connection closes. Tear down things done in connection_made.''' # Work around uvloop bug; see https://github.com/MagicStack/uvloop/issues/246 if self.transport: self.transport = None self.closed_event....
Called by asyncio when the connection closes. Tear down things done in connection_made.
Below is the the instruction that describes the task: ### Input: Called by asyncio when the connection closes. Tear down things done in connection_made. ### Response: def connection_lost(self, exc): '''Called by asyncio when the connection closes. Tear down things done in connection_made....
def get_layer(pressure, *args, **kwargs): r"""Return an atmospheric layer from upper air data with the requested bottom and depth. This function will subset an upper air dataset to contain only the specified layer. The bottom of the layer can be specified with a pressure or height above the surface pre...
r"""Return an atmospheric layer from upper air data with the requested bottom and depth. This function will subset an upper air dataset to contain only the specified layer. The bottom of the layer can be specified with a pressure or height above the surface pressure. The bottom defaults to the surface pres...
Below is the the instruction that describes the task: ### Input: r"""Return an atmospheric layer from upper air data with the requested bottom and depth. This function will subset an upper air dataset to contain only the specified layer. The bottom of the layer can be specified with a pressure or height ab...
def add_new_grid_headers(self, new_headers): """ Add in all user-added headers. If those new headers depend on other headers, add the other headers too. """ already_present = [] for name in new_headers: if name: if name not in self.grid...
Add in all user-added headers. If those new headers depend on other headers, add the other headers too.
Below is the the instruction that describes the task: ### Input: Add in all user-added headers. If those new headers depend on other headers, add the other headers too. ### Response: def add_new_grid_headers(self, new_headers): """ Add in all user-added headers. If those new...
def render_diagram(out_base): """Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: This function requires the 'dot'...
Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: This function requires the 'dot' executable from the GraphViz package...
Below is the the instruction that describes the task: ### Input: Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: ...
def _iter_channels(framefile): """Yields the name and type of each channel in a GWF file TOC **Requires:** |LDAStools.frameCPP|_ Parameters ---------- framefile : `str`, `LDAStools.frameCPP.IFrameFStream` path of GWF file, or open file stream, to read """ from LDAStools import fram...
Yields the name and type of each channel in a GWF file TOC **Requires:** |LDAStools.frameCPP|_ Parameters ---------- framefile : `str`, `LDAStools.frameCPP.IFrameFStream` path of GWF file, or open file stream, to read
Below is the the instruction that describes the task: ### Input: Yields the name and type of each channel in a GWF file TOC **Requires:** |LDAStools.frameCPP|_ Parameters ---------- framefile : `str`, `LDAStools.frameCPP.IFrameFStream` path of GWF file, or open file stream, to read ### Res...
def _nac(self, q_direction): """nac_term = (A1 (x) A2) / B * coef. """ num_atom = self._pcell.get_number_of_atoms() nac_q = np.zeros((num_atom, num_atom, 3, 3), dtype='double') if (np.abs(q_direction) < 1e-5).all(): return nac_q rec_lat = np.linalg.inv(self._...
nac_term = (A1 (x) A2) / B * coef.
Below is the the instruction that describes the task: ### Input: nac_term = (A1 (x) A2) / B * coef. ### Response: def _nac(self, q_direction): """nac_term = (A1 (x) A2) / B * coef. """ num_atom = self._pcell.get_number_of_atoms() nac_q = np.zeros((num_atom, num_atom, 3, 3), dtype='d...
def _finalise_result_(compound, value, mass): """ Convert the value to its final form by unit conversions and multiplying by mass. :param compound: Compound object. :param value: [J/mol] Value to be finalised. :param mass: [kg] Mass of compound. :returns: [kWh] Finalised value. """ ...
Convert the value to its final form by unit conversions and multiplying by mass. :param compound: Compound object. :param value: [J/mol] Value to be finalised. :param mass: [kg] Mass of compound. :returns: [kWh] Finalised value.
Below is the the instruction that describes the task: ### Input: Convert the value to its final form by unit conversions and multiplying by mass. :param compound: Compound object. :param value: [J/mol] Value to be finalised. :param mass: [kg] Mass of compound. :returns: [kWh] Finalised value. ...
def cross_list_section(self, id, new_course_id): """ Cross-list a Section. Move the Section to another course. The new course may be in a different account (department), but must belong to the same root account (institution). """ path = {} data = {} ...
Cross-list a Section. Move the Section to another course. The new course may be in a different account (department), but must belong to the same root account (institution).
Below is the the instruction that describes the task: ### Input: Cross-list a Section. Move the Section to another course. The new course may be in a different account (department), but must belong to the same root account (institution). ### Response: def cross_list_section(self, id, new_cours...
def intern(self, text): """Interns the given Unicode sequence into the symbol table. Note: This operation is only valid on local symbol tables. Args: text (unicode): The target to intern. Returns: SymbolToken: The mapped symbol token which may alrea...
Interns the given Unicode sequence into the symbol table. Note: This operation is only valid on local symbol tables. Args: text (unicode): The target to intern. Returns: SymbolToken: The mapped symbol token which may already exist in the table.
Below is the the instruction that describes the task: ### Input: Interns the given Unicode sequence into the symbol table. Note: This operation is only valid on local symbol tables. Args: text (unicode): The target to intern. Returns: SymbolToken: The m...
def get_subclass_from_module(module, parent_class): """ Get a subclass of parent_class from the module at module get_subclass_from_module performs reflection to find the first class that extends the parent_class in the module path, and returns it. """ try: r = __recursive_import(module)...
Get a subclass of parent_class from the module at module get_subclass_from_module performs reflection to find the first class that extends the parent_class in the module path, and returns it.
Below is the the instruction that describes the task: ### Input: Get a subclass of parent_class from the module at module get_subclass_from_module performs reflection to find the first class that extends the parent_class in the module path, and returns it. ### Response: def get_subclass_from_module(module...
def fold_joint_sfs(s, n1, n2): """Fold a joint site frequency spectrum. Parameters ---------- s : array_like, int, shape (m_chromosomes, n_chromosomes) Joint site frequency spectrum. n1, n2 : int, optional The total number of chromosomes called in each population. Returns -...
Fold a joint site frequency spectrum. Parameters ---------- s : array_like, int, shape (m_chromosomes, n_chromosomes) Joint site frequency spectrum. n1, n2 : int, optional The total number of chromosomes called in each population. Returns ------- joint_sfs_folded : ndarray,...
Below is the the instruction that describes the task: ### Input: Fold a joint site frequency spectrum. Parameters ---------- s : array_like, int, shape (m_chromosomes, n_chromosomes) Joint site frequency spectrum. n1, n2 : int, optional The total number of chromosomes called in each...
def _get_sorted_relationships(self, goterm): """Traverse GO Terms above the current GO Term. Then add current GO Term to sorted.""" if goterm.id in self.goids_seen: return self.goids_seen.add(goterm.id) for goterm_upper in goterm.get_goterms_upper(): self._get_sor...
Traverse GO Terms above the current GO Term. Then add current GO Term to sorted.
Below is the the instruction that describes the task: ### Input: Traverse GO Terms above the current GO Term. Then add current GO Term to sorted. ### Response: def _get_sorted_relationships(self, goterm): """Traverse GO Terms above the current GO Term. Then add current GO Term to sorted.""" if gote...
def get_variables_substitution_dictionaries(self, lhs_graph, rhs_graph): """ Looks for sub-isomorphisms of rhs into lhs :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph) :param rhs_graph: The smaller graph :return: The list of matching names ""...
Looks for sub-isomorphisms of rhs into lhs :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph) :param rhs_graph: The smaller graph :return: The list of matching names
Below is the the instruction that describes the task: ### Input: Looks for sub-isomorphisms of rhs into lhs :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph) :param rhs_graph: The smaller graph :return: The list of matching names ### Response: def get_variables_s...
def _sample_points(X, centers, oversampling_factor, random_state): r""" Sample points independently with probability .. math:: p_x = \frac{\ell \cdot d^2(x, \mathcal{C})}{\phi_X(\mathcal{C})} """ # re-implement evaluate_cost here, to avoid redundant computation distances = pairwise_di...
r""" Sample points independently with probability .. math:: p_x = \frac{\ell \cdot d^2(x, \mathcal{C})}{\phi_X(\mathcal{C})}
Below is the the instruction that describes the task: ### Input: r""" Sample points independently with probability .. math:: p_x = \frac{\ell \cdot d^2(x, \mathcal{C})}{\phi_X(\mathcal{C})} ### Response: def _sample_points(X, centers, oversampling_factor, random_state): r""" Sample points...
def handle(self, *args, **options): """ Command execution. """ self.cursor = connection.cursor() self.introspection = connection.introspection self.interactive = options['interactive'] found_missing_fields = False models = translator.get_registered_models...
Command execution.
Below is the the instruction that describes the task: ### Input: Command execution. ### Response: def handle(self, *args, **options): """ Command execution. """ self.cursor = connection.cursor() self.introspection = connection.introspection self.interactive = options...
def _set_any(self, v, load=False): """ Setter method for any, mapped from YANG variable /overlay_class_map/cmap_seq/match/any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_any is considered as a private method. Backends looking to populate this variable sho...
Setter method for any, mapped from YANG variable /overlay_class_map/cmap_seq/match/any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_any is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_any() di...
Below is the the instruction that describes the task: ### Input: Setter method for any, mapped from YANG variable /overlay_class_map/cmap_seq/match/any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_any is considered as a private method. Backends looking to popu...
def _email(name, *, allow_unverified=False): """ This decorator is used to turn an e function into an email sending function! The name parameter is the name of the email we're going to be sending (used to locate the templates on the file system). The allow_unverified kwarg flags whether we will se...
This decorator is used to turn an e function into an email sending function! The name parameter is the name of the email we're going to be sending (used to locate the templates on the file system). The allow_unverified kwarg flags whether we will send this email to an unverified email or not. We gener...
Below is the the instruction that describes the task: ### Input: This decorator is used to turn an e function into an email sending function! The name parameter is the name of the email we're going to be sending (used to locate the templates on the file system). The allow_unverified kwarg flags whethe...
def switch_to_frame_with_id(self, frame): """Swap Selenium's context to the given frame or iframe.""" elem = world.browser.find_element_by_id(frame) world.browser.switch_to.frame(elem)
Swap Selenium's context to the given frame or iframe.
Below is the the instruction that describes the task: ### Input: Swap Selenium's context to the given frame or iframe. ### Response: def switch_to_frame_with_id(self, frame): """Swap Selenium's context to the given frame or iframe.""" elem = world.browser.find_element_by_id(frame) world.browser.switch_...
def _get_config(self, section: str, key: str, fallback: str=object()) -> str: """ Gets a string config value :param section: Section :param key: Key :param fallback: Optional fallback value """ return self._config.get(section, key, fallback=fallback)
Gets a string config value :param section: Section :param key: Key :param fallback: Optional fallback value
Below is the the instruction that describes the task: ### Input: Gets a string config value :param section: Section :param key: Key :param fallback: Optional fallback value ### Response: def _get_config(self, section: str, key: str, fallback: str=object()) -> str: """ Gets a...
def remove_initial_spaces_and_mark_message_lines(lines): """ Removes the initial spaces in each line before marking message lines. This ensures headers can be identified if they are indented with spaces. """ i = 0 while i < len(lines): lines[i] = lines[i].lstrip(' ') i += 1 ...
Removes the initial spaces in each line before marking message lines. This ensures headers can be identified if they are indented with spaces.
Below is the the instruction that describes the task: ### Input: Removes the initial spaces in each line before marking message lines. This ensures headers can be identified if they are indented with spaces. ### Response: def remove_initial_spaces_and_mark_message_lines(lines): """ Removes the initial...
def plot_filters(filters): '''Create a plot of conv filters, visualized as pixel arrays.''' imgs = filters.get_value() N, channels, x, y = imgs.shape n = int(np.sqrt(N)) assert n * n == N, 'filters must contain a square number of rows!' assert channels == 1 or channels == 3, 'can only plot gray...
Create a plot of conv filters, visualized as pixel arrays.
Below is the the instruction that describes the task: ### Input: Create a plot of conv filters, visualized as pixel arrays. ### Response: def plot_filters(filters): '''Create a plot of conv filters, visualized as pixel arrays.''' imgs = filters.get_value() N, channels, x, y = imgs.shape n = int(np...
def write(self, writer=None, encoding='utf-8', indent=0, newline='', omit_declaration=False, node_depth=0, quote_char='"'): """ Serialize this node and its descendants to text, writing the output to a given *writer* or to stdout. :param writer: an object such as a file or st...
Serialize this node and its descendants to text, writing the output to a given *writer* or to stdout. :param writer: an object such as a file or stream to which XML text is sent. If *None* text is sent to :attr:`sys.stdout`. :type writer: a file, stream, etc or None :param s...
Below is the the instruction that describes the task: ### Input: Serialize this node and its descendants to text, writing the output to a given *writer* or to stdout. :param writer: an object such as a file or stream to which XML text is sent. If *None* text is sent to :attr:`sys.stdout...
def _tune(self, args): """ propose connection tuning parameters This method proposes a set of connection configuration values to the client. The client can accept and/or adjust these. PARAMETERS: channel_max: short proposed maximum channels ...
propose connection tuning parameters This method proposes a set of connection configuration values to the client. The client can accept and/or adjust these. PARAMETERS: channel_max: short proposed maximum channels The maximum total number of chann...
Below is the the instruction that describes the task: ### Input: propose connection tuning parameters This method proposes a set of connection configuration values to the client. The client can accept and/or adjust these. PARAMETERS: channel_max: short propose...
def setup_stanza_handlers(self, handler_objects, usage_restriction): """Install stanza handlers provided by `handler_objects`""" # pylint: disable=W0212 iq_handlers = {"get": {}, "set": {}} message_handlers = [] presence_handlers = [] for obj in handler_objects: ...
Install stanza handlers provided by `handler_objects`
Below is the the instruction that describes the task: ### Input: Install stanza handlers provided by `handler_objects` ### Response: def setup_stanza_handlers(self, handler_objects, usage_restriction): """Install stanza handlers provided by `handler_objects`""" # pylint: disable=W0212 iq_ha...
def generate_pws_in_order(self, n, filter_func=None, N_max=1e6): """ Generates passwords in order between upto N_max @N_max is the maximum size of the priority queue will be tolerated, so if the size of the queue is bigger than 1.5 * N_max, it will shrink the size to 0.75 * N_max...
Generates passwords in order between upto N_max @N_max is the maximum size of the priority queue will be tolerated, so if the size of the queue is bigger than 1.5 * N_max, it will shrink the size to 0.75 * N_max @n is the number of password to generate. **This function is expensi...
Below is the the instruction that describes the task: ### Input: Generates passwords in order between upto N_max @N_max is the maximum size of the priority queue will be tolerated, so if the size of the queue is bigger than 1.5 * N_max, it will shrink the size to 0.75 * N_max @n is t...
def pix2sky(self, pixel): """ Get the sky coordinates for a given image pixel. Parameters ---------- pixel : (float, float) Image coordinates. Returns ------- ra,dec : float Sky coordinates (degrees) """ pixbox = ...
Get the sky coordinates for a given image pixel. Parameters ---------- pixel : (float, float) Image coordinates. Returns ------- ra,dec : float Sky coordinates (degrees)
Below is the the instruction that describes the task: ### Input: Get the sky coordinates for a given image pixel. Parameters ---------- pixel : (float, float) Image coordinates. Returns ------- ra,dec : float Sky coordinates (degrees) ### Res...
def synset(self, synset_repr): ''' Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') ...
Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') Synset(funktionieren.v.2)
Below is the the instruction that describes the task: ### Input: Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'fun...
def _read_msg(self): """read message from server""" # # NOTE: # '_recv_socket(nbytes)' was implemented as # 'socket.recv(nbytes, socket.MSG_WAITALL)' # but socket.MSG_WAITALL proved not reliable # def _recv_socket(nbytes): """read nbytes byte...
read message from server
Below is the the instruction that describes the task: ### Input: read message from server ### Response: def _read_msg(self): """read message from server""" # # NOTE: # '_recv_socket(nbytes)' was implemented as # 'socket.recv(nbytes, socket.MSG_WAITALL)' # but socket...
def predict(self, a, b): """ Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic """ a = np.array(a).reshape((-1, 1)) b = np.array(b).reshape((-1, 1)) return (m...
Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic
Below is the the instruction that describes the task: ### Input: Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic ### Response: def predict(self, a, b): """ Compute the test statistic ...
def statistics(self, elapsed, result): """ Return output for the combined time and result summary statistics. """ return "\n".join((self.timing(elapsed), self.result_summary(result)))
Return output for the combined time and result summary statistics.
Below is the the instruction that describes the task: ### Input: Return output for the combined time and result summary statistics. ### Response: def statistics(self, elapsed, result): """ Return output for the combined time and result summary statistics. """ return "\n".join((sel...
def unmanaged_cpcs(self): """ :class:`~zhmcclient.UnmanagedCpcManager`: Access to the unmanaged :term:`CPCs <CPC>` in this Console. """ # We do here some lazy loading. if not self._unmanaged_cpcs: self._unmanaged_cpcs = UnmanagedCpcManager(self) return...
:class:`~zhmcclient.UnmanagedCpcManager`: Access to the unmanaged :term:`CPCs <CPC>` in this Console.
Below is the the instruction that describes the task: ### Input: :class:`~zhmcclient.UnmanagedCpcManager`: Access to the unmanaged :term:`CPCs <CPC>` in this Console. ### Response: def unmanaged_cpcs(self): """ :class:`~zhmcclient.UnmanagedCpcManager`: Access to the unmanaged :term:...
def t_ccomment_close(self, t): r'\*\/' t.lexer.ccomment_level -= 1 if t.lexer.ccomment_level == 0: t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1 - 3] t.type = "CCOMMENT" t.lexer.lineno += t.value.count('\n') t.lexer.begin('INITIA...
r'\*\/
Below is the the instruction that describes the task: ### Input: r'\*\/ ### Response: def t_ccomment_close(self, t): r'\*\/' t.lexer.ccomment_level -= 1 if t.lexer.ccomment_level == 0: t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1 - 3] t.type = "CC...
def sample_out_dir(self): """Absolute path to permanent location in working directory where EricScript output for the current sample will be stored. (a subdirectory of `output_dir`) """ if self._sample_out_dir is None: self._sample_out_dir = os.path.join( ...
Absolute path to permanent location in working directory where EricScript output for the current sample will be stored. (a subdirectory of `output_dir`)
Below is the the instruction that describes the task: ### Input: Absolute path to permanent location in working directory where EricScript output for the current sample will be stored. (a subdirectory of `output_dir`) ### Response: def sample_out_dir(self): """Absolute path to permanent loc...
async def start(self): """Start process execution.""" # Workaround for pylint issue #1469 # (https://github.com/PyCQA/pylint/issues/1469). self.proc = await subprocess.create_subprocess_exec( # pylint: disable=no-member *shlex.split(self.command), stdin=subproces...
Start process execution.
Below is the the instruction that describes the task: ### Input: Start process execution. ### Response: async def start(self): """Start process execution.""" # Workaround for pylint issue #1469 # (https://github.com/PyCQA/pylint/issues/1469). self.proc = await subprocess.create_subp...
def list(self, virtual_host='/', show_all=False): """List Queues. :param str virtual_host: Virtual host name :param bool show_all: List all Queues :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity ...
List Queues. :param str virtual_host: Virtual host name :param bool show_all: List all Queues :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: List Queues. :param str virtual_host: Virtual host name :param bool show_all: List all Queues :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a conne...
def _choose_what_to_display(self, force_refresh=False): """ Choose what combination to display on the bar. By default we try to display the active layout on the first run, else we display the last selected combination. """ for _ in range(len(self.available_combinations))...
Choose what combination to display on the bar. By default we try to display the active layout on the first run, else we display the last selected combination.
Below is the the instruction that describes the task: ### Input: Choose what combination to display on the bar. By default we try to display the active layout on the first run, else we display the last selected combination. ### Response: def _choose_what_to_display(self, force_refresh=False): ...
def _process_exception(e, body, tb): """ Process informations about exception and send them thru AMQP. Args: e (obj): Exception instance. body (str): Text which will be sent over AMQP. tb (obj): Traceback object with informations, which will be put to the headers. ...
Process informations about exception and send them thru AMQP. Args: e (obj): Exception instance. body (str): Text which will be sent over AMQP. tb (obj): Traceback object with informations, which will be put to the headers.
Below is the the instruction that describes the task: ### Input: Process informations about exception and send them thru AMQP. Args: e (obj): Exception instance. body (str): Text which will be sent over AMQP. tb (obj): Traceback object with informations, which will be put to the ...
def dispatch_commands(functions, *args, **kwargs): """ A wrapper for :func:`dispatch` that creates a parser, adds commands to the parser and dispatches them. Uses :attr:`PARSER_FORMATTER`. This:: dispatch_commands([foo, bar]) ...is a shortcut for:: parser = ArgumentParser() ...
A wrapper for :func:`dispatch` that creates a parser, adds commands to the parser and dispatches them. Uses :attr:`PARSER_FORMATTER`. This:: dispatch_commands([foo, bar]) ...is a shortcut for:: parser = ArgumentParser() add_commands(parser, [foo, bar]) dispatch(parser...
Below is the the instruction that describes the task: ### Input: A wrapper for :func:`dispatch` that creates a parser, adds commands to the parser and dispatches them. Uses :attr:`PARSER_FORMATTER`. This:: dispatch_commands([foo, bar]) ...is a shortcut for:: parser = ArgumentPars...
def _line_by_type(self, line, header, hgroups, htypes, out, want_type, collapse_quals_fn = None): """Parse out key value pairs for line information based on a group of values. """ for index, htype in ((i, t) for i, t in enumerate(htypes) if t == want_type): col ...
Parse out key value pairs for line information based on a group of values.
Below is the the instruction that describes the task: ### Input: Parse out key value pairs for line information based on a group of values. ### Response: def _line_by_type(self, line, header, hgroups, htypes, out, want_type, collapse_quals_fn = None): """Parse out key value pairs for ...
def write_double(self, number): """ Writes a double to the underlying output file as a 8-byte value. """ buf = pack(self.byte_order + "d", number) self.write(buf)
Writes a double to the underlying output file as a 8-byte value.
Below is the the instruction that describes the task: ### Input: Writes a double to the underlying output file as a 8-byte value. ### Response: def write_double(self, number): """ Writes a double to the underlying output file as a 8-byte value. """ buf = pack(self.byte_order + "d", number) ...
def check_valid_cpc_status(method, uri, cpc): """ Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: ConflictError wit...
Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: ConflictError with reason 1: The CPC itself has been targeted by the ...
Below is the the instruction that describes the task: ### Input: Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: Confli...
def time_elapsed(func): """ 记录函数运行耗时的生成器 :param func: :return: """ @wraps(func) def wrapper(*args, **kwargs): timestamp = time.time() * 1000 ret = func(*args, **kwargs) now_ts = time.time() * 1000 elapsed = now_ts - timestamp print('%s costs time: %.2...
记录函数运行耗时的生成器 :param func: :return:
Below is the the instruction that describes the task: ### Input: 记录函数运行耗时的生成器 :param func: :return: ### Response: def time_elapsed(func): """ 记录函数运行耗时的生成器 :param func: :return: """ @wraps(func) def wrapper(*args, **kwargs): timestamp = time.time() * 1000 ret = f...
async def stop(self): """ Stop recording. """ if self.__container: for track, context in self.__tracks.items(): if context.task is not None: context.task.cancel() context.task = None for packet in con...
Stop recording.
Below is the the instruction that describes the task: ### Input: Stop recording. ### Response: async def stop(self): """ Stop recording. """ if self.__container: for track, context in self.__tracks.items(): if context.task is not None: ...
def store_records_for_package(self, entry_point, records): """ Store the records in a way that permit lookup by package """ # If provided records already exist in the module mapping list, # it likely means that a package declared multiple keys for the # same package name...
Store the records in a way that permit lookup by package
Below is the the instruction that describes the task: ### Input: Store the records in a way that permit lookup by package ### Response: def store_records_for_package(self, entry_point, records): """ Store the records in a way that permit lookup by package """ # If provided records ...
def check_sentence_spacing(text): """Use no more than two spaces after a period.""" err = "typography.symbols.sentence_spacing" msg = u"More than two spaces after the period; use 1 or 2." regex = "\. {3}" return existence_check( text, [regex], err, msg, max_errors=3, require_padding=False)
Use no more than two spaces after a period.
Below is the the instruction that describes the task: ### Input: Use no more than two spaces after a period. ### Response: def check_sentence_spacing(text): """Use no more than two spaces after a period.""" err = "typography.symbols.sentence_spacing" msg = u"More than two spaces after the period; use 1...
def t_TOKEN(t): '[a-zA-Z0-9]+' #print t.value,t.lexer.lexdata[t.lexer.lexpos-len(t.value):],re_TYPE.match(t.lexer.lexdata,t.lexer.lexpos-len(t.value)) if re_TYPE.match(t.value): t.type = 'TYPE' elif re_PTR.match(t.value): t.type = 'PTR' elif re_NUMBER.match(t.value): if t.val...
[a-zA-Z0-9]+
Below is the the instruction that describes the task: ### Input: [a-zA-Z0-9]+ ### Response: def t_TOKEN(t): '[a-zA-Z0-9]+' #print t.value,t.lexer.lexdata[t.lexer.lexpos-len(t.value):],re_TYPE.match(t.lexer.lexdata,t.lexer.lexpos-len(t.value)) if re_TYPE.match(t.value): t.type = 'TYPE' elif ...
def fetchmany(self, size = None): """ As in DBAPI2.0 (except the fact rows are not tuples but lists so if you try to modify them, you will succeed instead of the correct behavior that would be that an exception would have been raised) Additionally every row returned by th...
As in DBAPI2.0 (except the fact rows are not tuples but lists so if you try to modify them, you will succeed instead of the correct behavior that would be that an exception would have been raised) Additionally every row returned by this class is addressable by column name besides...
Below is the the instruction that describes the task: ### Input: As in DBAPI2.0 (except the fact rows are not tuples but lists so if you try to modify them, you will succeed instead of the correct behavior that would be that an exception would have been raised) Additionally every row...
def pix2ang(nside, ipix, nest=False, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`.""" lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return _lonlat_to_healpy(lon, lat, lonlat=lonlat)
Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`.
Below is the the instruction that describes the task: ### Input: Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`. ### Response: def pix2ang(nside, ipix, nest=False, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`.""" lon, lat = healpix_to_lonlat(ipix, nside, order='n...
def distance_to_tile(self, point, direction, length = 50): """ Find nearest wall on a given bearing. Used for agent wall sensors. """ assert isinstance(point, eu.Vector2) assert isinstance(direction, int) or isinstance(direction, float) assert isinstance(length, i...
Find nearest wall on a given bearing. Used for agent wall sensors.
Below is the the instruction that describes the task: ### Input: Find nearest wall on a given bearing. Used for agent wall sensors. ### Response: def distance_to_tile(self, point, direction, length = 50): """ Find nearest wall on a given bearing. Used for agent wall sensors. ...
def provider_factory(factory=_sentinel, scope=NoneScope): ''' Decorator to create a provider using the given factory, and scope. Can also be used in a non-decorator manner. :param scope: Scope key, factory, or instance :type scope: object or callable :return: decorator :rtype: decorator ...
Decorator to create a provider using the given factory, and scope. Can also be used in a non-decorator manner. :param scope: Scope key, factory, or instance :type scope: object or callable :return: decorator :rtype: decorator
Below is the the instruction that describes the task: ### Input: Decorator to create a provider using the given factory, and scope. Can also be used in a non-decorator manner. :param scope: Scope key, factory, or instance :type scope: object or callable :return: decorator :rtype: decorator ### ...
def get_connection_state(self, connection: str) -> Dict[str, Any]: """ For an already established connection return its state. """ if connection not in self.connections: raise ConnectionNotOpen(connection) return self.connections[connection].state
For an already established connection return its state.
Below is the the instruction that describes the task: ### Input: For an already established connection return its state. ### Response: def get_connection_state(self, connection: str) -> Dict[str, Any]: """ For an already established connection return its state. """ if connection not...
def plot_sn_discovery_map(log, snSurveyDiscoveryTimes, peakAppMagList, snCampaignLengthList, redshifts, extraSurveyConstraints, pathToOutputPlotFolder): """ ...
*Plot the SN discoveries in a polar plot as function of redshift & time* **Key Arguments:** - ``log`` -- logger - ``snSurveyDiscoveryTimes`` -- - ``peakAppMagList`` -- - ``snCampaignLengthList`` -- a list of campaign lengths in each filter - ``redshifts`` -- - ``extr...
Below is the the instruction that describes the task: ### Input: *Plot the SN discoveries in a polar plot as function of redshift & time* **Key Arguments:** - ``log`` -- logger - ``snSurveyDiscoveryTimes`` -- - ``peakAppMagList`` -- - ``snCampaignLengthList`` -- a list of campai...
def update(self, result, spec): """Replace elements with results of calling callables.""" if isinstance(spec, dict): if spec: spec_value = next(iter(spec.values())) for key, value in result.items(): result[key] = self.update(value, spec_val...
Replace elements with results of calling callables.
Below is the the instruction that describes the task: ### Input: Replace elements with results of calling callables. ### Response: def update(self, result, spec): """Replace elements with results of calling callables.""" if isinstance(spec, dict): if spec: spec_value = n...
def _handle_execute_reply(self, msg): """ Reimplemented to handle communications between Spyder and the kernel """ msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) # unset reading flag, because if execute finished, raw_input...
Reimplemented to handle communications between Spyder and the kernel
Below is the the instruction that describes the task: ### Input: Reimplemented to handle communications between Spyder and the kernel ### Response: def _handle_execute_reply(self, msg): """ Reimplemented to handle communications between Spyder and the kernel """ msg_...
def _dump_inline_table(section): """Preserve inline table in its compact syntax instead of expanding into subsection. https://github.com/toml-lang/toml#user-content-inline-table """ retval = "" if isinstance(section, dict): val_list = [] for k, v in section.items(): ...
Preserve inline table in its compact syntax instead of expanding into subsection. https://github.com/toml-lang/toml#user-content-inline-table
Below is the the instruction that describes the task: ### Input: Preserve inline table in its compact syntax instead of expanding into subsection. https://github.com/toml-lang/toml#user-content-inline-table ### Response: def _dump_inline_table(section): """Preserve inline table in its compact syntax i...
def _get_internal_max_value(self): """ This is supposed to be only used by fitting engines to get the maximum value in internal representation. It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter :return: maximum value in inter...
This is supposed to be only used by fitting engines to get the maximum value in internal representation. It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter :return: maximum value in internal representation (or None if there is no minimum)
Below is the the instruction that describes the task: ### Input: This is supposed to be only used by fitting engines to get the maximum value in internal representation. It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter :return: maximum ...
def has_family_notes(family, data_dir=None): '''Check if notes exist for a given family Returns True if they exist, false otherwise ''' file_path = _family_notes_path(family, data_dir) return os.path.isfile(file_path)
Check if notes exist for a given family Returns True if they exist, false otherwise
Below is the the instruction that describes the task: ### Input: Check if notes exist for a given family Returns True if they exist, false otherwise ### Response: def has_family_notes(family, data_dir=None): '''Check if notes exist for a given family Returns True if they exist, false otherwise ''...
def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths): """ Get the cached commit times for the combination of this parent_dir and relpaths Return the commit assigned to this combination and the actual times! """ result = get_all_cached_commit_times(root_folder) for item in resu...
Get the cached commit times for the combination of this parent_dir and relpaths Return the commit assigned to this combination and the actual times!
Below is the the instruction that describes the task: ### Input: Get the cached commit times for the combination of this parent_dir and relpaths Return the commit assigned to this combination and the actual times! ### Response: def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths): """ ...
def decrease_frequency(self, frequency=None): """ Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int """ if frequency is None: javabridge.call(self.jobject, "decreaseFrequency", "()V") else: ...
Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int
Below is the the instruction that describes the task: ### Input: Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int ### Response: def decrease_frequency(self, frequency=None): """ Decreases the frequency. :param frequenc...
def valid(a, b): """Check whether `a` and `b` are not inf or nan""" return ~(np.isnan(a) | np.isinf(a) | np.isnan(b) | np.isinf(b))
Check whether `a` and `b` are not inf or nan
Below is the the instruction that describes the task: ### Input: Check whether `a` and `b` are not inf or nan ### Response: def valid(a, b): """Check whether `a` and `b` are not inf or nan""" return ~(np.isnan(a) | np.isinf(a) | np.isnan(b) | np.isinf(b))
def propagate(cls, date): """Compute the position of the sun at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the sun in MOD frame Example: .. code-block:: python from beyond.util...
Compute the position of the sun at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the sun in MOD frame Example: .. code-block:: python from beyond.utils.date import Date Su...
Below is the the instruction that describes the task: ### Input: Compute the position of the sun at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the sun in MOD frame Example: .. code-block:: python ...
def plot(self): """ Visualize the state. :return: The generated figure. :rtype: matplotlib.Figure """ width = 10 # The pleasing golden ratio. height = width / 1.618 f = plt.figure(figsize=(width, height)) ax = f.add_subplot(111, projection...
Visualize the state. :return: The generated figure. :rtype: matplotlib.Figure
Below is the the instruction that describes the task: ### Input: Visualize the state. :return: The generated figure. :rtype: matplotlib.Figure ### Response: def plot(self): """ Visualize the state. :return: The generated figure. :rtype: matplotlib.Figure ""...
def write_output(self, data, args=None, filename=None, label=None): """Write log data to a log file""" if args: if not args.outlog: return 0 if not filename: filename=args.outlog lastpath = '' with open(str(filename), 'w') as output_file: f...
Write log data to a log file
Below is the the instruction that describes the task: ### Input: Write log data to a log file ### Response: def write_output(self, data, args=None, filename=None, label=None): """Write log data to a log file""" if args: if not args.outlog: return 0 if not filenam...
def update_configuration(app): """Update parameters which are dependent on information from the project-specific conf.py (including its location on the filesystem)""" config = app.config project = config.project config_dir = app.env.srcdir sys.path.insert(0, os.path.join(config_dir, '..')) ...
Update parameters which are dependent on information from the project-specific conf.py (including its location on the filesystem)
Below is the the instruction that describes the task: ### Input: Update parameters which are dependent on information from the project-specific conf.py (including its location on the filesystem) ### Response: def update_configuration(app): """Update parameters which are dependent on information from the ...
def main(_): """Load a trained algorithm and render videos.""" utility.set_up_logging() if not FLAGS.logdir or not FLAGS.outdir: raise KeyError('You must specify logging and outdirs directories.') FLAGS.logdir = os.path.expanduser(FLAGS.logdir) FLAGS.outdir = os.path.expanduser(FLAGS.outdir) visualize( ...
Load a trained algorithm and render videos.
Below is the the instruction that describes the task: ### Input: Load a trained algorithm and render videos. ### Response: def main(_): """Load a trained algorithm and render videos.""" utility.set_up_logging() if not FLAGS.logdir or not FLAGS.outdir: raise KeyError('You must specify logging and outdirs ...
def _retry_on_connection_error(func: Callable) -> Callable: """Decorator to retry the function max_connection_attemps number of times. Herewith-decorated functions need an ``_attempt`` keyword argument. This is to decorate functions that do network requests that may fail. Note that :meth:`.get_json`, ...
Decorator to retry the function max_connection_attemps number of times. Herewith-decorated functions need an ``_attempt`` keyword argument. This is to decorate functions that do network requests that may fail. Note that :meth:`.get_json`, :meth:`.get_iphone_json`, :meth:`.graphql_query` and :meth:`.graphq...
Below is the the instruction that describes the task: ### Input: Decorator to retry the function max_connection_attemps number of times. Herewith-decorated functions need an ``_attempt`` keyword argument. This is to decorate functions that do network requests that may fail. Note that :meth:`.get_json`...
def calculate_angular_momentum(self): """ Returns a list of the three (x,y,z) components of the total angular momentum of all particles in the simulation. """ clibrebound.reb_tools_angular_momentum.restype = reb_vec3d L = clibrebound.reb_tools_angular_momentum(byref(self)) ...
Returns a list of the three (x,y,z) components of the total angular momentum of all particles in the simulation.
Below is the the instruction that describes the task: ### Input: Returns a list of the three (x,y,z) components of the total angular momentum of all particles in the simulation. ### Response: def calculate_angular_momentum(self): """ Returns a list of the three (x,y,z) components of the total angul...
def get_reservation_resources(session, reservation_id, *models): """ Get all resources of given models in reservation. :param session: CloudShell session :type session: cloudshell.api.cloudshell_api.CloudShellAPISession :param reservation_id: active reservation ID :param models: list of requested m...
Get all resources of given models in reservation. :param session: CloudShell session :type session: cloudshell.api.cloudshell_api.CloudShellAPISession :param reservation_id: active reservation ID :param models: list of requested models :return: list of all resources of models in reservation
Below is the the instruction that describes the task: ### Input: Get all resources of given models in reservation. :param session: CloudShell session :type session: cloudshell.api.cloudshell_api.CloudShellAPISession :param reservation_id: active reservation ID :param models: list of requested model...
def _check_instrument(self): """Check and try fix instrument name if needed""" instr = INSTRUMENTS.get(self.platform_name, self.instrument.lower()) if instr != self.instrument.lower(): self.instrument = instr LOG.warning("Inconsistent instrument/satellite input - " + ...
Check and try fix instrument name if needed
Below is the the instruction that describes the task: ### Input: Check and try fix instrument name if needed ### Response: def _check_instrument(self): """Check and try fix instrument name if needed""" instr = INSTRUMENTS.get(self.platform_name, self.instrument.lower()) if instr != self.ins...
def _context_build(self, pending=False): """ Create a context dict from standard task configuration. The context is constructed in a standard way and is passed to str.format() on configuration. The context consists of the entire os.environ, the config 'defines', and a set of pre...
Create a context dict from standard task configuration. The context is constructed in a standard way and is passed to str.format() on configuration. The context consists of the entire os.environ, the config 'defines', and a set of pre-defined values which have a common prefix from 'context_pref...
Below is the the instruction that describes the task: ### Input: Create a context dict from standard task configuration. The context is constructed in a standard way and is passed to str.format() on configuration. The context consists of the entire os.environ, the config 'defines', and a set ...
def get_client_info(self): """ A query is sent to the server to obtain the client's data stored at the server. :return: :class:`~aioxmpp.ibr.Query` """ iq = aioxmpp.IQ( to=self.client.local_jid.bare().replace(localpart=None), type_=aioxmpp.IQType....
A query is sent to the server to obtain the client's data stored at the server. :return: :class:`~aioxmpp.ibr.Query`
Below is the the instruction that describes the task: ### Input: A query is sent to the server to obtain the client's data stored at the server. :return: :class:`~aioxmpp.ibr.Query` ### Response: def get_client_info(self): """ A query is sent to the server to obtain the client's da...
def get_unpacked_response_body(self, requestId, mimetype="application/unknown"): ''' Return a unpacked, decoded resposne body from Network_getResponseBody() ''' content = self.Network_getResponseBody(requestId) assert 'result' in content result = content['result'] assert 'base64Encoded' in result asse...
Return a unpacked, decoded resposne body from Network_getResponseBody()
Below is the the instruction that describes the task: ### Input: Return a unpacked, decoded resposne body from Network_getResponseBody() ### Response: def get_unpacked_response_body(self, requestId, mimetype="application/unknown"): ''' Return a unpacked, decoded resposne body from Network_getResponseBody() '...
def register(): """View function which handles a registration request.""" if _security.confirmable or request.is_json: form_class = _security.confirm_register_form else: form_class = _security.register_form if request.is_json: form_data = MultiDict(request.get_json()) else:...
View function which handles a registration request.
Below is the the instruction that describes the task: ### Input: View function which handles a registration request. ### Response: def register(): """View function which handles a registration request.""" if _security.confirmable or request.is_json: form_class = _security.confirm_register_form ...
def is_secret_known( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> bool: """True if the `secrethash` is for a lock with a known secret.""" return ( secrethash in end_state.secrethashes_to_unlockedlocks or secrethash in end_state.secrethashes_to_onchain_unlockedl...
True if the `secrethash` is for a lock with a known secret.
Below is the the instruction that describes the task: ### Input: True if the `secrethash` is for a lock with a known secret. ### Response: def is_secret_known( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> bool: """True if the `secrethash` is for a lock with a known secret."""...
def get_positions(self): """ Returns a list of positions. http://dev.wheniwork.com/#listing-positions """ url = "/2/positions" data = self._get_resource(url) positions = [] for entry in data['positions']: positions.append(self.position_from_j...
Returns a list of positions. http://dev.wheniwork.com/#listing-positions
Below is the the instruction that describes the task: ### Input: Returns a list of positions. http://dev.wheniwork.com/#listing-positions ### Response: def get_positions(self): """ Returns a list of positions. http://dev.wheniwork.com/#listing-positions """ url = "...
def to_dict_list_generic_type(df, int_col=None, binary_col=None): """Transform each row to dict, and put them into a list. And automatically convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to ``datetime.datetime``, ``np.nan`` to ``None``. :param df: ``pandas.DataFrame`` instance. :para...
Transform each row to dict, and put them into a list. And automatically convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to ``datetime.datetime``, ``np.nan`` to ``None``. :param df: ``pandas.DataFrame`` instance. :param int_col: integer type columns. :param binary_col: binary type type ...
Below is the the instruction that describes the task: ### Input: Transform each row to dict, and put them into a list. And automatically convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to ``datetime.datetime``, ``np.nan`` to ``None``. :param df: ``pandas.DataFrame`` instance. :param in...
def _build_saveframe(self, lexer): """Build NMR-STAR file saveframe. :param lexer: instance of the lexical analyzer. :type lexer: :func:`~nmrstarlib.bmrblex.bmrblex` :return: Saveframe dictionary. :rtype: :py:class:`collections.OrderedDict` """ odict = OrderedDic...
Build NMR-STAR file saveframe. :param lexer: instance of the lexical analyzer. :type lexer: :func:`~nmrstarlib.bmrblex.bmrblex` :return: Saveframe dictionary. :rtype: :py:class:`collections.OrderedDict`
Below is the the instruction that describes the task: ### Input: Build NMR-STAR file saveframe. :param lexer: instance of the lexical analyzer. :type lexer: :func:`~nmrstarlib.bmrblex.bmrblex` :return: Saveframe dictionary. :rtype: :py:class:`collections.OrderedDict` ### Response: ...
def update_attribute_group(attributegroup, **kwargs): """ Add a new attribute group. An attribute group is a container for attributes which need to be grouped in some logical way. For example, if the 'attr_is_var' flag isn't expressive enough to delineate different groupings. ...
Add a new attribute group. An attribute group is a container for attributes which need to be grouped in some logical way. For example, if the 'attr_is_var' flag isn't expressive enough to delineate different groupings. an attribute group looks like: { 'proje...
Below is the the instruction that describes the task: ### Input: Add a new attribute group. An attribute group is a container for attributes which need to be grouped in some logical way. For example, if the 'attr_is_var' flag isn't expressive enough to delineate different groupings. ...
def _process_gradient_args(f, kwargs): """Handle common processing of arguments for gradient and gradient-like functions.""" axes = kwargs.get('axes', range(f.ndim)) def _check_length(positions): if 'axes' in kwargs and len(positions) < len(axes): raise ValueError('Length of "coordinate...
Handle common processing of arguments for gradient and gradient-like functions.
Below is the the instruction that describes the task: ### Input: Handle common processing of arguments for gradient and gradient-like functions. ### Response: def _process_gradient_args(f, kwargs): """Handle common processing of arguments for gradient and gradient-like functions.""" axes = kwargs.get('axes...
def cat(self, paths, check_crc=False): ''' Fetch all files that match the source file pattern and display their content on stdout. :param paths: Paths to display :type paths: list of strings :param check_crc: Check for checksum errors :type check_crc: boolean :re...
Fetch all files that match the source file pattern and display their content on stdout. :param paths: Paths to display :type paths: list of strings :param check_crc: Check for checksum errors :type check_crc: boolean :returns: a generator that yields strings
Below is the the instruction that describes the task: ### Input: Fetch all files that match the source file pattern and display their content on stdout. :param paths: Paths to display :type paths: list of strings :param check_crc: Check for checksum errors :type check_crc: b...
def CreateSms(self, MessageType, *TargetNumbers): """Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers. :return: An sms message object. :rtype: `SmsMess...
Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers. :return: An sms message object. :rtype: `SmsMessage`
Below is the the instruction that describes the task: ### Input: Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers. :return: An sms message object. :rtype: ...
def sbo_version(self, repo, find): """ Add version to SBo packages """ ver = "" if repo == "sbo": ver = "-" + SBoGrep(find).version() return ver
Add version to SBo packages
Below is the the instruction that describes the task: ### Input: Add version to SBo packages ### Response: def sbo_version(self, repo, find): """ Add version to SBo packages """ ver = "" if repo == "sbo": ver = "-" + SBoGrep(find).version() return ver
def send_command(self, obj, command, *arguments): """ Send command and do not parse output (except for communication errors). :param obj: requested object. :param command: command to send. :param arguments: list of command arguments. """ index_command = obj._build_index_...
Send command and do not parse output (except for communication errors). :param obj: requested object. :param command: command to send. :param arguments: list of command arguments.
Below is the the instruction that describes the task: ### Input: Send command and do not parse output (except for communication errors). :param obj: requested object. :param command: command to send. :param arguments: list of command arguments. ### Response: def send_command(self, obj, com...
def integrate_days(self, days=1.0, verbose=True): """Integrates the model forward for a specified number of days. It convertes the given number of days into years and calls :func:`integrate_years`. :param float days: integration time for the model in days ...
Integrates the model forward for a specified number of days. It convertes the given number of days into years and calls :func:`integrate_years`. :param float days: integration time for the model in days [default: 1.0] :param bool verbose: informa...
Below is the the instruction that describes the task: ### Input: Integrates the model forward for a specified number of days. It convertes the given number of days into years and calls :func:`integrate_years`. :param float days: integration time for the model in days ...
def generate_plaintext_random(plain_vocab, distribution, train_samples, length): """Generates samples of text from the provided vocabulary. Args: plain_vocab: vocabulary. distribution: distribution. train_samples: samples for training. length: length. Returns: t...
Generates samples of text from the provided vocabulary. Args: plain_vocab: vocabulary. distribution: distribution. train_samples: samples for training. length: length. Returns: train_indices (np.array of Integers): random integers for training. shape = [num_samples, length] test_indi...
Below is the the instruction that describes the task: ### Input: Generates samples of text from the provided vocabulary. Args: plain_vocab: vocabulary. distribution: distribution. train_samples: samples for training. length: length. Returns: train_indices (np.array of Integers): random int...
def reload(self): """Reload the metadata for this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_reload_cluster] :end-before: [END bigtable_reload_cluster] """ cluster_pb = self._instance._client.instance_admin_client...
Reload the metadata for this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_reload_cluster] :end-before: [END bigtable_reload_cluster]
Below is the the instruction that describes the task: ### Input: Reload the metadata for this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_reload_cluster] :end-before: [END bigtable_reload_cluster] ### Response: def reload(self): ...
def sequence(values): """ Wrap a list of Python values as an Ibis sequence type Parameters ---------- values : list Should all be None or the same type Returns ------- seq : Sequence """ import ibis.expr.operations as ops return ops.ValueList(values).to_expr()
Wrap a list of Python values as an Ibis sequence type Parameters ---------- values : list Should all be None or the same type Returns ------- seq : Sequence
Below is the the instruction that describes the task: ### Input: Wrap a list of Python values as an Ibis sequence type Parameters ---------- values : list Should all be None or the same type Returns ------- seq : Sequence ### Response: def sequence(values): """ Wrap a list o...
def subjects_download(self, subject_id): """Get data file for subject with given identifier. Parameters ---------- subject_id : string Unique subject identifier Returns ------- FileInfo Information about subject's data file on disk or Non...
Get data file for subject with given identifier. Parameters ---------- subject_id : string Unique subject identifier Returns ------- FileInfo Information about subject's data file on disk or None if identifier is unknown
Below is the the instruction that describes the task: ### Input: Get data file for subject with given identifier. Parameters ---------- subject_id : string Unique subject identifier Returns ------- FileInfo Information about subject's data fi...
def _set_advertisement_interval(self, v, load=False): """ Setter method for advertisement_interval, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/neighbor/af_ipv4_vrf_neighbor_address_holder/af_ipv4_neighbor_addr/advertisement_interval (container) If thi...
Setter method for advertisement_interval, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/neighbor/af_ipv4_vrf_neighbor_address_holder/af_ipv4_neighbor_addr/advertisement_interval (container) If this variable is read-only (config: false) in the source YANG fil...
Below is the the instruction that describes the task: ### Input: Setter method for advertisement_interval, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/neighbor/af_ipv4_vrf_neighbor_address_holder/af_ipv4_neighbor_addr/advertisement_interval (container) If ...
def datetime_at_loc(self, loc): """Returns the timestamp at the given integer location as a Pandas Timestamp.""" return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.dateTimeAtLoc(loc)))
Returns the timestamp at the given integer location as a Pandas Timestamp.
Below is the the instruction that describes the task: ### Input: Returns the timestamp at the given integer location as a Pandas Timestamp. ### Response: def datetime_at_loc(self, loc): """Returns the timestamp at the given integer location as a Pandas Timestamp.""" return pd.Timestamp(self._zdt_to...
def variable( self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None): """returns reference to variable declaration, that is matched defined criteria""" return ( ...
returns reference to variable declaration, that is matched defined criteria
Below is the the instruction that describes the task: ### Input: returns reference to variable declaration, that is matched defined criteria ### Response: def variable( self, name=None, function=None, decl_type=None, header_dir=None, h...
def save(self, commit=True): """Save and send""" contact = super(ContactFormBase, self).save() context = {'contact': contact} context.update(get_site_metas()) subject = ''.join(render_to_string(self.mail_subject_template, context).splitlines()) content = render_to_string...
Save and send
Below is the the instruction that describes the task: ### Input: Save and send ### Response: def save(self, commit=True): """Save and send""" contact = super(ContactFormBase, self).save() context = {'contact': contact} context.update(get_site_metas()) subject = ''.join(rend...