code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def wait(self, auth, resource, options, defer=False): """ This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options...
This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options: Options for the wait including a timeout (in ms), (max 5min) and...
Below is the the instruction that describes the task: ### Input: This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. opti...
def configureAutoReconnectBackoffTime(self, baseReconnectQuietTimeSecond, maxReconnectQuietTimeSecond, stableConnectionTimeSecond): """ **Description** Used to configure the auto-reconnect backoff timing. Should be called before connect. This is a public facing API inherited by applicat...
**Description** Used to configure the auto-reconnect backoff timing. Should be called before connect. This is a public facing API inherited by application level public clients. **Syntax** .. code:: python # Configure the auto-reconnect backoff to start with 1 second and use...
Below is the the instruction that describes the task: ### Input: **Description** Used to configure the auto-reconnect backoff timing. Should be called before connect. This is a public facing API inherited by application level public clients. **Syntax** .. code:: python ...
def compare_hdf_files(file1, file2): """ Compare two hdf files. :param file1: First file to compare. :param file2: Second file to compare. :returns True if they are the same. """ data1 = FileToDict() data2 = FileToDict() scanner1 = data1.scan scanner2 = data2.scan with h5py.File...
Compare two hdf files. :param file1: First file to compare. :param file2: Second file to compare. :returns True if they are the same.
Below is the the instruction that describes the task: ### Input: Compare two hdf files. :param file1: First file to compare. :param file2: Second file to compare. :returns True if they are the same. ### Response: def compare_hdf_files(file1, file2): """ Compare two hdf files. :param file1: Fir...
def tangent_curve_single_list(obj, param_list, normalize): """ Evaluates the curve tangent vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned v...
Evaluates the curve tangent vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :...
Below is the the instruction that describes the task: ### Input: Evaluates the curve tangent vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned...
def add_reporting_args(parser): """Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created. """ g = parser.add_argument_group('Reporting options') g.add_a...
Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created.
Below is the the instruction that describes the task: ### Input: Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created. ### Response: def add_reporting_args(parser)...
async def replace_dialog(self, dialog_id: str, options: object = None) -> DialogTurnResult: """ Ends the active dialog and starts a new dialog in its place. This is particularly useful for creating loops or redirecting to another dialog. :param dialog_id: ID of the dialog to search for. ...
Ends the active dialog and starts a new dialog in its place. This is particularly useful for creating loops or redirecting to another dialog. :param dialog_id: ID of the dialog to search for. :param options: (Optional) additional argument(s) to pass to the new dialog. :return:
Below is the the instruction that describes the task: ### Input: Ends the active dialog and starts a new dialog in its place. This is particularly useful for creating loops or redirecting to another dialog. :param dialog_id: ID of the dialog to search for. :param options: (Optional) addition...
async def get_link_secret_label(self) -> str: """ Get current link secret label from non-secret storage records; return None for no match. :return: latest non-secret storage record for link secret label """ LOGGER.debug('Wallet.get_link_secret_label >>>') if not self.h...
Get current link secret label from non-secret storage records; return None for no match. :return: latest non-secret storage record for link secret label
Below is the the instruction that describes the task: ### Input: Get current link secret label from non-secret storage records; return None for no match. :return: latest non-secret storage record for link secret label ### Response: async def get_link_secret_label(self) -> str: """ Get curr...
def lstled(x, n, array): """ Given a number x and an array of non-decreasing floats find the index of the largest array element less than or equal to x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstled_c.html :param x: Value to search against. :type x: float :param n: Number ...
Given a number x and an array of non-decreasing floats find the index of the largest array element less than or equal to x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstled_c.html :param x: Value to search against. :type x: float :param n: Number elements in array. :type n: int ...
Below is the the instruction that describes the task: ### Input: Given a number x and an array of non-decreasing floats find the index of the largest array element less than or equal to x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstled_c.html :param x: Value to search against. :typ...
def _get_cibfile_tmp(cibname): ''' Get the full path of a temporary CIB-file with the name of the CIB ''' cibfile_tmp = '{0}.tmp'.format(_get_cibfile(cibname)) log.trace('cibfile_tmp: %s', cibfile_tmp) return cibfile_tmp
Get the full path of a temporary CIB-file with the name of the CIB
Below is the the instruction that describes the task: ### Input: Get the full path of a temporary CIB-file with the name of the CIB ### Response: def _get_cibfile_tmp(cibname): ''' Get the full path of a temporary CIB-file with the name of the CIB ''' cibfile_tmp = '{0}.tmp'.format(_get_cibfile(cib...
def _swap(self): '''Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed''' self.ref_start, self.qry_start = self.qry_start, self.ref_start self.ref_end, self.qry_end = self.qry_end, self.ref_end self.hit...
Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed
Below is the the instruction that describes the task: ### Input: Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed ### Response: def _swap(self): '''Swaps the alignment so that the reference becomes the query and vice-ve...
def UseRangeIndexesOnStrings(client, database_id): """Showing how range queries can be performed even on strings. """ try: DeleteContainerIfExists(client, database_id, COLLECTION_ID) database_link = GetDatabaseLink(database_id) # collections = Query_Entities(client, 'collection', pa...
Showing how range queries can be performed even on strings.
Below is the the instruction that describes the task: ### Input: Showing how range queries can be performed even on strings. ### Response: def UseRangeIndexesOnStrings(client, database_id): """Showing how range queries can be performed even on strings. """ try: DeleteContainerIfExists(client, ...
def check(cls, status): """Checks if a status enum matches the trigger originally set, and if so, raises the appropriate error. Args: status (int, enum): A protobuf enum response status to check. Raises: AssertionError: If trigger or error were not set. ...
Checks if a status enum matches the trigger originally set, and if so, raises the appropriate error. Args: status (int, enum): A protobuf enum response status to check. Raises: AssertionError: If trigger or error were not set. _ApiError: If the statuses don'...
Below is the the instruction that describes the task: ### Input: Checks if a status enum matches the trigger originally set, and if so, raises the appropriate error. Args: status (int, enum): A protobuf enum response status to check. Raises: AssertionError: If trigg...
def rule_command_cmdlist_interface_o_interface_loopback_leaf_interface_loopback_leaf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def rule_command_cmdlist_interface_o_interface_loopback_leaf_interface_loopback_leaf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(conf...
def create_with_virtualenv(self, interpreter, virtualenv_options): """Create a virtualenv using the virtualenv lib.""" args = ['virtualenv', '--python', interpreter, self.env_path] args.extend(virtualenv_options) if not self.pip_installed: args.insert(3, '--no-pip') t...
Create a virtualenv using the virtualenv lib.
Below is the the instruction that describes the task: ### Input: Create a virtualenv using the virtualenv lib. ### Response: def create_with_virtualenv(self, interpreter, virtualenv_options): """Create a virtualenv using the virtualenv lib.""" args = ['virtualenv', '--python', interpreter, self.env...
def _discover_gui(): """Return the most desirable of the currently registered GUIs""" # Prefer last registered guis = reversed(pyblish.api.registered_guis()) for gui in guis: try: gui = __import__(gui).show except (ImportError, AttributeError): continue ...
Return the most desirable of the currently registered GUIs
Below is the the instruction that describes the task: ### Input: Return the most desirable of the currently registered GUIs ### Response: def _discover_gui(): """Return the most desirable of the currently registered GUIs""" # Prefer last registered guis = reversed(pyblish.api.registered_guis()) f...
def verify(self, parents=set()): """ ## DEBUG ONLY ## Recursively ensures that the invariants of an interval subtree hold. """ assert(isinstance(self.s_center, set)) bal = self.balance assert abs(bal) < 2, \ "Error: Rotation should have happen...
## DEBUG ONLY ## Recursively ensures that the invariants of an interval subtree hold.
Below is the the instruction that describes the task: ### Input: ## DEBUG ONLY ## Recursively ensures that the invariants of an interval subtree hold. ### Response: def verify(self, parents=set()): """ ## DEBUG ONLY ## Recursively ensures that the invariants of an interval s...
def set_bucket_props(self, bucket, props): """ Set the properties on the bucket object given """ bucket_type = self._get_bucket_type(bucket.bucket_type) url = self.bucket_properties_path(bucket.name, bucket_type=bucket_type) heade...
Set the properties on the bucket object given
Below is the the instruction that describes the task: ### Input: Set the properties on the bucket object given ### Response: def set_bucket_props(self, bucket, props): """ Set the properties on the bucket object given """ bucket_type = self._get_bucket_type(bucket.bucket_type) ...
def pivot(table, left, top, value): """ Creates a cross-tab or pivot table from a normalised input table. Use this function to 'denormalize' a table of normalized records. * The table argument can be a list of dictionaries or a Table object. (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/...
Creates a cross-tab or pivot table from a normalised input table. Use this function to 'denormalize' a table of normalized records. * The table argument can be a list of dictionaries or a Table object. (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334621) * The left argument is a tuple of he...
Below is the the instruction that describes the task: ### Input: Creates a cross-tab or pivot table from a normalised input table. Use this function to 'denormalize' a table of normalized records. * The table argument can be a list of dictionaries or a Table object. (http://aspn.activestate.com/ASPN/Co...
def export(app, local): """Export the data.""" print_header() log("Preparing to export the data...") id = str(app) subdata_path = os.path.join("data", id, "data") # Create the data package os.makedirs(subdata_path) # Copy the experiment code into a code/ subdirectory try: ...
Export the data.
Below is the the instruction that describes the task: ### Input: Export the data. ### Response: def export(app, local): """Export the data.""" print_header() log("Preparing to export the data...") id = str(app) subdata_path = os.path.join("data", id, "data") # Create the data package ...
def greplines(lines, regexpr_list, reflags=0): """ grepfile - greps a specific file TODO: move to util_str, rework to be core of grepfile """ found_lines = [] found_lxs = [] # Ensure a list islist = isinstance(regexpr_list, (list, tuple)) islist2 = isinstance(reflags, (list, tuple))...
grepfile - greps a specific file TODO: move to util_str, rework to be core of grepfile
Below is the the instruction that describes the task: ### Input: grepfile - greps a specific file TODO: move to util_str, rework to be core of grepfile ### Response: def greplines(lines, regexpr_list, reflags=0): """ grepfile - greps a specific file TODO: move to util_str, rework to be core of gr...
def is_in_list(self, plane_list): """ Checks whether the plane is identical to one of the Planes in the plane_list list of Planes :param plane_list: List of Planes to be compared to :return: True if the plane is in the list, False otherwise """ for plane in plane_list: ...
Checks whether the plane is identical to one of the Planes in the plane_list list of Planes :param plane_list: List of Planes to be compared to :return: True if the plane is in the list, False otherwise
Below is the the instruction that describes the task: ### Input: Checks whether the plane is identical to one of the Planes in the plane_list list of Planes :param plane_list: List of Planes to be compared to :return: True if the plane is in the list, False otherwise ### Response: def is_in_list(se...
def calculate_bayesian_probability(self, cat, token_score, token_tally): """ Calculates the bayesian probability for a given token/category :param cat: The category we're scoring for this token :type cat: str :param token_score: The tally of this token for this category ...
Calculates the bayesian probability for a given token/category :param cat: The category we're scoring for this token :type cat: str :param token_score: The tally of this token for this category :type token_score: float :param token_tally: The tally total for this token from all ...
Below is the the instruction that describes the task: ### Input: Calculates the bayesian probability for a given token/category :param cat: The category we're scoring for this token :type cat: str :param token_score: The tally of this token for this category :type token_score: float...
def triangle(self, params=None, **kwargs): """ Makes a nifty corner plot. Uses :func:`triangle.corner`. :param params: (optional) Names of columns (from :attr:`StarModel.samples`) to plot. If ``None``, then it will plot samples of the parameters use...
Makes a nifty corner plot. Uses :func:`triangle.corner`. :param params: (optional) Names of columns (from :attr:`StarModel.samples`) to plot. If ``None``, then it will plot samples of the parameters used in the MCMC fit-- that is, mass, age, [Fe/H], and...
Below is the the instruction that describes the task: ### Input: Makes a nifty corner plot. Uses :func:`triangle.corner`. :param params: (optional) Names of columns (from :attr:`StarModel.samples`) to plot. If ``None``, then it will plot samples of the paramete...
def get_intent_name(handler_input): # type: (HandlerInput) -> AnyStr """Return the name of the intent request. The method retrieves the intent ``name`` from the input request, only if the input request is an :py:class:`ask_sdk_model.intent_request.IntentRequest`. If the input is not an IntentRe...
Return the name of the intent request. The method retrieves the intent ``name`` from the input request, only if the input request is an :py:class:`ask_sdk_model.intent_request.IntentRequest`. If the input is not an IntentRequest, a :py:class:`TypeError` is raised. :param handler_input: The handler...
Below is the the instruction that describes the task: ### Input: Return the name of the intent request. The method retrieves the intent ``name`` from the input request, only if the input request is an :py:class:`ask_sdk_model.intent_request.IntentRequest`. If the input is not an IntentRequest, a :p...
def _detect_sse3(self): "Does this compiler support SSE3 intrinsics?" self._print_support_start('SSE3') result = self.hasfunction('__m128 v; _mm_hadd_ps(v,v)', include='<pmmintrin.h>', extra_postargs=['-msse3']) self._print_support_en...
Does this compiler support SSE3 intrinsics?
Below is the the instruction that describes the task: ### Input: Does this compiler support SSE3 intrinsics? ### Response: def _detect_sse3(self): "Does this compiler support SSE3 intrinsics?" self._print_support_start('SSE3') result = self.hasfunction('__m128 v; _mm_hadd_ps(v,v)', ...
def on_diff(request, page_name): """Show the diff between two revisions.""" old = request.args.get("old", type=int) new = request.args.get("new", type=int) error = "" diff = page = old_rev = new_rev = None if not (old and new): error = "No revisions specified." else: revisio...
Show the diff between two revisions.
Below is the the instruction that describes the task: ### Input: Show the diff between two revisions. ### Response: def on_diff(request, page_name): """Show the diff between two revisions.""" old = request.args.get("old", type=int) new = request.args.get("new", type=int) error = "" diff = page ...
def _list_packages(self, args): ''' List files for an installed package ''' packages = self._pkgdb_fun('list_packages', self.db_conn) for package in packages: if self.opts['verbose']: status_msg = ','.join(package) else: sta...
List files for an installed package
Below is the the instruction that describes the task: ### Input: List files for an installed package ### Response: def _list_packages(self, args): ''' List files for an installed package ''' packages = self._pkgdb_fun('list_packages', self.db_conn) for package in packages: ...
def validate_activatable_models(): """ Raises a ValidationError for any ActivatableModel that has ForeignKeys or OneToOneFields that will cause cascading deletions to occur. This function also raises a ValidationError if the activatable model has not defined a Boolean field with the field name defined b...
Raises a ValidationError for any ActivatableModel that has ForeignKeys or OneToOneFields that will cause cascading deletions to occur. This function also raises a ValidationError if the activatable model has not defined a Boolean field with the field name defined by the ACTIVATABLE_FIELD_NAME variable on th...
Below is the the instruction that describes the task: ### Input: Raises a ValidationError for any ActivatableModel that has ForeignKeys or OneToOneFields that will cause cascading deletions to occur. This function also raises a ValidationError if the activatable model has not defined a Boolean field with th...
def _function_contents(func): """ The signature is as follows (should be byte/chars): < _code_contents (see above) from func.__code__ > ,( comma separated _object_contents for function argument defaults) ,( comma separated _object_contents for any closure contents ) See also: https://docs.pyth...
The signature is as follows (should be byte/chars): < _code_contents (see above) from func.__code__ > ,( comma separated _object_contents for function argument defaults) ,( comma separated _object_contents for any closure contents ) See also: https://docs.python.org/3/reference/datamodel.html - ...
Below is the the instruction that describes the task: ### Input: The signature is as follows (should be byte/chars): < _code_contents (see above) from func.__code__ > ,( comma separated _object_contents for function argument defaults) ,( comma separated _object_contents for any closure contents ) ...
def getSolution(self): """ Find and return a solution to the problem Example: >>> problem = Problem() >>> problem.getSolution() is None True >>> problem.addVariables(["a"], [42]) >>> problem.getSolution() {'a': 42} @return: Solution for ...
Find and return a solution to the problem Example: >>> problem = Problem() >>> problem.getSolution() is None True >>> problem.addVariables(["a"], [42]) >>> problem.getSolution() {'a': 42} @return: Solution for the problem @rtype: dictionary mapp...
Below is the the instruction that describes the task: ### Input: Find and return a solution to the problem Example: >>> problem = Problem() >>> problem.getSolution() is None True >>> problem.addVariables(["a"], [42]) >>> problem.getSolution() {'a': 42} ...
def __make_tree(self): """Build a tree using lxml.html.builder and our subtrees""" # create div with "container" class div = E.DIV(E.CLASS("container")) # append header with title div.append(E.H2(self.__title)) # next, iterate through subtrees appending each t...
Build a tree using lxml.html.builder and our subtrees
Below is the the instruction that describes the task: ### Input: Build a tree using lxml.html.builder and our subtrees ### Response: def __make_tree(self): """Build a tree using lxml.html.builder and our subtrees""" # create div with "container" class div = E.DIV(E.CLASS("container")) ...
def add_site(self, site_name, location_name=None, er_data=None, pmag_data=None): """ Create a Site object and add it to self.sites. If a location name is provided, add the site to location.sites as well. """ if location_name: location = self.find_by_name(location_name...
Create a Site object and add it to self.sites. If a location name is provided, add the site to location.sites as well.
Below is the the instruction that describes the task: ### Input: Create a Site object and add it to self.sites. If a location name is provided, add the site to location.sites as well. ### Response: def add_site(self, site_name, location_name=None, er_data=None, pmag_data=None): """ Create a...
def power(self, n): """Return the compose of a operator with itself n times. Args: n (int): the number of times to compose with self (n>0). Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions...
Return the compose of a operator with itself n times. Args: n (int): the number of times to compose with self (n>0). Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions of the operator ar...
Below is the the instruction that describes the task: ### Input: Return the compose of a operator with itself n times. Args: n (int): the number of times to compose with self (n>0). Returns: BaseOperator: the n-times composed operator. Raises: QiskitErr...
def add_virtual_columns_aitoff(self, alpha, delta, x, y, radians=True): """Add aitoff (https://en.wikipedia.org/wiki/Aitoff_projection) projection :param alpha: azimuth angle :param delta: polar angle :param x: output name for x coordinate :param y: output name for y coordinate ...
Add aitoff (https://en.wikipedia.org/wiki/Aitoff_projection) projection :param alpha: azimuth angle :param delta: polar angle :param x: output name for x coordinate :param y: output name for y coordinate :param radians: input and output in radians (True), or degrees (False) ...
Below is the the instruction that describes the task: ### Input: Add aitoff (https://en.wikipedia.org/wiki/Aitoff_projection) projection :param alpha: azimuth angle :param delta: polar angle :param x: output name for x coordinate :param y: output name for y coordinate :param...
def scaffold(): """Start a new site.""" click.echo("A whole new site? Awesome.") title = click.prompt("What's the title?") url = click.prompt("Great. What's url? http://") # Make sure that title doesn't exist. click.echo("Got it. Creating %s..." % url)
Start a new site.
Below is the the instruction that describes the task: ### Input: Start a new site. ### Response: def scaffold(): """Start a new site.""" click.echo("A whole new site? Awesome.") title = click.prompt("What's the title?") url = click.prompt("Great. What's url? http://") # Make sure that title do...
def create_fw(self, proj_name, pol_id, fw_id, fw_name, fw_type, rtr_id): """Fills up the local attributes when FW is created. """ self.tenant_name = proj_name self.fw_id = fw_id self.fw_name = fw_name self.fw_created = True self.active_pol_id = pol_id self.fw_type...
Fills up the local attributes when FW is created.
Below is the the instruction that describes the task: ### Input: Fills up the local attributes when FW is created. ### Response: def create_fw(self, proj_name, pol_id, fw_id, fw_name, fw_type, rtr_id): """Fills up the local attributes when FW is created. """ self.tenant_name = proj_name sel...
def from_url(url): """ Given a URL, return a package :param url: :return: """ package_data = HTTPClient().http_request(url=url, decode=None) return Package(raw_data=package_data)
Given a URL, return a package :param url: :return:
Below is the the instruction that describes the task: ### Input: Given a URL, return a package :param url: :return: ### Response: def from_url(url): """ Given a URL, return a package :param url: :return: """ package_data = HTTPClient().http_request(ur...
def new(params, event_shape=(), validate_args=False, name=None): """Create the distribution instance from a `params` vector.""" with tf.compat.v1.name_scope(name, 'IndependentPoisson', [params, event_shape]): params = tf.convert_to_tensor(value=params, name='params') ...
Create the distribution instance from a `params` vector.
Below is the the instruction that describes the task: ### Input: Create the distribution instance from a `params` vector. ### Response: def new(params, event_shape=(), validate_args=False, name=None): """Create the distribution instance from a `params` vector.""" with tf.compat.v1.name_scope(name, 'Indepen...
def compare_version(value): """ Determines if the provided version value compares with program version. `value` Version comparison string (e.g. ==1.0, <=1.0, >1.1) Supported operators: <, <=, ==, >, >= """ # extract parts from value import re...
Determines if the provided version value compares with program version. `value` Version comparison string (e.g. ==1.0, <=1.0, >1.1) Supported operators: <, <=, ==, >, >=
Below is the the instruction that describes the task: ### Input: Determines if the provided version value compares with program version. `value` Version comparison string (e.g. ==1.0, <=1.0, >1.1) Supported operators: <, <=, ==, >, >= ### Response: def compa...
def read_metadata(self, f, objects, previous_segment=None): """Read segment metadata section and update object information""" if not self.toc["kTocMetaData"]: try: self.ordered_objects = previous_segment.ordered_objects except AttributeError: rais...
Read segment metadata section and update object information
Below is the the instruction that describes the task: ### Input: Read segment metadata section and update object information ### Response: def read_metadata(self, f, objects, previous_segment=None): """Read segment metadata section and update object information""" if not self.toc["kTocMetaData"]: ...
def executemany(self, sql, *params): """Prepare a database query or command and then execute it against all parameter sequences found in the sequence seq_of_params. :param sql: the SQL statement to execute with optional ? parameters :param params: sequence parameters for the markers in...
Prepare a database query or command and then execute it against all parameter sequences found in the sequence seq_of_params. :param sql: the SQL statement to execute with optional ? parameters :param params: sequence parameters for the markers in the SQL.
Below is the the instruction that describes the task: ### Input: Prepare a database query or command and then execute it against all parameter sequences found in the sequence seq_of_params. :param sql: the SQL statement to execute with optional ? parameters :param params: sequence paramete...
def generate_confusables(): """Generates the confusables JSON data file from the unicode specification. :return: True for success, raises otherwise. :rtype: bool """ url = 'ftp://ftp.unicode.org/Public/security/latest/confusables.txt' file = get(url) confusables_matrix = defaultdict(list) ...
Generates the confusables JSON data file from the unicode specification. :return: True for success, raises otherwise. :rtype: bool
Below is the the instruction that describes the task: ### Input: Generates the confusables JSON data file from the unicode specification. :return: True for success, raises otherwise. :rtype: bool ### Response: def generate_confusables(): """Generates the confusables JSON data file from the unicode spe...
def unlock_kinetis_abort_clear(): """Returns the abort register clear code. Returns: The abort register clear code. """ flags = registers.AbortRegisterFlags() flags.STKCMPCLR = 1 flags.STKERRCLR = 1 flags.WDERRCLR = 1 flags.ORUNERRCLR = 1 return flags.value
Returns the abort register clear code. Returns: The abort register clear code.
Below is the the instruction that describes the task: ### Input: Returns the abort register clear code. Returns: The abort register clear code. ### Response: def unlock_kinetis_abort_clear(): """Returns the abort register clear code. Returns: The abort register clear code. """ fla...
def parse_coaches(self): """ Parse the home and away coaches :returns: ``self`` on success, ``None`` otherwise """ lx_doc = self.html_doc() tr = lx_doc.xpath('//tr[@id="HeadCoaches"]')[0] for i, td in enumerate(tr): txt = td.xpath('.//text()') ...
Parse the home and away coaches :returns: ``self`` on success, ``None`` otherwise
Below is the the instruction that describes the task: ### Input: Parse the home and away coaches :returns: ``self`` on success, ``None`` otherwise ### Response: def parse_coaches(self): """ Parse the home and away coaches :returns: ``self`` on success, ``None`` otherwise "...
def GetNumberOfRows(self): """Retrieves the number of rows of the table. Returns: int: number of rows. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened. """ if not self._database_object: raise IOError('Not op...
Retrieves the number of rows of the table. Returns: int: number of rows. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened.
Below is the the instruction that describes the task: ### Input: Retrieves the number of rows of the table. Returns: int: number of rows. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened. ### Response: def GetNumberOfRows...
def assert_matches(self, *args, **kwargs): """Assert this matches a :ref:`message spec <message spec>`. Returns self. """ matcher = make_matcher(*args, **kwargs) if not matcher.matches(self): raise AssertionError('%r does not match %r' % (self, matcher)) retu...
Assert this matches a :ref:`message spec <message spec>`. Returns self.
Below is the the instruction that describes the task: ### Input: Assert this matches a :ref:`message spec <message spec>`. Returns self. ### Response: def assert_matches(self, *args, **kwargs): """Assert this matches a :ref:`message spec <message spec>`. Returns self. """ ...
def listDatasetArray(self, **kwargs): """ API to list datasets in DBS. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (Required if dataset_id is not presented), Max length 1000. :type dataset: list :param dataset_id: list of dataset_ids that are the primary ke...
API to list datasets in DBS. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (Required if dataset_id is not presented), Max length 1000. :type dataset: list :param dataset_id: list of dataset_ids that are the primary keys of datasets table: [dataset_id1,dataset_id2,..,dataset_...
Below is the the instruction that describes the task: ### Input: API to list datasets in DBS. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (Required if dataset_id is not presented), Max length 1000. :type dataset: list :param dataset_id: list of dataset_ids that are the...
def validate_param_name(name, param_type): """Validate that the name follows posix conventions for env variables.""" # http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_235 # # 3.235 Name # In the shell command language, a word consisting solely of underscores, # digits, and alp...
Validate that the name follows posix conventions for env variables.
Below is the the instruction that describes the task: ### Input: Validate that the name follows posix conventions for env variables. ### Response: def validate_param_name(name, param_type): """Validate that the name follows posix conventions for env variables.""" # http://pubs.opengroup.org/onlinepubs/96999197...
def _cursor_down(self, count=1): """ Moves cursor down count lines in same column. Cursor stops at bottom margin. """ self.y = min(self.size[0] - 1, self.y + count)
Moves cursor down count lines in same column. Cursor stops at bottom margin.
Below is the the instruction that describes the task: ### Input: Moves cursor down count lines in same column. Cursor stops at bottom margin. ### Response: def _cursor_down(self, count=1): """ Moves cursor down count lines in same column. Cursor stops at bottom margin. """...
def save_file(result, filename, encoding='utf8', headers=None, convertors=None, visitor=None, writer=None, **kwargs): """ save query result to a csv file visitor can used to convert values, all value should be convert to string visitor function should be defined as: def visitor(key...
save query result to a csv file visitor can used to convert values, all value should be convert to string visitor function should be defined as: def visitor(keys, values, encoding): #return new values [] convertors is used to convert single column value, for example: ...
Below is the the instruction that describes the task: ### Input: save query result to a csv file visitor can used to convert values, all value should be convert to string visitor function should be defined as: def visitor(keys, values, encoding): #return new values [] convertors...
def text(el, strip=True): """ Return the text of a ``BeautifulSoup`` element """ if not el: return "" text = el.text if strip: text = text.strip() return text
Return the text of a ``BeautifulSoup`` element
Below is the the instruction that describes the task: ### Input: Return the text of a ``BeautifulSoup`` element ### Response: def text(el, strip=True): """ Return the text of a ``BeautifulSoup`` element """ if not el: return "" text = el.text if strip: text = text.strip() ...
def _add_study_provenance( self, phenotyping_center, colony, project_fullname, pipeline_name, pipeline_stable_id, procedure_stable_id, procedure_name, parameter_stable_id, parameter_name, ...
:param phenotyping_center: str, from self.files['all'] :param colony: str, from self.files['all'] :param project_fullname: str, from self.files['all'] :param pipeline_name: str, from self.files['all'] :param pipeline_stable_id: str, from self.files['all'] :param procedure_stable_...
Below is the the instruction that describes the task: ### Input: :param phenotyping_center: str, from self.files['all'] :param colony: str, from self.files['all'] :param project_fullname: str, from self.files['all'] :param pipeline_name: str, from self.files['all'] :param pipeline_st...
def parse_args(self, ctx, args): """Parse arguments sent to this command. The code for this method is taken from MultiCommand: https://github.com/mitsuhiko/click/blob/master/click/core.py It is Copyright (c) 2014 by Armin Ronacher. See the license: https://github.com/mi...
Parse arguments sent to this command. The code for this method is taken from MultiCommand: https://github.com/mitsuhiko/click/blob/master/click/core.py It is Copyright (c) 2014 by Armin Ronacher. See the license: https://github.com/mitsuhiko/click/blob/master/LICENSE
Below is the the instruction that describes the task: ### Input: Parse arguments sent to this command. The code for this method is taken from MultiCommand: https://github.com/mitsuhiko/click/blob/master/click/core.py It is Copyright (c) 2014 by Armin Ronacher. See the license: ...
def list_disks(disk_ids=None, scsi_addresses=None, service_instance=None): ''' Returns a list of dict representations of the disks in an ESXi host. The list of disks can be filtered by disk canonical names or scsi addresses. disk_ids: List of disk canonical names to be retrieved. Default is...
Returns a list of dict representations of the disks in an ESXi host. The list of disks can be filtered by disk canonical names or scsi addresses. disk_ids: List of disk canonical names to be retrieved. Default is None. scsi_addresses List of scsi addresses of disks to be retrieved. Def...
Below is the the instruction that describes the task: ### Input: Returns a list of dict representations of the disks in an ESXi host. The list of disks can be filtered by disk canonical names or scsi addresses. disk_ids: List of disk canonical names to be retrieved. Default is None. scsi_a...
def save_data(trigger_id, data): """ call the consumer and handle the data :param trigger_id: :param data: :return: """ status = True # consumer - the service which uses the data default_provider.load_services() service = TriggerService.objects.get(id=trigger_id) ...
call the consumer and handle the data :param trigger_id: :param data: :return:
Below is the the instruction that describes the task: ### Input: call the consumer and handle the data :param trigger_id: :param data: :return: ### Response: def save_data(trigger_id, data): """ call the consumer and handle the data :param trigger_id: :param data...
def _nvram_file(self): """ Path to the nvram file """ return os.path.join(self.working_dir, "nvram_{:05d}".format(self.application_id))
Path to the nvram file
Below is the the instruction that describes the task: ### Input: Path to the nvram file ### Response: def _nvram_file(self): """ Path to the nvram file """ return os.path.join(self.working_dir, "nvram_{:05d}".format(self.application_id))
def set_contents_from_filename(self, filename, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, reduced_redundancy=False, encrypt_key=False): """ Store an object in S3 using the...
Store an object in S3 using the name of the Key object as the key in S3 and the contents of the file named by 'filename'. See set_contents_from_file method for details about the parameters. :type filename: string :param filename: The name of the file that you want to put onto S3...
Below is the the instruction that describes the task: ### Input: Store an object in S3 using the name of the Key object as the key in S3 and the contents of the file named by 'filename'. See set_contents_from_file method for details about the parameters. :type filename: string ...
def path_file_to_list(path_file): """ :return: A list with the paths which are stored in a text file in a line-by- line format. Validate each path using is_valid_path """ paths = [] path_file_fd = file(path_file) for line_no, line in enumerate(path_file_fd.readlines(), start=1): ...
:return: A list with the paths which are stored in a text file in a line-by- line format. Validate each path using is_valid_path
Below is the the instruction that describes the task: ### Input: :return: A list with the paths which are stored in a text file in a line-by- line format. Validate each path using is_valid_path ### Response: def path_file_to_list(path_file): """ :return: A list with the paths which are stored ...
def add_parameter(self, location='query', **kwargs): """Adds a new parameter to the request :param location: the 'in' field of the parameter (e.g: 'query', 'body', 'path') """ kwargs.setdefault('in', location) if kwargs['in'] != 'body': kwargs.setdefault('...
Adds a new parameter to the request :param location: the 'in' field of the parameter (e.g: 'query', 'body', 'path')
Below is the the instruction that describes the task: ### Input: Adds a new parameter to the request :param location: the 'in' field of the parameter (e.g: 'query', 'body', 'path') ### Response: def add_parameter(self, location='query', **kwargs): """Adds a new parameter to the request ...
def enable(identifier, exclude_children=False): """ Enable a previously disabled include type :param identifier: module or name of the include type :param exclude_children: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple wa...
Enable a previously disabled include type :param identifier: module or name of the include type :param exclude_children: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple ways to disable an include type. See :py:meth:`~.DisabledI...
Below is the the instruction that describes the task: ### Input: Enable a previously disabled include type :param identifier: module or name of the include type :param exclude_children: disable the include type only for child processes, not the current process The ``identifier`` can be specified in mu...
def weights(self): """Weights as described in the FS framework.""" m = self.kernel.feature_log_prob_[self._match_class_pos()] u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(numpy.exp(m - u))
Weights as described in the FS framework.
Below is the the instruction that describes the task: ### Input: Weights as described in the FS framework. ### Response: def weights(self): """Weights as described in the FS framework.""" m = self.kernel.feature_log_prob_[self._match_class_pos()] u = self.kernel.feature_log_prob_[self._nonm...
def print_warning(msg, color=True): """ Print a warning message. :param string msg: the message :param bool color: if ``True``, print with POSIX color """ if color and is_posix(): safe_print(u"%s[WARN] %s%s" % (ANSI_WARNING, msg, ANSI_END)) else: safe_print(u"[WARN] %s" % (m...
Print a warning message. :param string msg: the message :param bool color: if ``True``, print with POSIX color
Below is the the instruction that describes the task: ### Input: Print a warning message. :param string msg: the message :param bool color: if ``True``, print with POSIX color ### Response: def print_warning(msg, color=True): """ Print a warning message. :param string msg: the message :pa...
def dict_to_element(doc: dict, value_key: str='@', attribute_prefix: str='@') -> Element: """ Generates XML Element from dict. Generates complex elements by assuming element attributes are prefixed with '@', and value is stored to plain '@' in case of complex element. Children are sub-dicts. For ex...
Generates XML Element from dict. Generates complex elements by assuming element attributes are prefixed with '@', and value is stored to plain '@' in case of complex element. Children are sub-dicts. For example: { 'Doc': { '@version': '1.2', 'A': [{'@clas...
Below is the the instruction that describes the task: ### Input: Generates XML Element from dict. Generates complex elements by assuming element attributes are prefixed with '@', and value is stored to plain '@' in case of complex element. Children are sub-dicts. For example: { 'Doc...
def handle_stream(self, stream, address): ''' Handle incoming streams and add messages to the incoming queue ''' log.trace('Req client %s connected', address) self.clients.append((stream, address)) unpacker = msgpack.Unpacker() try: while True: ...
Handle incoming streams and add messages to the incoming queue
Below is the the instruction that describes the task: ### Input: Handle incoming streams and add messages to the incoming queue ### Response: def handle_stream(self, stream, address): ''' Handle incoming streams and add messages to the incoming queue ''' log.trace('Req client %s con...
def _fnop_style(schema, op, name): """Set an operator's parameter representing the style of this schema.""" if is_common(schema): if name in op.params: del op.params[name] return if _is_pending(schema): ntp = 'pending' elif schema.style...
Set an operator's parameter representing the style of this schema.
Below is the the instruction that describes the task: ### Input: Set an operator's parameter representing the style of this schema. ### Response: def _fnop_style(schema, op, name): """Set an operator's parameter representing the style of this schema.""" if is_common(schema): if name in ...
def upload_panel(store, institute_id, case_name, stream): """Parse out HGNC symbols from a stream.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) raw_symbols = [line.strip().split('\t')[0] for line in stream if line and not line.startswith('#')] # chec...
Parse out HGNC symbols from a stream.
Below is the the instruction that describes the task: ### Input: Parse out HGNC symbols from a stream. ### Response: def upload_panel(store, institute_id, case_name, stream): """Parse out HGNC symbols from a stream.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) raw_sym...
def show_messages(self): """Show all messages.""" if isinstance(self.static_message, MessageElement): # Handle sent Message instance string = html_header() if self.static_message is not None: string += self.static_message.to_html() # Keep ...
Show all messages.
Below is the the instruction that describes the task: ### Input: Show all messages. ### Response: def show_messages(self): """Show all messages.""" if isinstance(self.static_message, MessageElement): # Handle sent Message instance string = html_header() if self.s...
def is_bool_matrix(l): r"""Checks if l is a 2D numpy array of bools """ if isinstance(l, np.ndarray): if l.ndim == 2 and (l.dtype == bool): return True return False
r"""Checks if l is a 2D numpy array of bools
Below is the the instruction that describes the task: ### Input: r"""Checks if l is a 2D numpy array of bools ### Response: def is_bool_matrix(l): r"""Checks if l is a 2D numpy array of bools """ if isinstance(l, np.ndarray): if l.ndim == 2 and (l.dtype == bool): return True re...
def export_modifications(self): """ Returns list modifications. """ if self.__modified_data__ is not None: return self.export_data() result = {} for key, value in enumerate(self.__original_data__): try: if not value.is_modified():...
Returns list modifications.
Below is the the instruction that describes the task: ### Input: Returns list modifications. ### Response: def export_modifications(self): """ Returns list modifications. """ if self.__modified_data__ is not None: return self.export_data() result = {} f...
def relative_path(self, filepath, basepath=None): """ Convert the filepath path to a relative path against basepath. By default basepath is self.basedir. """ if basepath is None: basepath = self.basedir if not basepath: return filepath if f...
Convert the filepath path to a relative path against basepath. By default basepath is self.basedir.
Below is the the instruction that describes the task: ### Input: Convert the filepath path to a relative path against basepath. By default basepath is self.basedir. ### Response: def relative_path(self, filepath, basepath=None): """ Convert the filepath path to a relative path against basep...
def evaluate(ref_intervals, ref_pitches, est_intervals, est_pitches, **kwargs): """Compute all metrics for the given reference and estimated annotations. Examples -------- >>> ref_intervals, ref_pitches = mir_eval.io.load_valued_intervals( ... 'reference.txt') >>> est_intervals, est_pitches ...
Compute all metrics for the given reference and estimated annotations. Examples -------- >>> ref_intervals, ref_pitches = mir_eval.io.load_valued_intervals( ... 'reference.txt') >>> est_intervals, est_pitches = mir_eval.io.load_valued_intervals( ... 'estimate.txt') >>> scores = mir_ev...
Below is the the instruction that describes the task: ### Input: Compute all metrics for the given reference and estimated annotations. Examples -------- >>> ref_intervals, ref_pitches = mir_eval.io.load_valued_intervals( ... 'reference.txt') >>> est_intervals, est_pitches = mir_eval.io.load...
def run(self): """ Overrides the default _run() private method. Performs the complete analysis :return: A fully computed set of Ordinary Differential Equations that can be used for further simulation :rtype: :class:`~means.core.problems.ODEProblem` """ S = self.m...
Overrides the default _run() private method. Performs the complete analysis :return: A fully computed set of Ordinary Differential Equations that can be used for further simulation :rtype: :class:`~means.core.problems.ODEProblem`
Below is the the instruction that describes the task: ### Input: Overrides the default _run() private method. Performs the complete analysis :return: A fully computed set of Ordinary Differential Equations that can be used for further simulation :rtype: :class:`~means.core.problems.ODEProble...
def get_resources(cls): """Returns Ext Resources.""" plural_mappings = resource_helper.build_plural_mappings( {}, RESOURCE_ATTRIBUTE_MAP) # attr.PLURALS.update(plural_mappings) return resource_helper.build_resource_info(plural_mappings, ...
Returns Ext Resources.
Below is the the instruction that describes the task: ### Input: Returns Ext Resources. ### Response: def get_resources(cls): """Returns Ext Resources.""" plural_mappings = resource_helper.build_plural_mappings( {}, RESOURCE_ATTRIBUTE_MAP) # attr.PLURALS.update(plural_mappings) ...
def hincrby(self, hashkey, attribute, increment=1): """Emulate hincrby.""" return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment)
Emulate hincrby.
Below is the the instruction that describes the task: ### Input: Emulate hincrby. ### Response: def hincrby(self, hashkey, attribute, increment=1): """Emulate hincrby.""" return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment)
def parse_gene_panel(path, institute='cust000', panel_id='test', panel_type='clinical', date=datetime.now(), version=1.0, display_name=None, genes = None): """Parse the panel info and return a gene panel Args: path(str): Path to panel file institute(str): Name ...
Parse the panel info and return a gene panel Args: path(str): Path to panel file institute(str): Name of institute that owns the panel panel_id(str): Panel id date(datetime.datetime): Date of creation version(float) full_name(str): Option ...
Below is the the instruction that describes the task: ### Input: Parse the panel info and return a gene panel Args: path(str): Path to panel file institute(str): Name of institute that owns the panel panel_id(str): Panel id date(datetime.datetime): Date of cr...
def register(self, new_formulas, *args, **kwargs): """ Register formula and meta data. * ``islinear`` - ``True`` if formula is linear, ``False`` if non-linear. * ``args`` - position of arguments * ``units`` - units of returns and arguments as pair of tuples * ``isconstan...
Register formula and meta data. * ``islinear`` - ``True`` if formula is linear, ``False`` if non-linear. * ``args`` - position of arguments * ``units`` - units of returns and arguments as pair of tuples * ``isconstant`` - constant arguments not included in covariance :param new...
Below is the the instruction that describes the task: ### Input: Register formula and meta data. * ``islinear`` - ``True`` if formula is linear, ``False`` if non-linear. * ``args`` - position of arguments * ``units`` - units of returns and arguments as pair of tuples * ``isconstant`...
def choose_optimizer(optimizer_name, bounds): """ Selects the type of local optimizer """ if optimizer_name == 'lbfgs': optimizer = OptLbfgs(bounds) elif optimizer_name == 'DIRECT': optimizer = OptDirect(bounds) elif optimizer_name == 'CMA': ...
Selects the type of local optimizer
Below is the the instruction that describes the task: ### Input: Selects the type of local optimizer ### Response: def choose_optimizer(optimizer_name, bounds): """ Selects the type of local optimizer """ if optimizer_name == 'lbfgs': optimizer = OptLbfgs(bounds) ...
def generic_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = common_attention.maybe_upcast(logits, hparams=model_hparams) cutoff = getattr(model_hparams, "video_modality_l...
Compute loss numerator and denominator for one shard of output.
Below is the the instruction that describes the task: ### Input: Compute loss numerator and denominator for one shard of output. ### Response: def generic_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unuse...
def handle_text(self, item): """Helper method for fetching a text value.""" doc = yield from self.handle_get(item) if doc is None: return None return doc.value.c8_array.text or None
Helper method for fetching a text value.
Below is the the instruction that describes the task: ### Input: Helper method for fetching a text value. ### Response: def handle_text(self, item): """Helper method for fetching a text value.""" doc = yield from self.handle_get(item) if doc is None: return None return ...
def operator_relocate(self, graph, solution, op_diff_round_digits, anim): """applies Relocate inter-route operator to solution Takes every node from every route and calculates savings when inserted into all possible positions in other routes. Insertion is done at position with m...
applies Relocate inter-route operator to solution Takes every node from every route and calculates savings when inserted into all possible positions in other routes. Insertion is done at position with max. saving and procedure starts over again with newly created graph as input....
Below is the the instruction that describes the task: ### Input: applies Relocate inter-route operator to solution Takes every node from every route and calculates savings when inserted into all possible positions in other routes. Insertion is done at position with max. saving and p...
def session_scope(session_cls=None): """Provide a transactional scope around a series of operations.""" session = session_cls() if session_cls else Session() try: yield session session.commit() except Exception: session.rollback() raise finally: session.close(...
Provide a transactional scope around a series of operations.
Below is the the instruction that describes the task: ### Input: Provide a transactional scope around a series of operations. ### Response: def session_scope(session_cls=None): """Provide a transactional scope around a series of operations.""" session = session_cls() if session_cls else Session() try: ...
def encode(self, pad=106): """Encodes this AIT command to binary. If pad is specified, it indicates the maximum size of the encoded command in bytes. If the encoded command is less than pad, the remaining bytes are set to zero. Commands sent to ISS payloads over 1553 are limit...
Encodes this AIT command to binary. If pad is specified, it indicates the maximum size of the encoded command in bytes. If the encoded command is less than pad, the remaining bytes are set to zero. Commands sent to ISS payloads over 1553 are limited to 64 words (128 bytes) wit...
Below is the the instruction that describes the task: ### Input: Encodes this AIT command to binary. If pad is specified, it indicates the maximum size of the encoded command in bytes. If the encoded command is less than pad, the remaining bytes are set to zero. Commands sent to I...
def head(file_path, lines=10, encoding="utf-8", printed=True, errors='strict'): """ Read the first N lines of a file, defaults to 10 :param file_path: Path to file to read :param lines: Number of lines to read in :param encoding: defaults to utf-8 to decode as, will fail on binary :par...
Read the first N lines of a file, defaults to 10 :param file_path: Path to file to read :param lines: Number of lines to read in :param encoding: defaults to utf-8 to decode as, will fail on binary :param printed: Automatically print the lines instead of returning it :param errors: Decoding errors:...
Below is the the instruction that describes the task: ### Input: Read the first N lines of a file, defaults to 10 :param file_path: Path to file to read :param lines: Number of lines to read in :param encoding: defaults to utf-8 to decode as, will fail on binary :param printed: Automatically print ...
def getOverlayTransformTrackedDeviceComponent(self, ulOverlayHandle, pchComponentName, unComponentNameSize): """Gets the transform information when the overlay is rendering on a component.""" fn = self.function_table.getOverlayTransformTrackedDeviceComponent punDeviceIndex = TrackedDeviceIndex_...
Gets the transform information when the overlay is rendering on a component.
Below is the the instruction that describes the task: ### Input: Gets the transform information when the overlay is rendering on a component. ### Response: def getOverlayTransformTrackedDeviceComponent(self, ulOverlayHandle, pchComponentName, unComponentNameSize): """Gets the transform information when the...
def buscar_ambientep44_por_finalidade_cliente( self, finalidade_txt, cliente_txt): """Search ambiente_p44_txt environment vip :return: Dictionary with the following structure: :: {‘ambiente_p44_txt’: 'id':<'id_ambientevip'>, ...
Search ambiente_p44_txt environment vip :return: Dictionary with the following structure: :: {‘ambiente_p44_txt’: 'id':<'id_ambientevip'>, ‘finalidade’: <'finalidade_txt'>, 'cliente_txt: <'cliente_txt'>', 'ambiente_p44: <'ambiente_p44'>',} ...
Below is the the instruction that describes the task: ### Input: Search ambiente_p44_txt environment vip :return: Dictionary with the following structure: :: {‘ambiente_p44_txt’: 'id':<'id_ambientevip'>, ‘finalidade’: <'finalidade_txt'>, 'cliente_tx...
def credits(self): """Returns either a tuple representing the credit range or a single integer if the range is set to one value. Use self.cred to always get the tuple. """ if self.cred[0] == self.cred[1]: return self.cred[0] return self.cred
Returns either a tuple representing the credit range or a single integer if the range is set to one value. Use self.cred to always get the tuple.
Below is the the instruction that describes the task: ### Input: Returns either a tuple representing the credit range or a single integer if the range is set to one value. Use self.cred to always get the tuple. ### Response: def credits(self): """Returns either a tuple representing the cre...
def selfoss(reset_password=False): '''Install, update and set up selfoss. This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt....
Install, update and set up selfoss. This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt. More infos: https://selfoss.ad...
Below is the the instruction that describes the task: ### Input: Install, update and set up selfoss. This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with tas...
def _preloading_env(self): """ A "stripped" jinja environment. """ ctx = self.env.globals try: ctx['random_model'] = lambda *a, **kw: None ctx['random_models'] = lambda *a, **kw: None yield self.env finally: ctx['random_mode...
A "stripped" jinja environment.
Below is the the instruction that describes the task: ### Input: A "stripped" jinja environment. ### Response: def _preloading_env(self): """ A "stripped" jinja environment. """ ctx = self.env.globals try: ctx['random_model'] = lambda *a, **kw: None c...
def download_scans(sc, age=0, unzip=False, path='scans'): '''Scan Downloader Here we will attempt to download all of the scans that have completed between now and AGE days ago. sc = SecurityCenter5 object age = how many days back do we want to pull? (default: 0) unzip = Do we want to uncompress...
Scan Downloader Here we will attempt to download all of the scans that have completed between now and AGE days ago. sc = SecurityCenter5 object age = how many days back do we want to pull? (default: 0) unzip = Do we want to uncompress the nessus files? (default: False) path = Path where the res...
Below is the the instruction that describes the task: ### Input: Scan Downloader Here we will attempt to download all of the scans that have completed between now and AGE days ago. sc = SecurityCenter5 object age = how many days back do we want to pull? (default: 0) unzip = Do we want to uncomp...
def get_charset(content_type): """Function used to retrieve the charset from a content-type.If there is no charset in the content type then the charset defined on DEFAULT_CHARSET will be returned :param content_type: A string containing a Content-Type header :returns: A string cont...
Function used to retrieve the charset from a content-type.If there is no charset in the content type then the charset defined on DEFAULT_CHARSET will be returned :param content_type: A string containing a Content-Type header :returns: A string containing the charset
Below is the the instruction that describes the task: ### Input: Function used to retrieve the charset from a content-type.If there is no charset in the content type then the charset defined on DEFAULT_CHARSET will be returned :param content_type: A string containing a Content-Type header :retur...
def select(self, model): """Select nodes according to the input selector. This can ALWAYS return multiple root elements. """ res = [] def doSelect(value, pre, remaining): if not remaining: res.append((pre, value)) else: # For the other selectors to work, value must be a...
Select nodes according to the input selector. This can ALWAYS return multiple root elements.
Below is the the instruction that describes the task: ### Input: Select nodes according to the input selector. This can ALWAYS return multiple root elements. ### Response: def select(self, model): """Select nodes according to the input selector. This can ALWAYS return multiple root elements. """ ...
def start_new_thread(function, args, kwargs={}): """Dummy implementation of thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by thread.exit()) it is caugh...
Dummy implementation of thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by thread.exit()) it is caught and nothing is done; all other exceptions are printed ...
Below is the the instruction that describes the task: ### Input: Dummy implementation of thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by thread.exit()) it...
def _fetch_all(cls, api_key, endpoint=None, offset=0, limit=25, **kwargs): """ Call `self._fetch_page` for as many pages as exist. TODO: should be extended to do async page fetches if API allows it via exposing total value. Returns a list of `cls` instances. """ ...
Call `self._fetch_page` for as many pages as exist. TODO: should be extended to do async page fetches if API allows it via exposing total value. Returns a list of `cls` instances.
Below is the the instruction that describes the task: ### Input: Call `self._fetch_page` for as many pages as exist. TODO: should be extended to do async page fetches if API allows it via exposing total value. Returns a list of `cls` instances. ### Response: def _fetch_all(cls, api_key, e...
def resume(): """ Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopped. """ t = timer() if f.t.stop...
Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopped.
Below is the the instruction that describes the task: ### Input: Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopp...
def _click_autocomplete(root, text): """Completer generator for click applications.""" try: parts = shlex.split(text) except ValueError: raise StopIteration location, incomplete = _click_resolve_command(root, parts) if not text.endswith(' ') and not incomplete and text: rai...
Completer generator for click applications.
Below is the the instruction that describes the task: ### Input: Completer generator for click applications. ### Response: def _click_autocomplete(root, text): """Completer generator for click applications.""" try: parts = shlex.split(text) except ValueError: raise StopIteration lo...
def logs_for_job(self, job_name, wait=False, poll=10): # noqa: C901 - suppress complexity warning for this method """Display the logs for a given training job, optionally tailing them until the job is complete. If the output is a tty or a Jupyter cell, it will be color-coded based on which inst...
Display the logs for a given training job, optionally tailing them until the job is complete. If the output is a tty or a Jupyter cell, it will be color-coded based on which instance the log entry is from. Args: job_name (str): Name of the training job to display the logs for. ...
Below is the the instruction that describes the task: ### Input: Display the logs for a given training job, optionally tailing them until the job is complete. If the output is a tty or a Jupyter cell, it will be color-coded based on which instance the log entry is from. Args: jo...
def insert_point(self, x, y): """ Inserts a point on the path at the mouse location. We first need to check if the mouse location is on the path. Inserting point is time intensive and experimental. """ try: bezier = _ctx.ximport("b...
Inserts a point on the path at the mouse location. We first need to check if the mouse location is on the path. Inserting point is time intensive and experimental.
Below is the the instruction that describes the task: ### Input: Inserts a point on the path at the mouse location. We first need to check if the mouse location is on the path. Inserting point is time intensive and experimental. ### Response: def insert_point(self, x, y): ...
def tokens(cls, tokens): """ Create a Lnk object for a token range. Args: tokens: a list of token identifiers """ return cls(Lnk.TOKENS, tuple(map(int, tokens)))
Create a Lnk object for a token range. Args: tokens: a list of token identifiers
Below is the the instruction that describes the task: ### Input: Create a Lnk object for a token range. Args: tokens: a list of token identifiers ### Response: def tokens(cls, tokens): """ Create a Lnk object for a token range. Args: tokens: a list of token...
def error_perturbation(C, S): r"""Error perturbation for given sensitivity matrix. Parameters ---------- C : (M, M) ndarray Count matrix S : (M, M) ndarray or (K, M, M) ndarray Sensitivity matrix (for scalar observable) or sensitivity tensor for vector observable Return...
r"""Error perturbation for given sensitivity matrix. Parameters ---------- C : (M, M) ndarray Count matrix S : (M, M) ndarray or (K, M, M) ndarray Sensitivity matrix (for scalar observable) or sensitivity tensor for vector observable Returns ------- X : float or (K,...
Below is the the instruction that describes the task: ### Input: r"""Error perturbation for given sensitivity matrix. Parameters ---------- C : (M, M) ndarray Count matrix S : (M, M) ndarray or (K, M, M) ndarray Sensitivity matrix (for scalar observable) or sensitivity tenso...
def count(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""): """Counts the number of ticalc.org files containing some search term, doesn't return them""" fileData = {} nameData = {} #Search the index if searchFiles: fileData = self.searchNamesIndex(self.fileIndex,...
Counts the number of ticalc.org files containing some search term, doesn't return them
Below is the the instruction that describes the task: ### Input: Counts the number of ticalc.org files containing some search term, doesn't return them ### Response: def count(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""): """Counts the number of ticalc.org files conta...