code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def collection_callback(result=None): """ :type result: opendnp3.CommandPointResult """ print("Header: {0} | Index: {1} | State: {2} | Status: {3}".format( result.headerIndex, result.index, opendnp3.CommandPointStateToString(result.state), opendnp3.CommandStatusToString...
:type result: opendnp3.CommandPointResult
Below is the the instruction that describes the task: ### Input: :type result: opendnp3.CommandPointResult ### Response: def collection_callback(result=None): """ :type result: opendnp3.CommandPointResult """ print("Header: {0} | Index: {1} | State: {2} | Status: {3}".format( result.heade...
def find_label(self, label: Label): """ Helper function that iterates over the program and looks for a JumpTarget that has a Label matching the input label. :param label: Label object to search for in program :return: Program index where ``label`` is found """ fo...
Helper function that iterates over the program and looks for a JumpTarget that has a Label matching the input label. :param label: Label object to search for in program :return: Program index where ``label`` is found
Below is the the instruction that describes the task: ### Input: Helper function that iterates over the program and looks for a JumpTarget that has a Label matching the input label. :param label: Label object to search for in program :return: Program index where ``label`` is found ### Respo...
def wallet_contains(self, wallet, account): """ Check whether **wallet** contains **account** :param wallet: Wallet to check contains **account** :type wallet: str :param account: Account to check exists in **wallet** :type account: str :raises: :py:exc:`nano.r...
Check whether **wallet** contains **account** :param wallet: Wallet to check contains **account** :type wallet: str :param account: Account to check exists in **wallet** :type account: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_contains( ... ...
Below is the the instruction that describes the task: ### Input: Check whether **wallet** contains **account** :param wallet: Wallet to check contains **account** :type wallet: str :param account: Account to check exists in **wallet** :type account: str :raises: :py:exc:`n...
def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(TextEntry, self).to_api_repr() info["textPayload"] = self.payload return info
API repr (JSON format) for entry.
Below is the the instruction that describes the task: ### Input: API repr (JSON format) for entry. ### Response: def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(TextEntry, self).to_api_repr() info["textPayload"] = self.payload return info
def _check_psutil(self, instance): """ Gather metrics about connections states and interfaces counters using psutil facilities """ custom_tags = instance.get('tags', []) if self._collect_cx_state: self._cx_state_psutil(tags=custom_tags) self._cx_count...
Gather metrics about connections states and interfaces counters using psutil facilities
Below is the the instruction that describes the task: ### Input: Gather metrics about connections states and interfaces counters using psutil facilities ### Response: def _check_psutil(self, instance): """ Gather metrics about connections states and interfaces counters using psutil ...
def locate_files(root_dir): """Find all python files in the given directory and all subfolders.""" all_files = [] root_dir = os.path.abspath(root_dir) for dir_name, subdirs, files in os.walk(root_dir): for f in files: if f.endswith(".py"): all_files.append(os.path.joi...
Find all python files in the given directory and all subfolders.
Below is the the instruction that describes the task: ### Input: Find all python files in the given directory and all subfolders. ### Response: def locate_files(root_dir): """Find all python files in the given directory and all subfolders.""" all_files = [] root_dir = os.path.abspath(root_dir) for ...
def htmlprint(*values, plain=None, **options): """ Convert HTML to VTML and then print it. Follows same semantics as vtmlprint. """ print(*[htmlrender(x, plain=plain) for x in values], **options)
Convert HTML to VTML and then print it. Follows same semantics as vtmlprint.
Below is the the instruction that describes the task: ### Input: Convert HTML to VTML and then print it. Follows same semantics as vtmlprint. ### Response: def htmlprint(*values, plain=None, **options): """ Convert HTML to VTML and then print it. Follows same semantics as vtmlprint. """ print(*[htm...
def delete(self, obj, force=False): """Deletes all of the fields at the specified locations. args: ``obj=``\ *OBJECT* the object to remove the fields from ``force=``\ *BOOL* if True, missing attributes do not raise errors. Otherwise, ...
Deletes all of the fields at the specified locations. args: ``obj=``\ *OBJECT* the object to remove the fields from ``force=``\ *BOOL* if True, missing attributes do not raise errors. Otherwise, the first failure raises an exception wit...
Below is the the instruction that describes the task: ### Input: Deletes all of the fields at the specified locations. args: ``obj=``\ *OBJECT* the object to remove the fields from ``force=``\ *BOOL* if True, missing attributes do not raise errors. ...
def compute_discounts(self, precision=None): ''' Returns the total amount of discounts for this line with a specific number of decimals. @param precision:int number of decimal places @return: Decimal ''' gross = self.compute_gross(precision) return min(gro...
Returns the total amount of discounts for this line with a specific number of decimals. @param precision:int number of decimal places @return: Decimal
Below is the the instruction that describes the task: ### Input: Returns the total amount of discounts for this line with a specific number of decimals. @param precision:int number of decimal places @return: Decimal ### Response: def compute_discounts(self, precision=None): ''' ...
def generate_records(self, infile): """ Process a file of rest and yield dictionaries """ state = 0 record = {} for item in self.generate_lines(infile): line = item['line'] heading = item['heading'] # any Markdown heading is just a capt...
Process a file of rest and yield dictionaries
Below is the the instruction that describes the task: ### Input: Process a file of rest and yield dictionaries ### Response: def generate_records(self, infile): """ Process a file of rest and yield dictionaries """ state = 0 record = {} for item in self.generate_lines(infile): ...
def ls(obj=None, case_sensitive=False, verbose=False): """List available layers, or infos on a given layer class or name. params: - obj: Packet / packet name to use - case_sensitive: if obj is a string, is it case sensitive? - verbose """ is_string = isinstance(obj, six.string_types) ...
List available layers, or infos on a given layer class or name. params: - obj: Packet / packet name to use - case_sensitive: if obj is a string, is it case sensitive? - verbose
Below is the the instruction that describes the task: ### Input: List available layers, or infos on a given layer class or name. params: - obj: Packet / packet name to use - case_sensitive: if obj is a string, is it case sensitive? - verbose ### Response: def ls(obj=None, case_sensitive=False, ...
def ftp_connect(self, host, user='anonymous', password='anonymous@', port=21, timeout=30, connId='default'): """ Constructs FTP object, opens a connection and login. Call this function before any other (otherwise raises exception). Returns server output. Parameters: -...
Constructs FTP object, opens a connection and login. Call this function before any other (otherwise raises exception). Returns server output. Parameters: - host - server host address - user(optional) - FTP user name. If not given, 'anonymous' is used. - passwo...
Below is the the instruction that describes the task: ### Input: Constructs FTP object, opens a connection and login. Call this function before any other (otherwise raises exception). Returns server output. Parameters: - host - server host address - user(optional) - F...
def DFS(G): """ Algorithm for depth-first searching the vertices of a graph. """ if not G.vertices: raise GraphInsertError("This graph have no vertices.") color = {} pred = {} reach = {} finish = {} def DFSvisit(G, current, time): color[current] = 'grey' ...
Algorithm for depth-first searching the vertices of a graph.
Below is the the instruction that describes the task: ### Input: Algorithm for depth-first searching the vertices of a graph. ### Response: def DFS(G): """ Algorithm for depth-first searching the vertices of a graph. """ if not G.vertices: raise GraphInsertError("This graph have no ver...
def bel_edges( self, nanopub: Mapping[str, Any], namespace_targets: Mapping[str, List[str]] = {}, rules: List[str] = [], orthologize_target: str = None, ) -> List[Mapping[str, Any]]: """Create BEL Edges from BEL nanopub Args: nanopub (Mapping[str,...
Create BEL Edges from BEL nanopub Args: nanopub (Mapping[str, Any]): bel nanopub namespace_targets (Mapping[str, List[str]]): what namespaces to canonicalize rules (List[str]): which computed edge rules to process, default is all, look at BEL Specification yam...
Below is the the instruction that describes the task: ### Input: Create BEL Edges from BEL nanopub Args: nanopub (Mapping[str, Any]): bel nanopub namespace_targets (Mapping[str, List[str]]): what namespaces to canonicalize rules (List[str]): which computed edge rules to ...
def chebyshev(h1, h2): # 12 us @array, 36 us @list \w 100 bins r""" Chebyshev distance. Also Tchebychev distance, Maximum or :math:`L_{\infty}` metric; equal to Minowski distance with :math:`p=+\infty`. For the case of :math:`p=-\infty`, use `chebyshev_neg`. The Chebyshev distance between ...
r""" Chebyshev distance. Also Tchebychev distance, Maximum or :math:`L_{\infty}` metric; equal to Minowski distance with :math:`p=+\infty`. For the case of :math:`p=-\infty`, use `chebyshev_neg`. The Chebyshev distance between two histograms :math:`H` and :math:`H'` of size :math:`m` is de...
Below is the the instruction that describes the task: ### Input: r""" Chebyshev distance. Also Tchebychev distance, Maximum or :math:`L_{\infty}` metric; equal to Minowski distance with :math:`p=+\infty`. For the case of :math:`p=-\infty`, use `chebyshev_neg`. The Chebyshev distance betwee...
def _update_axes_color(self, color): """Internal helper to set the axes label color""" prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty() prop_y = self.axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty() prop_z = self.axes_actor.GetZAxisCaptionActor2D().G...
Internal helper to set the axes label color
Below is the the instruction that describes the task: ### Input: Internal helper to set the axes label color ### Response: def _update_axes_color(self, color): """Internal helper to set the axes label color""" prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty() prop_y...
def make_population(population_size, solution_generator, *args, **kwargs): """Make a population with the supplied generator.""" return [ solution_generator(*args, **kwargs) for _ in range(population_size) ]
Make a population with the supplied generator.
Below is the the instruction that describes the task: ### Input: Make a population with the supplied generator. ### Response: def make_population(population_size, solution_generator, *args, **kwargs): """Make a population with the supplied generator.""" return [ solution_generator(*args, **kwargs) ...
def depth_first_iter(self, self_first=True): """ Iterate over nodes below this node, optionally yielding children before self. """ if self_first: yield self for child in list(self.children): for i in child.depth_first_iter(self_first): ...
Iterate over nodes below this node, optionally yielding children before self.
Below is the the instruction that describes the task: ### Input: Iterate over nodes below this node, optionally yielding children before self. ### Response: def depth_first_iter(self, self_first=True): """ Iterate over nodes below this node, optionally yielding children before self....
def get_site_type_dummy_variables(self, sites): """ Binary rock/soil classification dummy variable based on sites.vs30. "``S`` is 1 for a rock site and 0 otherwise" (p. 1201). """ is_rock = np.array(sites.vs30 > self.NEHRP_BC_BOUNDARY) return is_rock
Binary rock/soil classification dummy variable based on sites.vs30. "``S`` is 1 for a rock site and 0 otherwise" (p. 1201).
Below is the the instruction that describes the task: ### Input: Binary rock/soil classification dummy variable based on sites.vs30. "``S`` is 1 for a rock site and 0 otherwise" (p. 1201). ### Response: def get_site_type_dummy_variables(self, sites): """ Binary rock/soil classification dum...
def remove_service(self, service): """Removes the service passed in from the services offered by the current Profile. If the Analysis Service passed in is not assigned to this Analysis Profile, returns False. :param service: the service to be removed from this Analysis Profile :t...
Removes the service passed in from the services offered by the current Profile. If the Analysis Service passed in is not assigned to this Analysis Profile, returns False. :param service: the service to be removed from this Analysis Profile :type service: AnalysisService :return: ...
Below is the the instruction that describes the task: ### Input: Removes the service passed in from the services offered by the current Profile. If the Analysis Service passed in is not assigned to this Analysis Profile, returns False. :param service: the service to be removed from this Anal...
def get(cls, name, raise_exc=True): """ Get the element by name. Does an exact match by element type. :param str name: name of element :param bool raise_exc: optionally disable exception. :raises ElementNotFound: if element does not exist :rtype: Element ...
Get the element by name. Does an exact match by element type. :param str name: name of element :param bool raise_exc: optionally disable exception. :raises ElementNotFound: if element does not exist :rtype: Element
Below is the the instruction that describes the task: ### Input: Get the element by name. Does an exact match by element type. :param str name: name of element :param bool raise_exc: optionally disable exception. :raises ElementNotFound: if element does not exist :rtype: El...
def clear(self, flush=True): """ Args: flush(bool): Flush stream after clearing progress bar (Default:True) Clear progress bar """ if self.enabled: self.manager.write(flush=flush, position=self.position)
Args: flush(bool): Flush stream after clearing progress bar (Default:True) Clear progress bar
Below is the the instruction that describes the task: ### Input: Args: flush(bool): Flush stream after clearing progress bar (Default:True) Clear progress bar ### Response: def clear(self, flush=True): """ Args: flush(bool): Flush stream after clearing progress bar ...
def build_ctx(pythonpath=None): """ Decorator that makes decorated function use BuildContext instead of \ Context instance. BuildContext instance has more methods. :param pythonpath: Path or list of paths to add to environment variable PYTHONPATH. Each path can be absolute path, or relative pat...
Decorator that makes decorated function use BuildContext instead of \ Context instance. BuildContext instance has more methods. :param pythonpath: Path or list of paths to add to environment variable PYTHONPATH. Each path can be absolute path, or relative path relative to top directory. ...
Below is the the instruction that describes the task: ### Input: Decorator that makes decorated function use BuildContext instead of \ Context instance. BuildContext instance has more methods. :param pythonpath: Path or list of paths to add to environment variable PYTHONPATH. Each path can be absol...
def get_context(template, line, num_lines=5, marker=None): ''' Returns debugging context around a line in a given string Returns:: string ''' template_lines = template.splitlines() num_template_lines = len(template_lines) # In test mode, a single line template would return a crazy line num...
Returns debugging context around a line in a given string Returns:: string
Below is the the instruction that describes the task: ### Input: Returns debugging context around a line in a given string Returns:: string ### Response: def get_context(template, line, num_lines=5, marker=None): ''' Returns debugging context around a line in a given string Returns:: string '...
def _prep_non_framed(self): """Prepare the opening data for a non-framed message.""" try: plaintext_length = self.stream_length self.__unframed_plaintext_cache = self.source_stream except NotSupportedError: # We need to know the plaintext length before we can ...
Prepare the opening data for a non-framed message.
Below is the the instruction that describes the task: ### Input: Prepare the opening data for a non-framed message. ### Response: def _prep_non_framed(self): """Prepare the opening data for a non-framed message.""" try: plaintext_length = self.stream_length self.__unframed_p...
def list_devices(): """ List devices via HTTP GET. """ output = {} for device_id, device in devices.items(): output[device_id] = { 'host': device.host, 'state': device.state } return jsonify(devices=output)
List devices via HTTP GET.
Below is the the instruction that describes the task: ### Input: List devices via HTTP GET. ### Response: def list_devices(): """ List devices via HTTP GET. """ output = {} for device_id, device in devices.items(): output[device_id] = { 'host': device.host, 'state': devi...
def _extract_links_from_asset_tags_in_text(self, text): """ Scan the text and extract asset tags and links to corresponding files. @param text: Page text. @type text: str @return: @see CourseraOnDemand._extract_links_from_text """ # Extract asset tags fr...
Scan the text and extract asset tags and links to corresponding files. @param text: Page text. @type text: str @return: @see CourseraOnDemand._extract_links_from_text
Below is the the instruction that describes the task: ### Input: Scan the text and extract asset tags and links to corresponding files. @param text: Page text. @type text: str @return: @see CourseraOnDemand._extract_links_from_text ### Response: def _extract_links_from_asset_tags_...
def lms(): '''Install and start a Logitech Media Server (lms). More infos: * http://wiki.slimdevices.com/index.php/Logitech_Media_Server * http://wiki.slimdevices.com/index.php/DebianPackage * http://www.mysqueezebox.com/download * XSqueeze on Kodi: * http://kodi.wiki/view/Add-on:XSq...
Install and start a Logitech Media Server (lms). More infos: * http://wiki.slimdevices.com/index.php/Logitech_Media_Server * http://wiki.slimdevices.com/index.php/DebianPackage * http://www.mysqueezebox.com/download * XSqueeze on Kodi: * http://kodi.wiki/view/Add-on:XSqueeze * htt...
Below is the the instruction that describes the task: ### Input: Install and start a Logitech Media Server (lms). More infos: * http://wiki.slimdevices.com/index.php/Logitech_Media_Server * http://wiki.slimdevices.com/index.php/DebianPackage * http://www.mysqueezebox.com/download * XSqueeze...
def download_SRA(self, email, directory='series', filterby=None, nproc=1, **kwargs): """Download SRA files for each GSM in series. .. warning:: Do not use parallel option (nproc > 1) in the interactive shell. For more details see `this issue <https://stacko...
Download SRA files for each GSM in series. .. warning:: Do not use parallel option (nproc > 1) in the interactive shell. For more details see `this issue <https://stackoverflow.com/questions/23641475/multiprocessing-working-in-python-but-not-in-ipython/23641560#23641560>`_ ...
Below is the the instruction that describes the task: ### Input: Download SRA files for each GSM in series. .. warning:: Do not use parallel option (nproc > 1) in the interactive shell. For more details see `this issue <https://stackoverflow.com/questions/23641475/multiprocessing-w...
def analyze_event_rate(scan_base, combine_n_readouts=1000, time_line_absolute=True, output_pdf=None, output_file=None): ''' Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the meta data i...
Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the meta data info and stored into a pdf file. Parameters ---------- scan_base: list of str scan base names (e.g.: ['...
Below is the the instruction that describes the task: ### Input: Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the meta data info and stored into a pdf file. Parameters ---...
def classical_damage( fragility_functions, hazard_imls, hazard_poes, investigation_time, risk_investigation_time): """ :param fragility_functions: a list of fragility functions for each damage state :param hazard_imls: Intensity Measure Levels :param hazard_poes: ...
:param fragility_functions: a list of fragility functions for each damage state :param hazard_imls: Intensity Measure Levels :param hazard_poes: hazard curve :param investigation_time: hazard investigation time :param risk_investigation_time: risk investigation ti...
Below is the the instruction that describes the task: ### Input: :param fragility_functions: a list of fragility functions for each damage state :param hazard_imls: Intensity Measure Levels :param hazard_poes: hazard curve :param investigation_time: hazard investigation t...
def to_gufunc_string(self): """Create an equivalent signature string for a NumPy gufunc. Unlike __str__, handles dimensions that don't map to Python identifiers. """ all_dims = self.all_core_dims dims_map = dict(zip(sorted(all_dims), range(len(all_dims)))) input_...
Create an equivalent signature string for a NumPy gufunc. Unlike __str__, handles dimensions that don't map to Python identifiers.
Below is the the instruction that describes the task: ### Input: Create an equivalent signature string for a NumPy gufunc. Unlike __str__, handles dimensions that don't map to Python identifiers. ### Response: def to_gufunc_string(self): """Create an equivalent signature string for a NumPy...
def delete_queue(name, region, opts=None, user=None): ''' Deletes a queue in the region. name Name of the SQS queue to deletes region Name of the region to delete the queue from opts : None Any additional options to add to the command line user : None Run hg as...
Deletes a queue in the region. name Name of the SQS queue to deletes region Name of the region to delete the queue from opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as CLI Example: ...
Below is the the instruction that describes the task: ### Input: Deletes a queue in the region. name Name of the SQS queue to deletes region Name of the region to delete the queue from opts : None Any additional options to add to the command line user : None Run hg...
def mgl_seq(x): """ Sequence whose sum is the Madhava-Gregory-Leibniz series. [x, -x^3/3, x^5/5, -x^7/7, x^9/9, -x^11/11, ...] Returns ------- An endless sequence that has the property ``atan(x) = sum(mgl_seq(x))``. Usually you would use the ``atan()`` function, not this one. """ odd_num...
Sequence whose sum is the Madhava-Gregory-Leibniz series. [x, -x^3/3, x^5/5, -x^7/7, x^9/9, -x^11/11, ...] Returns ------- An endless sequence that has the property ``atan(x) = sum(mgl_seq(x))``. Usually you would use the ``atan()`` function, not this one.
Below is the the instruction that describes the task: ### Input: Sequence whose sum is the Madhava-Gregory-Leibniz series. [x, -x^3/3, x^5/5, -x^7/7, x^9/9, -x^11/11, ...] Returns ------- An endless sequence that has the property ``atan(x) = sum(mgl_seq(x))``. Usually you would use the ``atan...
def launch_request(self, uri_pattern, body, method, headers=None, parameters=None, **kwargs): """ Launch HTTP request to the API with given arguments :param uri_pattern: string pattern of the full API url with keyword arguments (format string syntax) :param body: Raw Body content (string...
Launch HTTP request to the API with given arguments :param uri_pattern: string pattern of the full API url with keyword arguments (format string syntax) :param body: Raw Body content (string) (Plain/XML/JSON to be sent) :param method: HTTP ver to be used in the request [GET | POST | PUT | DELETE...
Below is the the instruction that describes the task: ### Input: Launch HTTP request to the API with given arguments :param uri_pattern: string pattern of the full API url with keyword arguments (format string syntax) :param body: Raw Body content (string) (Plain/XML/JSON to be sent) :param ...
def main(argv): """Main """ parameters = process_arguments(argv) file_list = sed_eval.io.load_file_pair_list(parameters['file_list']) path = os.path.dirname(parameters['file_list']) data = [] all_data = dcase_util.containers.MetaDataContainer() for file_pair in file_list: refer...
Main
Below is the the instruction that describes the task: ### Input: Main ### Response: def main(argv): """Main """ parameters = process_arguments(argv) file_list = sed_eval.io.load_file_pair_list(parameters['file_list']) path = os.path.dirname(parameters['file_list']) data = [] all_data ...
def access(self, app_subdomain): ''' a method to validate user can access app ''' title = '%s.access' % self.__class__.__name__ # validate input input_fields = { 'app_subdomain': app_subdomain } for key, value in input_fields.items(): ...
a method to validate user can access app
Below is the the instruction that describes the task: ### Input: a method to validate user can access app ### Response: def access(self, app_subdomain): ''' a method to validate user can access app ''' title = '%s.access' % self.__class__.__name__ # validate input input_fi...
def interruptWrite(self, endpoint, buffer, timeout = 100): r"""Perform a interrupt write request to the endpoint specified. Arguments: endpoint: endpoint number. buffer: sequence data buffer to write. This parameter can be any sequence type. ...
r"""Perform a interrupt write request to the endpoint specified. Arguments: endpoint: endpoint number. buffer: sequence data buffer to write. This parameter can be any sequence type. timeout: operation timeout in milliseconds. (default...
Below is the the instruction that describes the task: ### Input: r"""Perform a interrupt write request to the endpoint specified. Arguments: endpoint: endpoint number. buffer: sequence data buffer to write. This parameter can be any sequence type....
def flattened(self): """return flattened data ``(x, f)`` such that for the sweep through coordinate ``i`` we have for data point ``j`` that ``f[i][j] == func(x[i][j])`` """ flatx = {} flatf = {} for i in self.res: if isinstance(i, int): flatx[...
return flattened data ``(x, f)`` such that for the sweep through coordinate ``i`` we have for data point ``j`` that ``f[i][j] == func(x[i][j])``
Below is the the instruction that describes the task: ### Input: return flattened data ``(x, f)`` such that for the sweep through coordinate ``i`` we have for data point ``j`` that ``f[i][j] == func(x[i][j])`` ### Response: def flattened(self): """return flattened data ``(x, f)`` such that for the ...
def cart2pol(x, y): """Cartesian to Polar coordinates conversion.""" theta = np.arctan2(y, x) rho = np.hypot(x, y) return theta, rho
Cartesian to Polar coordinates conversion.
Below is the the instruction that describes the task: ### Input: Cartesian to Polar coordinates conversion. ### Response: def cart2pol(x, y): """Cartesian to Polar coordinates conversion.""" theta = np.arctan2(y, x) rho = np.hypot(x, y) return theta, rho
def _show_message(self, text): """Show message on splash screen.""" self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.white))
Show message on splash screen.
Below is the the instruction that describes the task: ### Input: Show message on splash screen. ### Response: def _show_message(self, text): """Show message on splash screen.""" self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QCol...
def update(self, truth, guess, features): """Update the feature weights.""" def upd_feat(c, f, w, v): param = (f, c) self._totals[param] += (self.i - self._tstamps[param]) * w self._tstamps[param] = self.i self.weights[f][c] = w + v self.i += 1 ...
Update the feature weights.
Below is the the instruction that describes the task: ### Input: Update the feature weights. ### Response: def update(self, truth, guess, features): """Update the feature weights.""" def upd_feat(c, f, w, v): param = (f, c) self._totals[param] += (self.i - self._tstamps[para...
def create(self, email, verify=None, components=None): """Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:cl...
Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:class:`dict`) .. seealso:: https://docs.cachethq.io/referen...
Below is the the instruction that describes the task: ### Input: Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (...
def guesstype(timestr): """Tries to guess whether a string represents a time or a time delta and returns the appropriate object. :param timestr (required) The string to be analyzed """ timestr_full = " {} ".format(timestr) if timestr_full.find(" in ") != -1 or timestr_full.find(" ago ")...
Tries to guess whether a string represents a time or a time delta and returns the appropriate object. :param timestr (required) The string to be analyzed
Below is the the instruction that describes the task: ### Input: Tries to guess whether a string represents a time or a time delta and returns the appropriate object. :param timestr (required) The string to be analyzed ### Response: def guesstype(timestr): """Tries to guess whether a string re...
def _fw_delete(self, drvr_name, data): """Firewall Delete routine. This function calls routines to remove FW from fabric and device. It also updates its local cache. """ fw_id = data.get('firewall_id') tenant_id = self.tenant_db.get_fw_tenant(fw_id) if tenant_id...
Firewall Delete routine. This function calls routines to remove FW from fabric and device. It also updates its local cache.
Below is the the instruction that describes the task: ### Input: Firewall Delete routine. This function calls routines to remove FW from fabric and device. It also updates its local cache. ### Response: def _fw_delete(self, drvr_name, data): """Firewall Delete routine. This functi...
def transform(self, X, y=None, scan_onsets=None): """ Use the model to estimate the time course of response to each condition (ts), and the time course unrelated to task (ts0) which is spread across the brain. This is equivalent to "decoding" the design matrix and ...
Use the model to estimate the time course of response to each condition (ts), and the time course unrelated to task (ts0) which is spread across the brain. This is equivalent to "decoding" the design matrix and nuisance regressors from a new dataset different from the ...
Below is the the instruction that describes the task: ### Input: Use the model to estimate the time course of response to each condition (ts), and the time course unrelated to task (ts0) which is spread across the brain. This is equivalent to "decoding" the design matrix and ...
def emit(self, record): """Emit a record. Output the record to the file, catering for rollover as described in doRollover(). """ try: if self.shouldRollover(record): self.doRollover() FileHandler.emit(self, record) except (Keyboard...
Emit a record. Output the record to the file, catering for rollover as described in doRollover().
Below is the the instruction that describes the task: ### Input: Emit a record. Output the record to the file, catering for rollover as described in doRollover(). ### Response: def emit(self, record): """Emit a record. Output the record to the file, catering for rollover as descri...
def value_equality(cls: type = None, *, unhashable: bool = False, distinct_child_types: bool = False, manual_cls: bool = False, approximate: bool = False ) -> Union[Callable[[type], type], type]: """Impl...
Implements __eq__/__ne__/__hash__ via a _value_equality_values_ method. _value_equality_values_ is a method that the decorated class must implement. _value_equality_approximate_values_ is a method that the decorated class might implement if special support for approximate equality is required. This is...
Below is the the instruction that describes the task: ### Input: Implements __eq__/__ne__/__hash__ via a _value_equality_values_ method. _value_equality_values_ is a method that the decorated class must implement. _value_equality_approximate_values_ is a method that the decorated class might implement...
def alexnet(pretrained=False, **kwargs): r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = AlexNet(**kwargs) if pretrained: model.load_sta...
r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Below is the the instruction that describes the task: ### Input: r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet ### Response: def alexnet(pretrained=False, **kwargs):...
def connection(self): """ Convenience property for externally accessing an authenticated connection to the server. This connection is automatically handled by the appcontext, so you do not have to perform an unbind. Returns: ldap3.Connection: A bound ldap3.Connection...
Convenience property for externally accessing an authenticated connection to the server. This connection is automatically handled by the appcontext, so you do not have to perform an unbind. Returns: ldap3.Connection: A bound ldap3.Connection Raises: ldap3.core.ex...
Below is the the instruction that describes the task: ### Input: Convenience property for externally accessing an authenticated connection to the server. This connection is automatically handled by the appcontext, so you do not have to perform an unbind. Returns: ldap3.Connectio...
def cmd(send, msg, _): """Tells you what acronyms mean. Syntax: {command} <term> """ try: answer = subprocess.check_output(['wtf', msg], stderr=subprocess.STDOUT) send(answer.decode().strip().replace('\n', ' or ').replace('fuck', 'fsck')) except subprocess.CalledProcessError as ex:...
Tells you what acronyms mean. Syntax: {command} <term>
Below is the the instruction that describes the task: ### Input: Tells you what acronyms mean. Syntax: {command} <term> ### Response: def cmd(send, msg, _): """Tells you what acronyms mean. Syntax: {command} <term> """ try: answer = subprocess.check_output(['wtf', msg], stderr=subpro...
def thread_pool(*workers, results=None, end_of_queue=EndOfQueue): """Returns a |pull| object, call it ``r``, starting a thread for each given worker. Each thread pulls from the source that ``r`` is connected to, and the returned results are pushed to a |Queue|. ``r`` yields from the other end of the s...
Returns a |pull| object, call it ``r``, starting a thread for each given worker. Each thread pulls from the source that ``r`` is connected to, and the returned results are pushed to a |Queue|. ``r`` yields from the other end of the same |Queue|. The target function for each thread is |patch|, which c...
Below is the the instruction that describes the task: ### Input: Returns a |pull| object, call it ``r``, starting a thread for each given worker. Each thread pulls from the source that ``r`` is connected to, and the returned results are pushed to a |Queue|. ``r`` yields from the other end of the same ...
def start_fileoutput (self): """Start output to configured file.""" path = os.path.dirname(self.filename) try: if path and not os.path.isdir(path): os.makedirs(path) self.fd = self.create_fd() self.close_fd = True except IOError: ...
Start output to configured file.
Below is the the instruction that describes the task: ### Input: Start output to configured file. ### Response: def start_fileoutput (self): """Start output to configured file.""" path = os.path.dirname(self.filename) try: if path and not os.path.isdir(path): os....
def set_converter(self, file_format, converter): """ Register a Converter and the FileFormat that it is able to convert from Parameters ---------- converter : Converter The converter to register file_format : FileFormat The file format that can be...
Register a Converter and the FileFormat that it is able to convert from Parameters ---------- converter : Converter The converter to register file_format : FileFormat The file format that can be converted into this format
Below is the the instruction that describes the task: ### Input: Register a Converter and the FileFormat that it is able to convert from Parameters ---------- converter : Converter The converter to register file_format : FileFormat The file format that can be...
def set_hash(self, algo, digest): """Set algorithm ID and hexadecimal digest for next operation.""" self.algo = algo self.digest = digest
Set algorithm ID and hexadecimal digest for next operation.
Below is the the instruction that describes the task: ### Input: Set algorithm ID and hexadecimal digest for next operation. ### Response: def set_hash(self, algo, digest): """Set algorithm ID and hexadecimal digest for next operation.""" self.algo = algo self.digest = digest
def start_evaluating(self, n: Node, s: ShExJ.shapeExpr) -> Optional[bool]: """Indicate that we are beginning to evaluate n according to shape expression s. If we are already in the process of evaluating (n,s), as indicated self.evaluating, we return our current guess as to the result. :...
Indicate that we are beginning to evaluate n according to shape expression s. If we are already in the process of evaluating (n,s), as indicated self.evaluating, we return our current guess as to the result. :param n: Node to be evaluated :param s: expression for node evaluation ...
Below is the the instruction that describes the task: ### Input: Indicate that we are beginning to evaluate n according to shape expression s. If we are already in the process of evaluating (n,s), as indicated self.evaluating, we return our current guess as to the result. :param n: Node to ...
def on_headers(self, response, exc=None): '''Websocket upgrade as ``on_headers`` event.''' if response.status_code == 101: connection = response.connection request = response.request handler = request.websocket_handler if not handler: hand...
Websocket upgrade as ``on_headers`` event.
Below is the the instruction that describes the task: ### Input: Websocket upgrade as ``on_headers`` event. ### Response: def on_headers(self, response, exc=None): '''Websocket upgrade as ``on_headers`` event.''' if response.status_code == 101: connection = response.connection ...
def center(a: Union[Set["Point2"], List["Point2"]]) -> "Point2": """ Returns the central point for points in list """ s = Point2((0, 0)) for p in a: s += p return s / len(a)
Returns the central point for points in list
Below is the the instruction that describes the task: ### Input: Returns the central point for points in list ### Response: def center(a: Union[Set["Point2"], List["Point2"]]) -> "Point2": """ Returns the central point for points in list """ s = Point2((0, 0)) for p in a: s += p...
def have_same_affine(one_img, another_img, only_check_3d=False): """Return True if the affine matrix of one_img is close to the affine matrix of another_img. False otherwise. Parameters ---------- one_img: nibabel.Nifti1Image another_img: nibabel.Nifti1Image only_check_3d: bool If...
Return True if the affine matrix of one_img is close to the affine matrix of another_img. False otherwise. Parameters ---------- one_img: nibabel.Nifti1Image another_img: nibabel.Nifti1Image only_check_3d: bool If True will extract only the 3D part of the affine matrices when they hav...
Below is the the instruction that describes the task: ### Input: Return True if the affine matrix of one_img is close to the affine matrix of another_img. False otherwise. Parameters ---------- one_img: nibabel.Nifti1Image another_img: nibabel.Nifti1Image only_check_3d: bool If Tr...
def dskobj(dsk): """ Find the set of body ID codes of all objects for which topographic data are provided in a specified DSK file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskobj_c.html :param dsk: Name of DSK file. :type dsk: str :return: Set of ID codes of obje...
Find the set of body ID codes of all objects for which topographic data are provided in a specified DSK file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskobj_c.html :param dsk: Name of DSK file. :type dsk: str :return: Set of ID codes of objects in DSK file. :rtype: ...
Below is the the instruction that describes the task: ### Input: Find the set of body ID codes of all objects for which topographic data are provided in a specified DSK file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskobj_c.html :param dsk: Name of DSK file. :type dsk: ...
def network_to_pandas_hdf5(network, filename, rm_nodes=None): """ Save a Network's data to a Pandas HDFStore. Parameters ---------- network : pandana.Network filename : str rm_nodes : array_like A list, array, Index, or Series of node IDs that should *not* be saved as part o...
Save a Network's data to a Pandas HDFStore. Parameters ---------- network : pandana.Network filename : str rm_nodes : array_like A list, array, Index, or Series of node IDs that should *not* be saved as part of the Network.
Below is the the instruction that describes the task: ### Input: Save a Network's data to a Pandas HDFStore. Parameters ---------- network : pandana.Network filename : str rm_nodes : array_like A list, array, Index, or Series of node IDs that should *not* be saved as part of the...
def file_hash(load, fnd): ''' Return a file hash, the hash type is set in the master config file ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') if not all(x in load for x in ('path', 'saltenv')): return '' saltenv = load['saltenv'] if ...
Return a file hash, the hash type is set in the master config file
Below is the the instruction that describes the task: ### Input: Return a file hash, the hash type is set in the master config file ### Response: def file_hash(load, fnd): ''' Return a file hash, the hash type is set in the master config file ''' if 'env' in load: # "env" is not supported; ...
def _mof_escaped(strvalue): # Note: This is a raw docstring because it shows many backslashes, and # that avoids having to double them. r""" Return a MOF-escaped string from the input string. Parameters: strvalue (:term:`unicode string`): The string value. Must not be `None`. Special...
r""" Return a MOF-escaped string from the input string. Parameters: strvalue (:term:`unicode string`): The string value. Must not be `None`. Special characters must not be backslash-escaped. Details on backslash-escaping: `DSP0004` defines that the character repertoire for MOF string c...
Below is the the instruction that describes the task: ### Input: r""" Return a MOF-escaped string from the input string. Parameters: strvalue (:term:`unicode string`): The string value. Must not be `None`. Special characters must not be backslash-escaped. Details on backslash-escaping: ...
def update(self, pop: Union[pd.DataFrame, pd.Series]): """Update the simulation's state to match ``pop`` Parameters ---------- pop : The data which should be copied into the simulation's state. If ``pop`` is a DataFrame only those columns included in the view...
Update the simulation's state to match ``pop`` Parameters ---------- pop : The data which should be copied into the simulation's state. If ``pop`` is a DataFrame only those columns included in the view's columns will be used. If ``pop`` is a Series it must have a nam...
Below is the the instruction that describes the task: ### Input: Update the simulation's state to match ``pop`` Parameters ---------- pop : The data which should be copied into the simulation's state. If ``pop`` is a DataFrame only those columns included in the v...
def createL4L2Column(network, networkConfig, suffix=""): """ Create a a single column containing one L4 and one L2. networkConfig is a dict that must contain the following keys (additional keys ok): { "enableFeedback": True, "externalInputSize": 1024, "sensorInputSize": 1024, "L4Re...
Create a a single column containing one L4 and one L2. networkConfig is a dict that must contain the following keys (additional keys ok): { "enableFeedback": True, "externalInputSize": 1024, "sensorInputSize": 1024, "L4RegionType": "py.ApicalTMPairRegion", "L4Params": { <...
Below is the the instruction that describes the task: ### Input: Create a a single column containing one L4 and one L2. networkConfig is a dict that must contain the following keys (additional keys ok): { "enableFeedback": True, "externalInputSize": 1024, "sensorInputSize": 1024, "...
def parse_from_string( root_processor, # type: RootProcessor xml_string # type: Text ): # type: (...) -> Any """ Parse the XML string using the processor starting from the root of the document. :param xml_string: XML string to parse. See also :func:`declxml.parse_from_file` "...
Parse the XML string using the processor starting from the root of the document. :param xml_string: XML string to parse. See also :func:`declxml.parse_from_file`
Below is the the instruction that describes the task: ### Input: Parse the XML string using the processor starting from the root of the document. :param xml_string: XML string to parse. See also :func:`declxml.parse_from_file` ### Response: def parse_from_string( root_processor, # type: RootProc...
def post(self, url: str, data: str, expected_status_code=201): """ Do a POST request """ r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT) self._check_response(r, expected_status_code) return r.json()
Do a POST request
Below is the the instruction that describes the task: ### Input: Do a POST request ### Response: def post(self, url: str, data: str, expected_status_code=201): """ Do a POST request """ r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT) ...
def unregister_presence_callback(self, type_, from_): """ Unregister a callback previously registered with :meth:`register_presence_callback`. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data...
Unregister a callback previously registered with :meth:`register_presence_callback`. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :...
Below is the the instruction that describes the task: ### Input: Unregister a callback previously registered with :meth:`register_presence_callback`. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`Non...
def create_app(cls, port): """Create a new instance of FrontEndApp that listens on port with a hostname of 0.0.0.0 :param int port: The port FrontEndApp is to listen on :return: A new instance of FrontEndApp wrapped in GeventServer :rtype: GeventServer """ app = FrontEnd...
Create a new instance of FrontEndApp that listens on port with a hostname of 0.0.0.0 :param int port: The port FrontEndApp is to listen on :return: A new instance of FrontEndApp wrapped in GeventServer :rtype: GeventServer
Below is the the instruction that describes the task: ### Input: Create a new instance of FrontEndApp that listens on port with a hostname of 0.0.0.0 :param int port: The port FrontEndApp is to listen on :return: A new instance of FrontEndApp wrapped in GeventServer :rtype: GeventServer ###...
def new_text_cell(text=None): """Create a new text cell.""" cell = NotebookNode() if text is not None: cell.text = unicode(text) cell.cell_type = u'text' return cell
Create a new text cell.
Below is the the instruction that describes the task: ### Input: Create a new text cell. ### Response: def new_text_cell(text=None): """Create a new text cell.""" cell = NotebookNode() if text is not None: cell.text = unicode(text) cell.cell_type = u'text' return cell
def __similarity(s1, s2, ngrams_fn, n=3): """ The fraction of n-grams matching between two sequences Args: s1: a string s2: another string n: an int for the n in n-gram Returns: float: the fraction of n-grams matching """ ngrams1, ngr...
The fraction of n-grams matching between two sequences Args: s1: a string s2: another string n: an int for the n in n-gram Returns: float: the fraction of n-grams matching
Below is the the instruction that describes the task: ### Input: The fraction of n-grams matching between two sequences Args: s1: a string s2: another string n: an int for the n in n-gram Returns: float: the fraction of n-grams matching ### Response:...
def fire(self, args, kwargs): """ Fire this signal with the specified arguments and keyword arguments. Typically this is used by using :meth:`__call__()` on this object which is more natural as it does all the argument packing/unpacking transparently. """ for inf...
Fire this signal with the specified arguments and keyword arguments. Typically this is used by using :meth:`__call__()` on this object which is more natural as it does all the argument packing/unpacking transparently.
Below is the the instruction that describes the task: ### Input: Fire this signal with the specified arguments and keyword arguments. Typically this is used by using :meth:`__call__()` on this object which is more natural as it does all the argument packing/unpacking transparently. ### Resp...
def store_memory_object(self, mo, overwrite=True): """ This function optimizes a large store by storing a single reference to the :class:`SimMemoryObject` instead of one for each byte. :param memory_object: the memory object to store """ for p in self._containing_pages_...
This function optimizes a large store by storing a single reference to the :class:`SimMemoryObject` instead of one for each byte. :param memory_object: the memory object to store
Below is the the instruction that describes the task: ### Input: This function optimizes a large store by storing a single reference to the :class:`SimMemoryObject` instead of one for each byte. :param memory_object: the memory object to store ### Response: def store_memory_object(self, mo, overwr...
def stop(self): """ Stop the server. """ log.debug("Stopping listeners") self.queue_lock.acquire() for s in self.listeners: log.debug("Stopping {}".format(s)) s.shutdown() s.socket.close() self.cancel_queue() for t in se...
Stop the server.
Below is the the instruction that describes the task: ### Input: Stop the server. ### Response: def stop(self): """ Stop the server. """ log.debug("Stopping listeners") self.queue_lock.acquire() for s in self.listeners: log.debug("Stopping {}".format(s)) ...
def plot_eigh2(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the second eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh2([tick_interval, xlabel, ylabel, ax, colorbar, ...
Plot the second eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh2([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] ...
Below is the the instruction that describes the task: ### Input: Plot the second eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh2([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- ...
def objectprep(self): """ Creates fastq files from an in-progress Illumina MiSeq run or create an object and moves files appropriately """ # Create .fastq files if necessary. Otherwise create the metadata object if self.bcltofastq: if self.customsamplesheet: ...
Creates fastq files from an in-progress Illumina MiSeq run or create an object and moves files appropriately
Below is the the instruction that describes the task: ### Input: Creates fastq files from an in-progress Illumina MiSeq run or create an object and moves files appropriately ### Response: def objectprep(self): """ Creates fastq files from an in-progress Illumina MiSeq run or create an object and mo...
def watch(ctx): """Automatically run build whenever a relevant file changes. """ watcher = Watcher(ctx) watcher.watch_directory( path='{pkg.source_less}', ext='.less', action=lambda e: build(ctx, less=True) ) watcher.watch_directory( path='{pkg.source_js}', ext='.jsx', ...
Automatically run build whenever a relevant file changes.
Below is the the instruction that describes the task: ### Input: Automatically run build whenever a relevant file changes. ### Response: def watch(ctx): """Automatically run build whenever a relevant file changes. """ watcher = Watcher(ctx) watcher.watch_directory( path='{pkg.source_less}',...
def list_theme(): """List all available Engineer themes.""" from engineer.themes import ThemeManager themes = ThemeManager.themes() col1, col2 = map(max, zip(*[(len(t.id) + 2, len(t.root_path) + 2) for t in themes.itervalues()])) themes = ThemeManager.themes_by_finder() for finder in sorted(th...
List all available Engineer themes.
Below is the the instruction that describes the task: ### Input: List all available Engineer themes. ### Response: def list_theme(): """List all available Engineer themes.""" from engineer.themes import ThemeManager themes = ThemeManager.themes() col1, col2 = map(max, zip(*[(len(t.id) + 2, len(t.r...
def _expand_syntax_quote( ctx: ReaderContext, form: IterableLispForm ) -> Iterable[LispForm]: """Expand syntax quoted forms to handle unquoting and unquote-splicing. The unquoted form (unquote x) becomes: (list x) The unquote-spliced form (unquote-splicing x) becomes x All other f...
Expand syntax quoted forms to handle unquoting and unquote-splicing. The unquoted form (unquote x) becomes: (list x) The unquote-spliced form (unquote-splicing x) becomes x All other forms are recursively processed as by _process_syntax_quoted_form and are returned as: (list f...
Below is the the instruction that describes the task: ### Input: Expand syntax quoted forms to handle unquoting and unquote-splicing. The unquoted form (unquote x) becomes: (list x) The unquote-spliced form (unquote-splicing x) becomes x All other forms are recursively processed as by...
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE): """Perform LDAP search""" try: results = self._conn.search_s(base, scope, fltr, attrs) except Exception as e: log.exception(self._get_ldap_msg(e)) results = False return results
Perform LDAP search
Below is the the instruction that describes the task: ### Input: Perform LDAP search ### Response: def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE): """Perform LDAP search""" try: results = self._conn.search_s(base, scope, fltr, attrs) except Exception as e: ...
def kick_chat_member(self, chat_id, user_id, until_date=None): """ Use this method to kick a user from a group or a supergroup. :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup :param user_id: Int : Unique identifier of the targe...
Use this method to kick a user from a group or a supergroup. :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup :param user_id: Int : Unique identifier of the target user :param until_date: Date when the user will be unbanned, unix time. I...
Below is the the instruction that describes the task: ### Input: Use this method to kick a user from a group or a supergroup. :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup :param user_id: Int : Unique identifier of the target user ...
def download_static_assets(doc, destination, base_url, request_fn=make_request, url_blacklist=[], js_middleware=None, css_middleware=None, derive_filename=_derive_filename): """ Download all static assets referenced from an HTML page. The goal is to easily create HTML5 apps! Downloads JS, CS...
Download all static assets referenced from an HTML page. The goal is to easily create HTML5 apps! Downloads JS, CSS, images, and audio clips. Args: doc: The HTML page source as a string or BeautifulSoup instance. destination: The folder to download the static assets to! base_url: Th...
Below is the the instruction that describes the task: ### Input: Download all static assets referenced from an HTML page. The goal is to easily create HTML5 apps! Downloads JS, CSS, images, and audio clips. Args: doc: The HTML page source as a string or BeautifulSoup instance. destinati...
def basic_network(cm=False): """A 3-node network of logic gates. Diagram:: +~~~~~~~~+ +~~~~>| A |<~~~~+ | | (OR) +~~~+ | | +~~~~~~~~+ | | | | | | v | +~+~~~~~~+ +~~~~~+~+ ...
A 3-node network of logic gates. Diagram:: +~~~~~~~~+ +~~~~>| A |<~~~~+ | | (OR) +~~~+ | | +~~~~~~~~+ | | | | | | v | +~+~~~~~~+ +~~~~~+~+ | B |<~~~~~~+ C | |...
Below is the the instruction that describes the task: ### Input: A 3-node network of logic gates. Diagram:: +~~~~~~~~+ +~~~~>| A |<~~~~+ | | (OR) +~~~+ | | +~~~~~~~~+ | | | | | | v | +~...
def get_session(self): """Create Session to store credentials. Returns (Session) A Session object with OAuth 2.0 credentials. """ response = _request_access_token( grant_type=auth.CLIENT_CREDENTIALS_GRANT, client_id=self.client_id, ...
Create Session to store credentials. Returns (Session) A Session object with OAuth 2.0 credentials.
Below is the the instruction that describes the task: ### Input: Create Session to store credentials. Returns (Session) A Session object with OAuth 2.0 credentials. ### Response: def get_session(self): """Create Session to store credentials. Returns ...
def one(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[]): """ Transform object by jq script, returning the first result. Raise ValueError unless results does not include exactly one element. """ return compile(script, vars, library_paths).one(_get_value(value, url, ope...
Transform object by jq script, returning the first result. Raise ValueError unless results does not include exactly one element.
Below is the the instruction that describes the task: ### Input: Transform object by jq script, returning the first result. Raise ValueError unless results does not include exactly one element. ### Response: def one(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[]): """ Tr...
def fill_nan(self, val: str, *cols): """ Fill NaN values with new values in the main dataframe :param val: new value :type val: str :param \*cols: names of the colums :type \*cols: str, at least one :example: ``ds.fill_nan("new value", "mycol1", "mycol2")`` ...
Fill NaN values with new values in the main dataframe :param val: new value :type val: str :param \*cols: names of the colums :type \*cols: str, at least one :example: ``ds.fill_nan("new value", "mycol1", "mycol2")``
Below is the the instruction that describes the task: ### Input: Fill NaN values with new values in the main dataframe :param val: new value :type val: str :param \*cols: names of the colums :type \*cols: str, at least one :example: ``ds.fill_nan("new value", "mycol1", "myc...
def on_post(self, req, resp): """ Validate the access token request for spec compliance The spec also dictates the JSON based error response on failure & is handled in this responder. """ grant_type = req.get_param('grant_type') password = req.get_param('password') ...
Validate the access token request for spec compliance The spec also dictates the JSON based error response on failure & is handled in this responder.
Below is the the instruction that describes the task: ### Input: Validate the access token request for spec compliance The spec also dictates the JSON based error response on failure & is handled in this responder. ### Response: def on_post(self, req, resp): """ Validate the access token r...
def extract_source_planes_strikes_dips(src): """ Extract strike and dip angles for source defined by multiple planes. """ if "characteristicFaultSource" not in src.tag: strikes = dict([(key, None) for key, _ in PLANES_STRIKES_PARAM]) dips = dict([(key, None) for key, _ in PLANES_DIPS_PAR...
Extract strike and dip angles for source defined by multiple planes.
Below is the the instruction that describes the task: ### Input: Extract strike and dip angles for source defined by multiple planes. ### Response: def extract_source_planes_strikes_dips(src): """ Extract strike and dip angles for source defined by multiple planes. """ if "characteristicFaultSource...
def get_lookup(self, operator): """Look up a lookup. :param operator: Name of the lookup operator """ try: return self._lookups[operator] except KeyError: raise NotImplementedError("Lookup operator '{}' is not supported".format(operator))
Look up a lookup. :param operator: Name of the lookup operator
Below is the the instruction that describes the task: ### Input: Look up a lookup. :param operator: Name of the lookup operator ### Response: def get_lookup(self, operator): """Look up a lookup. :param operator: Name of the lookup operator """ try: return self....
def xzhdr(self, header, msgid_range=None): """XZHDR command. Args: msgid_range: A message-id as a string, or an article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]) - if last is omitted then all article...
XZHDR command. Args: msgid_range: A message-id as a string, or an article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]) - if last is omitted then all articles after first are included. A msgid_ra...
Below is the the instruction that describes the task: ### Input: XZHDR command. Args: msgid_range: A message-id as a string, or an article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]) - if last is omitted t...
def get(cls, pid, session): """Get an idle, unused connection from the pool. Once a connection has been retrieved, it will be marked as in-use until it is freed. :param str pid: The pool ID :param queries.Session session: The session to assign to the connection :rtype: psycopg2....
Get an idle, unused connection from the pool. Once a connection has been retrieved, it will be marked as in-use until it is freed. :param str pid: The pool ID :param queries.Session session: The session to assign to the connection :rtype: psycopg2.extensions.connection
Below is the the instruction that describes the task: ### Input: Get an idle, unused connection from the pool. Once a connection has been retrieved, it will be marked as in-use until it is freed. :param str pid: The pool ID :param queries.Session session: The session to assign to the connec...
def _add_temporary_results(self, results, label): """Adds `results` to a temporary table with `label`. :param results: results file :type results: `File` :param label: label to be associated with results :type label: `str` """ NGRAM, SIZE, NAME, SIGLUM, COUNT, L...
Adds `results` to a temporary table with `label`. :param results: results file :type results: `File` :param label: label to be associated with results :type label: `str`
Below is the the instruction that describes the task: ### Input: Adds `results` to a temporary table with `label`. :param results: results file :type results: `File` :param label: label to be associated with results :type label: `str` ### Response: def _add_temporary_results(self, ...
def tupletree(table, start='start', stop='stop', value=None): """ Construct an interval tree for the given table, where each node in the tree is a row of the table. """ import intervaltree tree = intervaltree.IntervalTree() it = iter(table) hdr = next(it) flds = list(map(text_type,...
Construct an interval tree for the given table, where each node in the tree is a row of the table.
Below is the the instruction that describes the task: ### Input: Construct an interval tree for the given table, where each node in the tree is a row of the table. ### Response: def tupletree(table, start='start', stop='stop', value=None): """ Construct an interval tree for the given table, where each ...
def register(self, f, *args, **kwargs): """ Register a function and arguments to be called later. """ self._functions.append(lambda: f(*args, **kwargs))
Register a function and arguments to be called later.
Below is the the instruction that describes the task: ### Input: Register a function and arguments to be called later. ### Response: def register(self, f, *args, **kwargs): """ Register a function and arguments to be called later. """ self._functions.append(lambda: f(*args, **kwargs...
def get_list_key(self, data, key, header_lines=2): """Get the list of a key elements. Each element is a tuple (key=None, description, type=None). Note that the tuple's element can differ depending on the key. :param data: the data to proceed :param key: the key """ ...
Get the list of a key elements. Each element is a tuple (key=None, description, type=None). Note that the tuple's element can differ depending on the key. :param data: the data to proceed :param key: the key
Below is the the instruction that describes the task: ### Input: Get the list of a key elements. Each element is a tuple (key=None, description, type=None). Note that the tuple's element can differ depending on the key. :param data: the data to proceed :param key: the key ### Respon...
def clone(self, project, folder="/", **kwargs): ''' :param project: Destination project ID :type project: string :param folder: Folder route to which to move the object :type folder: string :raises: :exc:`~dxpy.exceptions.DXError` if no project is associated with the obje...
:param project: Destination project ID :type project: string :param folder: Folder route to which to move the object :type folder: string :raises: :exc:`~dxpy.exceptions.DXError` if no project is associated with the object :returns: An object handler for the new cloned object ...
Below is the the instruction that describes the task: ### Input: :param project: Destination project ID :type project: string :param folder: Folder route to which to move the object :type folder: string :raises: :exc:`~dxpy.exceptions.DXError` if no project is associated with the obj...
def update_trigger(self, service): """ update the date when occurs the trigger :param service: service object to update """ now = arrow.utcnow().to(settings.TIME_ZONE).format('YYYY-MM-DD HH:mm:ssZZ') TriggerService.objects.filter(id=service.id).update(date_trigger...
update the date when occurs the trigger :param service: service object to update
Below is the the instruction that describes the task: ### Input: update the date when occurs the trigger :param service: service object to update ### Response: def update_trigger(self, service): """ update the date when occurs the trigger :param service: service object t...
def get_reserved_vlan_range(self, id_or_uri): """ Gets the reserved vlan ID range for the fabric. Note: This method is only available on HPE Synergy. Args: id_or_uri: ID or URI of fabric. Returns: dict: vlan-pool """ uri = se...
Gets the reserved vlan ID range for the fabric. Note: This method is only available on HPE Synergy. Args: id_or_uri: ID or URI of fabric. Returns: dict: vlan-pool
Below is the the instruction that describes the task: ### Input: Gets the reserved vlan ID range for the fabric. Note: This method is only available on HPE Synergy. Args: id_or_uri: ID or URI of fabric. Returns: dict: vlan-pool ### Response: def get_re...
def assemble_content_aad(message_id, aad_content_string, seq_num, length): """Assembles the Body AAD string for a message body structure. :param message_id: Message ID :type message_id: str :param aad_content_string: ContentAADString object for frame type :type aad_content_string: aws_encryption_sd...
Assembles the Body AAD string for a message body structure. :param message_id: Message ID :type message_id: str :param aad_content_string: ContentAADString object for frame type :type aad_content_string: aws_encryption_sdk.identifiers.ContentAADString :param seq_num: Sequence number of frame :t...
Below is the the instruction that describes the task: ### Input: Assembles the Body AAD string for a message body structure. :param message_id: Message ID :type message_id: str :param aad_content_string: ContentAADString object for frame type :type aad_content_string: aws_encryption_sdk.identifiers...
def pickle_loads(cls, s): """Reconstruct the flow from a string.""" strio = StringIO() strio.write(s) strio.seek(0) flow = pmg_pickle_load(strio) return flow
Reconstruct the flow from a string.
Below is the the instruction that describes the task: ### Input: Reconstruct the flow from a string. ### Response: def pickle_loads(cls, s): """Reconstruct the flow from a string.""" strio = StringIO() strio.write(s) strio.seek(0) flow = pmg_pickle_load(strio) return...