code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def add_route(app, fn, context=default_context): """ a decorator that adds a transmute route to the application. """ transmute_func = TransmuteFunction( fn, args_not_from_request=["request"] ) handler = create_handler(transmute_func, context=context) get_swagger_spec(app).add...
a decorator that adds a transmute route to the application.
Below is the the instruction that describes the task: ### Input: a decorator that adds a transmute route to the application. ### Response: def add_route(app, fn, context=default_context): """ a decorator that adds a transmute route to the application. """ transmute_func = TransmuteFunction( ...
def get_roles_for_permission(permission, brain_or_object): """Return the roles of the permission that is granted on the object Code extracted from `IRoleManager.rolesOfPermission` :param permission: The permission to get the roles :param brain_or_object: Catalog brain or object :returns: List of r...
Return the roles of the permission that is granted on the object Code extracted from `IRoleManager.rolesOfPermission` :param permission: The permission to get the roles :param brain_or_object: Catalog brain or object :returns: List of roles having the permission
Below is the the instruction that describes the task: ### Input: Return the roles of the permission that is granted on the object Code extracted from `IRoleManager.rolesOfPermission` :param permission: The permission to get the roles :param brain_or_object: Catalog brain or object :returns: List o...
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
Remove item from six.moves.
Below is the the instruction that describes the task: ### Input: Remove item from six.moves. ### Response: def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: ...
def from_start_and_end(cls, start, end, aa=None, helix_type='alpha'): """Creates a `Helix` between `start` and `end`. Parameters ---------- start : 3D Vector (tuple or list or numpy.array) The coordinate of the start of the helix primitive. end : 3D Vector (tuple or ...
Creates a `Helix` between `start` and `end`. Parameters ---------- start : 3D Vector (tuple or list or numpy.array) The coordinate of the start of the helix primitive. end : 3D Vector (tuple or list or numpy.array) The coordinate of the end of the helix primitive...
Below is the the instruction that describes the task: ### Input: Creates a `Helix` between `start` and `end`. Parameters ---------- start : 3D Vector (tuple or list or numpy.array) The coordinate of the start of the helix primitive. end : 3D Vector (tuple or list or nump...
def liftover(self, intersecting_region): """ Lift a region that overlaps the genomic occurrence of the retrotransposon to consensus sequence co-ordinates. This method will behave differently depending on whether this retrotransposon occurrance contains a full alignment or not. If it does, the alignm...
Lift a region that overlaps the genomic occurrence of the retrotransposon to consensus sequence co-ordinates. This method will behave differently depending on whether this retrotransposon occurrance contains a full alignment or not. If it does, the alignment is used to do the liftover and an exact resul...
Below is the the instruction that describes the task: ### Input: Lift a region that overlaps the genomic occurrence of the retrotransposon to consensus sequence co-ordinates. This method will behave differently depending on whether this retrotransposon occurrance contains a full alignment or not. If it ...
def otu_iter_nexson_proxy(nexson_proxy, otu_sort=None): """otu_sort can be None (not sorted or stable), True (sorted by ID lexigraphically) or a key function for a sort function on list of otuIDs Note that if there are multiple OTU groups, the NexSON specifies the order of sorting of the groups (so...
otu_sort can be None (not sorted or stable), True (sorted by ID lexigraphically) or a key function for a sort function on list of otuIDs Note that if there are multiple OTU groups, the NexSON specifies the order of sorting of the groups (so the sort argument here only refers to the sorting of OTUs with...
Below is the the instruction that describes the task: ### Input: otu_sort can be None (not sorted or stable), True (sorted by ID lexigraphically) or a key function for a sort function on list of otuIDs Note that if there are multiple OTU groups, the NexSON specifies the order of sorting of the grou...
def get_cds_ranges_for_transcript(self, transcript_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature=cds".format(transcript_id) r = self.ensembl_re...
obtain the sequence for a transcript from ensembl
Below is the the instruction that describes the task: ### Input: obtain the sequence for a transcript from ensembl ### Response: def get_cds_ranges_for_transcript(self, transcript_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application...
def last_available_business_date(self, asset_manager_id, asset_ids, page_no=None, page_size=None): """ Returns the last available business date for the assets so we know the starting date for new data which needs to be downloaded from data providers. This method can only be inv...
Returns the last available business date for the assets so we know the starting date for new data which needs to be downloaded from data providers. This method can only be invoked by system user
Below is the the instruction that describes the task: ### Input: Returns the last available business date for the assets so we know the starting date for new data which needs to be downloaded from data providers. This method can only be invoked by system user ### Response: def last_availa...
def _get_pattern_for_schema(self, schema_name, httpStatus): ''' returns the pattern specified in a response schema ''' defaultPattern = '.+' if self._is_http_error_rescode(httpStatus) else '.*' model = self._models().get(schema_name) patterns = self._find_patterns(model) ...
returns the pattern specified in a response schema
Below is the the instruction that describes the task: ### Input: returns the pattern specified in a response schema ### Response: def _get_pattern_for_schema(self, schema_name, httpStatus): ''' returns the pattern specified in a response schema ''' defaultPattern = '.+' if self._is_...
def release(self, conn): """Release a previously acquired connection. The connection is put back into the pool.""" self._pool_lock.acquire() self._pool.put(ConnectionWrapper(self._pool, conn)) self._current_acquired -= 1 self._pool_lock.release()
Release a previously acquired connection. The connection is put back into the pool.
Below is the the instruction that describes the task: ### Input: Release a previously acquired connection. The connection is put back into the pool. ### Response: def release(self, conn): """Release a previously acquired connection. The connection is put back into the pool.""" self....
def cli(env, volume_id, reason, immediate): """Cancel existing snapshot space for a given volume.""" file_storage_manager = SoftLayer.FileStorageManager(env.client) if not (env.skip_confirmations or formatting.no_going_back(volume_id)): raise exceptions.CLIAbort('Aborted') cancelled = file_st...
Cancel existing snapshot space for a given volume.
Below is the the instruction that describes the task: ### Input: Cancel existing snapshot space for a given volume. ### Response: def cli(env, volume_id, reason, immediate): """Cancel existing snapshot space for a given volume.""" file_storage_manager = SoftLayer.FileStorageManager(env.client) if not...
def request_add_sensor(self, sock, msg): """ add a sensor """ self.add_sensor(Sensor(int, 'int_sensor%d' % len(self._sensors), 'descr', 'unit', params=[-10, 10])) return Message.reply('add-sensor', 'ok')
add a sensor
Below is the the instruction that describes the task: ### Input: add a sensor ### Response: def request_add_sensor(self, sock, msg): """ add a sensor """ self.add_sensor(Sensor(int, 'int_sensor%d' % len(self._sensors), 'descr', 'unit', params=[-10, 10])) ...
def fullName(self): """ Returns a reliable full name (firstName lastName) for every member (as of the writing of this comment.) """ if self.givenName and self.sn: return "{0} {1}".format(self.givenName, self.sn) if self.givenName: return self.givenName...
Returns a reliable full name (firstName lastName) for every member (as of the writing of this comment.)
Below is the the instruction that describes the task: ### Input: Returns a reliable full name (firstName lastName) for every member (as of the writing of this comment.) ### Response: def fullName(self): """ Returns a reliable full name (firstName lastName) for every member (as of th...
def custom_parser(cards: list, parser: Optional[Callable[[list], Optional[list]]]=None) -> Optional[list]: '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards)
parser for CUSTOM [1] issue mode, please provide your custom parser as argument
Below is the the instruction that describes the task: ### Input: parser for CUSTOM [1] issue mode, please provide your custom parser as argument ### Response: def custom_parser(cards: list, parser: Optional[Callable[[list], Optional[list]]]=None) -> Optional[list]: '''parser for CUSTOM [1] issue mode, ...
def read(self, size=None): """Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all re...
Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: ...
Below is the the instruction that describes the task: ### Input: Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to r...
def mode_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the most frequent value under that column in those rows. """ most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_li...
Takes a list of rows and a column and returns the most frequent value under that column in those rows.
Below is the the instruction that describes the task: ### Input: Takes a list of rows and a column and returns the most frequent value under that column in those rows. ### Response: def mode_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column...
def wploader(self): '''per-sysid wploader''' if self.target_system not in self.wploader_by_sysid: self.wploader_by_sysid[self.target_system] = mavwp.MAVWPLoader() return self.wploader_by_sysid[self.target_system]
per-sysid wploader
Below is the the instruction that describes the task: ### Input: per-sysid wploader ### Response: def wploader(self): '''per-sysid wploader''' if self.target_system not in self.wploader_by_sysid: self.wploader_by_sysid[self.target_system] = mavwp.MAVWPLoader() return self.wpload...
def transform_qubits(self: TSelf_Operation, func: Callable[[Qid], Qid]) -> TSelf_Operation: """Returns the same operation, but with different qubits. Args: func: The function to use to turn each current qubit into a desired new qubit. Return...
Returns the same operation, but with different qubits. Args: func: The function to use to turn each current qubit into a desired new qubit. Returns: The receiving operation but with qubits transformed by the given function.
Below is the the instruction that describes the task: ### Input: Returns the same operation, but with different qubits. Args: func: The function to use to turn each current qubit into a desired new qubit. Returns: The receiving operation but with qubits tran...
def make_name(self): """Autogenerates a :attr:`name` from :attr:`title_for_name`""" if self.title: self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__))
Autogenerates a :attr:`name` from :attr:`title_for_name`
Below is the the instruction that describes the task: ### Input: Autogenerates a :attr:`name` from :attr:`title_for_name` ### Response: def make_name(self): """Autogenerates a :attr:`name` from :attr:`title_for_name`""" if self.title: self.name = six.text_type(make_name(self.title_for_n...
def coerce_to_target_dtype(self, other): """ coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block """ # if we cannot then co...
coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block
Below is the the instruction that describes the task: ### Input: coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block ### Response: def coerce_to_target...
def LinearContrast(alpha=1, per_channel=False, name=None, deterministic=False, random_state=None): """Adjust contrast by scaling each pixel value to ``127 + alpha*(I_ij-127)``. dtype support:: See :func:`imgaug.augmenters.contrast.adjust_contrast_linear`. Parameters ---------- alpha : num...
Adjust contrast by scaling each pixel value to ``127 + alpha*(I_ij-127)``. dtype support:: See :func:`imgaug.augmenters.contrast.adjust_contrast_linear`. Parameters ---------- alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional Multip...
Below is the the instruction that describes the task: ### Input: Adjust contrast by scaling each pixel value to ``127 + alpha*(I_ij-127)``. dtype support:: See :func:`imgaug.augmenters.contrast.adjust_contrast_linear`. Parameters ---------- alpha : number or tuple of number or list of num...
def declare_list(self, name, sep=os.pathsep): """ Declare an environment variable as a list-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered l...
Declare an environment variable as a list-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered list-like. :param sep: The separator to be used. Defaults ...
Below is the the instruction that describes the task: ### Input: Declare an environment variable as a list-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considere...
def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endsw...
Unhook stdout and stderr if buffering is enabled.
Below is the the instruction that describes the task: ### Input: Unhook stdout and stderr if buffering is enabled. ### Response: def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = ...
def prompt_save_images(args): """Prompt user to save images when crawling (for pdf and HTML formats).""" if args['images'] or args['no_images']: return if (args['pdf'] or args['html']) and (args['crawl'] or args['crawl_all']): save_msg = ('Choosing to save images will greatly slow the' ...
Prompt user to save images when crawling (for pdf and HTML formats).
Below is the the instruction that describes the task: ### Input: Prompt user to save images when crawling (for pdf and HTML formats). ### Response: def prompt_save_images(args): """Prompt user to save images when crawling (for pdf and HTML formats).""" if args['images'] or args['no_images']: return...
def IV(abf,T1,T2,plotToo=True,color='b'): """ Given two time points (seconds) return IV data. Optionally plots a fancy graph (with errorbars) Returns [[AV],[SD]] for the given range. """ rangeData=abf.average_data([[T1,T2]]) #get the average data per sweep AV,SD=rangeData[:,0,0],rangeData[:,...
Given two time points (seconds) return IV data. Optionally plots a fancy graph (with errorbars) Returns [[AV],[SD]] for the given range.
Below is the the instruction that describes the task: ### Input: Given two time points (seconds) return IV data. Optionally plots a fancy graph (with errorbars) Returns [[AV],[SD]] for the given range. ### Response: def IV(abf,T1,T2,plotToo=True,color='b'): """ Given two time points (seconds) retur...
def show_worst_drawdown_periods(returns, top=5): """ Prints information about the worst drawdown periods. Prints peak dates, valley dates, recovery dates, and net drawdowns. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full ...
Prints information about the worst drawdown periods. Prints peak dates, valley dates, recovery dates, and net drawdowns. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. top : int, o...
Below is the the instruction that describes the task: ### Input: Prints information about the worst drawdown periods. Prints peak dates, valley dates, recovery dates, and net drawdowns. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - S...
def DeleteAttachment(self, attachment_link, options=None): """Deletes an attachment. :param str attachment_link: The link to the attachment. :param dict options: The request options for the request. :return: The deleted Attachment. :rtype: ...
Deletes an attachment. :param str attachment_link: The link to the attachment. :param dict options: The request options for the request. :return: The deleted Attachment. :rtype: dict
Below is the the instruction that describes the task: ### Input: Deletes an attachment. :param str attachment_link: The link to the attachment. :param dict options: The request options for the request. :return: The deleted Attachment. :rtype: ...
def read_index_iter(self): """Generator function that reads the file index from the vpk file yeilds (file_path, metadata) """ with fopen(self.vpk_path, 'rb') as f: f.seek(self.header_length) while True: if self.version > 0 and f.tell() > self.tr...
Generator function that reads the file index from the vpk file yeilds (file_path, metadata)
Below is the the instruction that describes the task: ### Input: Generator function that reads the file index from the vpk file yeilds (file_path, metadata) ### Response: def read_index_iter(self): """Generator function that reads the file index from the vpk file yeilds (file_path, metada...
def load_from_namespace(module_name): """ Load a py3status bundled module. """ class_inst = None name = "py3status.modules.{}".format(module_name) py_mod = __import__(name) components = name.split(".") for comp in components[1:]: py_mod = getat...
Load a py3status bundled module.
Below is the the instruction that describes the task: ### Input: Load a py3status bundled module. ### Response: def load_from_namespace(module_name): """ Load a py3status bundled module. """ class_inst = None name = "py3status.modules.{}".format(module_name) py_mod =...
def _add_loss_summaries(total_loss): """Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages ...
Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages of losses.
Below is the the instruction that describes the task: ### Input: Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for ...
def _download_libraries(self, libname): """ download enrichr libraries.""" self._logger.info("Downloading and generating Enrichr library gene sets......") s = retry(5) # queery string ENRICHR_URL = 'http://amp.pharm.mssm.edu/Enrichr/geneSetLibrary' query_string = '?mode=t...
download enrichr libraries.
Below is the the instruction that describes the task: ### Input: download enrichr libraries. ### Response: def _download_libraries(self, libname): """ download enrichr libraries.""" self._logger.info("Downloading and generating Enrichr library gene sets......") s = retry(5) # queery...
def _set_config(c): """Set gl configuration""" gl_attribs = [glcanvas.WX_GL_RGBA, glcanvas.WX_GL_DEPTH_SIZE, c['depth_size'], glcanvas.WX_GL_STENCIL_SIZE, c['stencil_size'], glcanvas.WX_GL_MIN_RED, c['red_size'], glcanvas.WX_GL_MIN_GREEN, c...
Set gl configuration
Below is the the instruction that describes the task: ### Input: Set gl configuration ### Response: def _set_config(c): """Set gl configuration""" gl_attribs = [glcanvas.WX_GL_RGBA, glcanvas.WX_GL_DEPTH_SIZE, c['depth_size'], glcanvas.WX_GL_STENCIL_SIZE, c['stencil_size'...
def error(self): """Check if the async response is an error. Take care to call `is_done` before calling `error`. Note that the error messages are always encoded as strings. :raises CloudUnhandledError: When not checking `is_done` first :return: the error value/payload, if found...
Check if the async response is an error. Take care to call `is_done` before calling `error`. Note that the error messages are always encoded as strings. :raises CloudUnhandledError: When not checking `is_done` first :return: the error value/payload, if found. :rtype: str
Below is the the instruction that describes the task: ### Input: Check if the async response is an error. Take care to call `is_done` before calling `error`. Note that the error messages are always encoded as strings. :raises CloudUnhandledError: When not checking `is_done` first :...
def fluxfrac(*mags): """Returns fraction of total flux in first argument, assuming all are magnitudes. """ Ftot = 0 for mag in mags: Ftot += 10**(-0.4*mag) F1 = 10**(-0.4*mags[0]) return F1/Ftot
Returns fraction of total flux in first argument, assuming all are magnitudes.
Below is the the instruction that describes the task: ### Input: Returns fraction of total flux in first argument, assuming all are magnitudes. ### Response: def fluxfrac(*mags): """Returns fraction of total flux in first argument, assuming all are magnitudes. """ Ftot = 0 for mag in mags: ...
def GetUserInfo(knowledge_base, user): # TODO: This docstring cannot be a raw literal because there are # issues with raw unicode literals on Python 2. Once support for Python 2 is # dropped, it can be made raw again. # pylint: disable=g-docstring-has-escape """Get a User protobuf for a specific user. Args...
Get a User protobuf for a specific user. Args: knowledge_base: An rdf_client.KnowledgeBase object. user: Username as string. May contain domain like DOMAIN\\user. Returns: A User rdfvalue or None
Below is the the instruction that describes the task: ### Input: Get a User protobuf for a specific user. Args: knowledge_base: An rdf_client.KnowledgeBase object. user: Username as string. May contain domain like DOMAIN\\user. Returns: A User rdfvalue or None ### Response: def GetUserInfo(knowle...
def __geomToPointList(self, geom): """ converts a geometry object to a common.Geometry object """ if arcpyFound and isinstance(geom, arcpy.Multipoint): feature_geom = [] fPart = [] for part in geom: fPart = [] for pnt in part: ...
converts a geometry object to a common.Geometry object
Below is the the instruction that describes the task: ### Input: converts a geometry object to a common.Geometry object ### Response: def __geomToPointList(self, geom): """ converts a geometry object to a common.Geometry object """ if arcpyFound and isinstance(geom, arcpy.Multipoint): f...
def get_hash(self): """ Returns the associated hash for this template version Returns: str: Hash for this version """ if self._hash is None: self._hash = self._source.get_hash(self._handle).strip() return self._hash
Returns the associated hash for this template version Returns: str: Hash for this version
Below is the the instruction that describes the task: ### Input: Returns the associated hash for this template version Returns: str: Hash for this version ### Response: def get_hash(self): """ Returns the associated hash for this template version Returns: s...
def RGB_color_picker(obj): """Build a color representation from the string representation of an object This allows to quickly get a color from some data, with the additional benefit that the color will be the same as long as the (string representation of the) data is the same:: >>> from colour...
Build a color representation from the string representation of an object This allows to quickly get a color from some data, with the additional benefit that the color will be the same as long as the (string representation of the) data is the same:: >>> from colour import RGB_color_picker, Color ...
Below is the the instruction that describes the task: ### Input: Build a color representation from the string representation of an object This allows to quickly get a color from some data, with the additional benefit that the color will be the same as long as the (string representation of the) data is ...
def build_dependencies(self): """ Recursively build the dependencies for sub-modules and sub-packages. Iterate on node's modules then packages and call their build_dependencies methods. """ for m in self.modules: m.build_dependencies() for p in self.p...
Recursively build the dependencies for sub-modules and sub-packages. Iterate on node's modules then packages and call their build_dependencies methods.
Below is the the instruction that describes the task: ### Input: Recursively build the dependencies for sub-modules and sub-packages. Iterate on node's modules then packages and call their build_dependencies methods. ### Response: def build_dependencies(self): """ Recursively build...
def __setup(): """Will be executed in the first time someone calls classes_*() """ global __collaborators, __flag_first import f311 __flag_first = False for pkgname in f311.COLLABORATORS_C: try: pkg = importlib.import_module(pkgname) a99.get_python_logger().info("Im...
Will be executed in the first time someone calls classes_*()
Below is the the instruction that describes the task: ### Input: Will be executed in the first time someone calls classes_*() ### Response: def __setup(): """Will be executed in the first time someone calls classes_*() """ global __collaborators, __flag_first import f311 __flag_first = False ...
def createPolyline(self, points, strokewidth=1, stroke='black'): """ Creates a Polyline @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all points relevant to the polygon @type strokewidth: string or int @param strokewidth: width of the pen used to...
Creates a Polyline @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all points relevant to the polygon @type strokewidth: string or int @param strokewidth: width of the pen used to draw @type stroke: string (either css constants like "black" or numerical v...
Below is the the instruction that describes the task: ### Input: Creates a Polyline @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all points relevant to the polygon @type strokewidth: string or int @param strokewidth: width of the pen used to draw @t...
def remove_programmer(programmer_id): """remove programmer. :param programmer_id: programmer id (e.g. 'avrisp') :rtype: None """ log.debug('remove %s', programmer_id) lines = programmers_txt().lines() lines = filter( lambda x: not x.strip().startswith(programmer_id + '.'), lines) ...
remove programmer. :param programmer_id: programmer id (e.g. 'avrisp') :rtype: None
Below is the the instruction that describes the task: ### Input: remove programmer. :param programmer_id: programmer id (e.g. 'avrisp') :rtype: None ### Response: def remove_programmer(programmer_id): """remove programmer. :param programmer_id: programmer id (e.g. 'avrisp') :rtype: None ...
def logistic_regression(X, y, coef_only=False, alpha=0.05, as_dataframe=True, remove_na=False, **kwargs): """(Multiple) Binary logistic regression. Parameters ---------- X : np.array or list Predictor(s). Shape = (n_samples, n_features) or (n_samples,). y : np.array ...
(Multiple) Binary logistic regression. Parameters ---------- X : np.array or list Predictor(s). Shape = (n_samples, n_features) or (n_samples,). y : np.array or list Dependent variable. Shape = (n_samples). Must be binary. coef_only : bool If True, return only the re...
Below is the the instruction that describes the task: ### Input: (Multiple) Binary logistic regression. Parameters ---------- X : np.array or list Predictor(s). Shape = (n_samples, n_features) or (n_samples,). y : np.array or list Dependent variable. Shape = (n_samples). Mus...
def _generate_iam_invoke_role_policy(self): """ Generate the policy for the IAM role used by API Gateway to invoke the lambda function. Terraform name: aws_iam_role.invoke_role """ invoke_pol = { "Version": "2012-10-17", "Statement": [ ...
Generate the policy for the IAM role used by API Gateway to invoke the lambda function. Terraform name: aws_iam_role.invoke_role
Below is the the instruction that describes the task: ### Input: Generate the policy for the IAM role used by API Gateway to invoke the lambda function. Terraform name: aws_iam_role.invoke_role ### Response: def _generate_iam_invoke_role_policy(self): """ Generate the policy for th...
def _dusty_hosts_config(hosts_specs): """Return a string of all host rules required to match the given spec. This string is wrapped in the Dusty hosts header and footer so it can be easily removed later.""" rules = ''.join(['{} {}\n'.format(spec['forwarded_ip'], spec['host_address']) for spec in hosts_...
Return a string of all host rules required to match the given spec. This string is wrapped in the Dusty hosts header and footer so it can be easily removed later.
Below is the the instruction that describes the task: ### Input: Return a string of all host rules required to match the given spec. This string is wrapped in the Dusty hosts header and footer so it can be easily removed later. ### Response: def _dusty_hosts_config(hosts_specs): """Return a string of a...
def modify_schema(self, field_schema): """Modify field schema.""" field_schema['maximum'] = self.maximum_value if self.exclusive: field_schema['exclusiveMaximum'] = True
Modify field schema.
Below is the the instruction that describes the task: ### Input: Modify field schema. ### Response: def modify_schema(self, field_schema): """Modify field schema.""" field_schema['maximum'] = self.maximum_value if self.exclusive: field_schema['exclusiveMaximum'] = True
def normalize_url(url): """Return a normalized url with trailing and without leading slash. >>> normalize_url(None) '/' >>> normalize_url('/') '/' >>> normalize_url('/foo/bar') '/foo/bar' >>> normalize_url('foo/bar') '/foo/bar' >>> normalize_url('/foo/bar/') '/foo/...
Return a normalized url with trailing and without leading slash. >>> normalize_url(None) '/' >>> normalize_url('/') '/' >>> normalize_url('/foo/bar') '/foo/bar' >>> normalize_url('foo/bar') '/foo/bar' >>> normalize_url('/foo/bar/') '/foo/bar'
Below is the the instruction that describes the task: ### Input: Return a normalized url with trailing and without leading slash. >>> normalize_url(None) '/' >>> normalize_url('/') '/' >>> normalize_url('/foo/bar') '/foo/bar' >>> normalize_url('foo/bar') '/foo/bar' >>> ...
def visualize(G, settings, filename="dependencies", no_graphviz=False): """ Uses networkX to draw a graphviz dot file either (a) calls the graphviz command "dot" to turn it into a SVG and remove the dotfile (default), or (b) if no_graphviz is True, just output the graphviz dot file Args: ...
Uses networkX to draw a graphviz dot file either (a) calls the graphviz command "dot" to turn it into a SVG and remove the dotfile (default), or (b) if no_graphviz is True, just output the graphviz dot file Args: a NetworkX DiGraph the settings dictionary a filename (a default i...
Below is the the instruction that describes the task: ### Input: Uses networkX to draw a graphviz dot file either (a) calls the graphviz command "dot" to turn it into a SVG and remove the dotfile (default), or (b) if no_graphviz is True, just output the graphviz dot file Args: a NetworkX Di...
def check_row(state, index, missing_msg=None, expand_msg=None): """Zoom in on a particular row in the query result, by index. After zooming in on a row, which is represented as a single-row query result, you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution query res...
Zoom in on a particular row in the query result, by index. After zooming in on a row, which is represented as a single-row query result, you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution query result have a match in the student query result. Args: index:...
Below is the the instruction that describes the task: ### Input: Zoom in on a particular row in the query result, by index. After zooming in on a row, which is represented as a single-row query result, you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution query resul...
def replace(self, **kwargs): """ Return: a new :class:`SlashSeparatedCourseKey` with specific ``kwargs`` replacing their corresponding values. Using CourseLocator's replace function results in a mismatch of __init__ args and kwargs. Replace tries to instantiate a SlashSe...
Return: a new :class:`SlashSeparatedCourseKey` with specific ``kwargs`` replacing their corresponding values. Using CourseLocator's replace function results in a mismatch of __init__ args and kwargs. Replace tries to instantiate a SlashSeparatedCourseKey object with CourseLocator args a...
Below is the the instruction that describes the task: ### Input: Return: a new :class:`SlashSeparatedCourseKey` with specific ``kwargs`` replacing their corresponding values. Using CourseLocator's replace function results in a mismatch of __init__ args and kwargs. Replace tries to i...
def dtype(self): """Pixel data type.""" try: return self.data.dtype except AttributeError: return numpy.dtype('%s%d' % (self._sample_type, self._sample_bytes))
Pixel data type.
Below is the the instruction that describes the task: ### Input: Pixel data type. ### Response: def dtype(self): """Pixel data type.""" try: return self.data.dtype except AttributeError: return numpy.dtype('%s%d' % (self._sample_type, self._sample_bytes))
def reverse(view, *args, **kwargs): ''' User-friendly reverse. Pass arguments and keyword arguments to Django's `reverse` as `args` and `kwargs` arguments, respectively. The special optional keyword argument `query` is a dictionary of query (or GET) parameters that can be appended to the `reverse`d URL. Example...
User-friendly reverse. Pass arguments and keyword arguments to Django's `reverse` as `args` and `kwargs` arguments, respectively. The special optional keyword argument `query` is a dictionary of query (or GET) parameters that can be appended to the `reverse`d URL. Example: reverse('products:category', category...
Below is the the instruction that describes the task: ### Input: User-friendly reverse. Pass arguments and keyword arguments to Django's `reverse` as `args` and `kwargs` arguments, respectively. The special optional keyword argument `query` is a dictionary of query (or GET) parameters that can be appended to th...
def hacking_assert_equal(logical_line, noqa): r"""Check that self.assertEqual and self.assertNotEqual are used. Okay: self.assertEqual(x, y) Okay: self.assertNotEqual(x, y) H204: self.assertTrue(x == y) H204: self.assertTrue(x != y) H204: self.assertFalse(x == y) H204: self.assertFalse(x !=...
r"""Check that self.assertEqual and self.assertNotEqual are used. Okay: self.assertEqual(x, y) Okay: self.assertNotEqual(x, y) H204: self.assertTrue(x == y) H204: self.assertTrue(x != y) H204: self.assertFalse(x == y) H204: self.assertFalse(x != y)
Below is the the instruction that describes the task: ### Input: r"""Check that self.assertEqual and self.assertNotEqual are used. Okay: self.assertEqual(x, y) Okay: self.assertNotEqual(x, y) H204: self.assertTrue(x == y) H204: self.assertTrue(x != y) H204: self.assertFalse(x == y) H204: se...
def delete_feed(self, pid): """Delete a feed, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLi...
Delete a feed, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a...
Below is the the instruction that describes the task: ### Input: Delete a feed, identified by its local id. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink...
def send(self, url, data, headers): """ Spawn an async request to a remote webserver. """ eventlet.spawn(self._send_payload, (url, data, headers))
Spawn an async request to a remote webserver.
Below is the the instruction that describes the task: ### Input: Spawn an async request to a remote webserver. ### Response: def send(self, url, data, headers): """ Spawn an async request to a remote webserver. """ eventlet.spawn(self._send_payload, (url, data, headers))
def team(self, name=None, id=None, is_hidden=False, **kwargs): """ Team of KE-chain. Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id. :param name: (optional) team name to filter :type name: basestring or None :param id: (optional)...
Team of KE-chain. Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id. :param name: (optional) team name to filter :type name: basestring or None :param id: (optional) id of the user to filter :type id: basestring or None :param is_hi...
Below is the the instruction that describes the task: ### Input: Team of KE-chain. Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id. :param name: (optional) team name to filter :type name: basestring or None :param id: (optional) id of the use...
def _extend(self, newsub): ''' Append a subclass (extension) after the base class. For parser internal use. ''' current = self while hasattr(current, '_sub'): current = current._sub _set(current, '_sub', newsub) try: object.__delattr__(self...
Append a subclass (extension) after the base class. For parser internal use.
Below is the the instruction that describes the task: ### Input: Append a subclass (extension) after the base class. For parser internal use. ### Response: def _extend(self, newsub): ''' Append a subclass (extension) after the base class. For parser internal use. ''' current = self ...
def subclass(self, klass): """True if the Class is a subclass of the given one.""" return bool(lib.EnvSubclassP(self._env, self._cls, klass._cls))
True if the Class is a subclass of the given one.
Below is the the instruction that describes the task: ### Input: True if the Class is a subclass of the given one. ### Response: def subclass(self, klass): """True if the Class is a subclass of the given one.""" return bool(lib.EnvSubclassP(self._env, self._cls, klass._cls))
def put(self, item, *args, **kwargs): """Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available...
Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available for retrieval for ``timeout`` s...
Below is the the instruction that describes the task: ### Input: Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item w...
def add_arguments(self, parser): """ Add arguments to the command parser. Uses argparse syntax. See documentation at https://docs.python.org/3/library/argparse.html. """ parser.add_argument( '--dry-run', action='store_true', default=F...
Add arguments to the command parser. Uses argparse syntax. See documentation at https://docs.python.org/3/library/argparse.html.
Below is the the instruction that describes the task: ### Input: Add arguments to the command parser. Uses argparse syntax. See documentation at https://docs.python.org/3/library/argparse.html. ### Response: def add_arguments(self, parser): """ Add arguments to the command parser....
def render_mail_template(subject_template, body_template, context): """ Renders both the subject and body templates in the given context. Returns a tuple (subject, body) of the result. """ try: subject = strip_spaces(render_to_string(subject_template, context)) body = render_to_strin...
Renders both the subject and body templates in the given context. Returns a tuple (subject, body) of the result.
Below is the the instruction that describes the task: ### Input: Renders both the subject and body templates in the given context. Returns a tuple (subject, body) of the result. ### Response: def render_mail_template(subject_template, body_template, context): """ Renders both the subject and body templ...
def use_strategy(new_strategy): """Force the use of a different strategy. This is an alternative to setting default_strategy in the class definition. """ def wrapped_class(klass): klass._meta.strategy = new_strategy return klass return wrapped_class
Force the use of a different strategy. This is an alternative to setting default_strategy in the class definition.
Below is the the instruction that describes the task: ### Input: Force the use of a different strategy. This is an alternative to setting default_strategy in the class definition. ### Response: def use_strategy(new_strategy): """Force the use of a different strategy. This is an alternative to setting...
def cart_create(self, items, **kwargs): """CartCreate. :param items: A dictionary containing the items to be added to the cart. Or a list containing these dictionaries. It is not possible to create an empty cart! example: [{'offer_id': 'rt2ofih3f389nwiuhf8...
CartCreate. :param items: A dictionary containing the items to be added to the cart. Or a list containing these dictionaries. It is not possible to create an empty cart! example: [{'offer_id': 'rt2ofih3f389nwiuhf8934z87o3f4h', 'quantity': 1}] ...
Below is the the instruction that describes the task: ### Input: CartCreate. :param items: A dictionary containing the items to be added to the cart. Or a list containing these dictionaries. It is not possible to create an empty cart! example: [{'offer_id': 'r...
def mel_to_hz(mels, htk=False): """Convert mel bin numbers to frequencies Examples -------- >>> librosa.mel_to_hz(3) 200. >>> librosa.mel_to_hz([1,2,3,4,5]) array([ 66.667, 133.333, 200. , 266.667, 333.333]) Parameters ---------- mels : np.ndarray [shape=(n,)],...
Convert mel bin numbers to frequencies Examples -------- >>> librosa.mel_to_hz(3) 200. >>> librosa.mel_to_hz([1,2,3,4,5]) array([ 66.667, 133.333, 200. , 266.667, 333.333]) Parameters ---------- mels : np.ndarray [shape=(n,)], float mel bins to convert ...
Below is the the instruction that describes the task: ### Input: Convert mel bin numbers to frequencies Examples -------- >>> librosa.mel_to_hz(3) 200. >>> librosa.mel_to_hz([1,2,3,4,5]) array([ 66.667, 133.333, 200. , 266.667, 333.333]) Parameters ---------- mels ...
def prepare_data(self): """Prepare widget data for template.""" result = {} for field in self.fields: data = self.data.get(field.name) result[field.name] = field.prepare_data(data) return result
Prepare widget data for template.
Below is the the instruction that describes the task: ### Input: Prepare widget data for template. ### Response: def prepare_data(self): """Prepare widget data for template.""" result = {} for field in self.fields: data = self.data.get(field.name) result[field.name]...
def compute_ssm(X, metric="seuclidean"): """Computes the self-similarity matrix of X.""" D = distance.pdist(X, metric=metric) D = distance.squareform(D) D /= D.max() return 1 - D
Computes the self-similarity matrix of X.
Below is the the instruction that describes the task: ### Input: Computes the self-similarity matrix of X. ### Response: def compute_ssm(X, metric="seuclidean"): """Computes the self-similarity matrix of X.""" D = distance.pdist(X, metric=metric) D = distance.squareform(D) D /= D.max() return 1...
def id_request(self, device_id): """Get the device for the ID. ID request can return device type (cat/subcat), firmware ver, etc. Cat is status['is_high'], sub cat is status['id_mid']""" self.logger.info("\nid_request for device %s", device_id) device_id = device_id.upper() self...
Get the device for the ID. ID request can return device type (cat/subcat), firmware ver, etc. Cat is status['is_high'], sub cat is status['id_mid']
Below is the the instruction that describes the task: ### Input: Get the device for the ID. ID request can return device type (cat/subcat), firmware ver, etc. Cat is status['is_high'], sub cat is status['id_mid'] ### Response: def id_request(self, device_id): """Get the device for the ID. ID reques...
def on_send(self, frame): """ Add the heartbeat header to the frame when connecting, and bump next outbound heartbeat timestamp. :param Frame frame: the Frame object """ if frame.cmd == CMD_CONNECT or frame.cmd == CMD_STOMP: if self.heartbeats != (0, 0): ...
Add the heartbeat header to the frame when connecting, and bump next outbound heartbeat timestamp. :param Frame frame: the Frame object
Below is the the instruction that describes the task: ### Input: Add the heartbeat header to the frame when connecting, and bump next outbound heartbeat timestamp. :param Frame frame: the Frame object ### Response: def on_send(self, frame): """ Add the heartbeat header to the frame...
def create_udf_node(name, fields): """Create a new UDF node type. Parameters ---------- name : str Then name of the UDF node fields : OrderedDict Mapping of class member name to definition Returns ------- result : type A new BigQueryUDFNode subclass """ ...
Create a new UDF node type. Parameters ---------- name : str Then name of the UDF node fields : OrderedDict Mapping of class member name to definition Returns ------- result : type A new BigQueryUDFNode subclass
Below is the the instruction that describes the task: ### Input: Create a new UDF node type. Parameters ---------- name : str Then name of the UDF node fields : OrderedDict Mapping of class member name to definition Returns ------- result : type A new BigQueryUD...
def visit_Module(self, node): """ Build a compilation unit. """ # build all types deps = sorted(self.dependencies) headers = [Include(os.path.join("pythonic", "include", *t) + ".hpp") for t in deps] headers += [Include(os.path.join("pythonic", *t) + ".hpp") ...
Build a compilation unit.
Below is the the instruction that describes the task: ### Input: Build a compilation unit. ### Response: def visit_Module(self, node): """ Build a compilation unit. """ # build all types deps = sorted(self.dependencies) headers = [Include(os.path.join("pythonic", "include", *t) + "...
def adjust_internal_tacking_values(self, min_non_zero_index, max_index, total_added): '''Called during decoding and add to adjust the new min/max value and total count Args: ...
Called during decoding and add to adjust the new min/max value and total count Args: min_non_zero_index min nonzero index of all added counts (-1 if none) max_index max index of all added counts (-1 if none)
Below is the the instruction that describes the task: ### Input: Called during decoding and add to adjust the new min/max value and total count Args: min_non_zero_index min nonzero index of all added counts (-1 if none) max_index max index of all added counts (-1 if none) ##...
def has_method(obj, name): """ Checks if object has a method with specified name. :param obj: an object to introspect. :param name: a name of the method to check. :return: true if the object has the method and false if it doesn't. """ if obj == None: ...
Checks if object has a method with specified name. :param obj: an object to introspect. :param name: a name of the method to check. :return: true if the object has the method and false if it doesn't.
Below is the the instruction that describes the task: ### Input: Checks if object has a method with specified name. :param obj: an object to introspect. :param name: a name of the method to check. :return: true if the object has the method and false if it doesn't. ### Response: def has_m...
def copy(self, deep=True): """ Make a copy of this object's indices and data. When ``deep=True`` (default), a new object will be created with a copy of the calling object's data and indices. Modifications to the data or indices of the copy will not be reflected in the or...
Make a copy of this object's indices and data. When ``deep=True`` (default), a new object will be created with a copy of the calling object's data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below). When ...
Below is the the instruction that describes the task: ### Input: Make a copy of this object's indices and data. When ``deep=True`` (default), a new object will be created with a copy of the calling object's data and indices. Modifications to the data or indices of the copy will not be refle...
def Shell(device, *command): """Runs a command on the device and prints the stdout. Args: command: Command to run on the target. """ if command: return device.StreamingShell(' '.join(command)) else: # Retrieve the initial terminal prompt to use as a delimiter for future reads ...
Runs a command on the device and prints the stdout. Args: command: Command to run on the target.
Below is the the instruction that describes the task: ### Input: Runs a command on the device and prints the stdout. Args: command: Command to run on the target. ### Response: def Shell(device, *command): """Runs a command on the device and prints the stdout. Args: command: Command to run...
def iterate_sequences( consumer_fn, output_template, sequences, length, chunk_length=None, batch_size=None, num_epochs=1, padding_value=0): """Iterate over batches of chunks of sequences for multiple epochs. The batch dimension of the length tensor must be set because it is used to infer buffer sizes. ...
Iterate over batches of chunks of sequences for multiple epochs. The batch dimension of the length tensor must be set because it is used to infer buffer sizes. Args: consumer_fn: Function creating the operation to process the data. output_template: Nested tensors of same shape and dtype as outputs. ...
Below is the the instruction that describes the task: ### Input: Iterate over batches of chunks of sequences for multiple epochs. The batch dimension of the length tensor must be set because it is used to infer buffer sizes. Args: consumer_fn: Function creating the operation to process the data. out...
def applyIndex(self, lst, right): """Apply a list to something else.""" if len(right) != 1: raise exceptions.EvaluationError('%r can only be applied to one argument, got %r' % (self.left, self.right)) right = right[0] if isinstance(right, int): return lst[right] raise exceptions.Evalua...
Apply a list to something else.
Below is the the instruction that describes the task: ### Input: Apply a list to something else. ### Response: def applyIndex(self, lst, right): """Apply a list to something else.""" if len(right) != 1: raise exceptions.EvaluationError('%r can only be applied to one argument, got %r' % (self.left, se...
def print_user(user): """ Prints information about the current user. """ email = user['email'] domain = user['account']['domain'] role = user['role'] print('You are logged-in to the "{0}" domain ' 'as {1} with role {2}.' .format(domain, email, role))
Prints information about the current user.
Below is the the instruction that describes the task: ### Input: Prints information about the current user. ### Response: def print_user(user): """ Prints information about the current user. """ email = user['email'] domain = user['account']['domain'] role = user['role'] print('You are ...
def list_vms(self, allow_clone=False): """ Gets VirtualBox VM list. """ vbox_vms = [] result = yield from self.execute("list", ["vms"]) for line in result: if len(line) == 0 or line[0] != '"' or line[-1:] != "}": continue # Broken output (per...
Gets VirtualBox VM list.
Below is the the instruction that describes the task: ### Input: Gets VirtualBox VM list. ### Response: def list_vms(self, allow_clone=False): """ Gets VirtualBox VM list. """ vbox_vms = [] result = yield from self.execute("list", ["vms"]) for line in result: ...
def getReflexRuleSetup(self): """ Return a json dict with all the setup data necessary to build the relations: - Relations between methods and analysis services options. - The current saved data the functions returns: {'<method_uid>': { 'analysisservic...
Return a json dict with all the setup data necessary to build the relations: - Relations between methods and analysis services options. - The current saved data the functions returns: {'<method_uid>': { 'analysisservices': { '<as_uid>': {'as_id': '<as_...
Below is the the instruction that describes the task: ### Input: Return a json dict with all the setup data necessary to build the relations: - Relations between methods and analysis services options. - The current saved data the functions returns: {'<method_uid>': { ...
def affine_respective_zoom_matrix(w_range=0.8, h_range=1.1): """Get affine transform matrix for zooming/scaling that height and width are changed independently. OpenCV format, x is width. Parameters ----------- w_range : float or tuple of 2 floats The zooming/scaling ratio of width, greater...
Get affine transform matrix for zooming/scaling that height and width are changed independently. OpenCV format, x is width. Parameters ----------- w_range : float or tuple of 2 floats The zooming/scaling ratio of width, greater than 1 means larger. - float, a fixed ratio. ...
Below is the the instruction that describes the task: ### Input: Get affine transform matrix for zooming/scaling that height and width are changed independently. OpenCV format, x is width. Parameters ----------- w_range : float or tuple of 2 floats The zooming/scaling ratio of width, greate...
def parent_suite(self): """Get the current parent suite. A parent suite exists when a context within a suite is active. That is, during execution of a tool within a suite, or after a user has entered an interactive shell in a suite context, for example via the command- line synt...
Get the current parent suite. A parent suite exists when a context within a suite is active. That is, during execution of a tool within a suite, or after a user has entered an interactive shell in a suite context, for example via the command- line syntax 'tool +i', where 'tool' is an al...
Below is the the instruction that describes the task: ### Input: Get the current parent suite. A parent suite exists when a context within a suite is active. That is, during execution of a tool within a suite, or after a user has entered an interactive shell in a suite context, for example ...
def blt(f: List[SYM], x: List[SYM]) -> Dict[str, Any]: """ Sort equations by dependence """ J = ca.jacobian(f, x) nblock, rowperm, colperm, rowblock, colblock, coarserow, coarsecol = J.sparsity().btf() return { 'J': J, 'nblock': nblock, 'rowperm': rowperm, 'colper...
Sort equations by dependence
Below is the the instruction that describes the task: ### Input: Sort equations by dependence ### Response: def blt(f: List[SYM], x: List[SYM]) -> Dict[str, Any]: """ Sort equations by dependence """ J = ca.jacobian(f, x) nblock, rowperm, colperm, rowblock, colblock, coarserow, coarsecol = J.sp...
def get(self, instance, **kw): """Get the value of the field """ # Gracefully avoid programming errors in Computed fields try: return self._get(instance, **kw) except AttributeError: logger.error("Could not get the value of the computed field '{}'" ...
Get the value of the field
Below is the the instruction that describes the task: ### Input: Get the value of the field ### Response: def get(self, instance, **kw): """Get the value of the field """ # Gracefully avoid programming errors in Computed fields try: return self._get(instance, **kw) ...
def validate_request(self, path, action, body=None, query=None): """Check if the given request is valid. Validates the body and the query # Rules to validate the BODY: # Let's limit this to mime types that either contain 'text' or 'json' # 1. if body is None, there m...
Check if the given request is valid. Validates the body and the query # Rules to validate the BODY: # Let's limit this to mime types that either contain 'text' or 'json' # 1. if body is None, there must not be any required parameters in # the given schema ...
Below is the the instruction that describes the task: ### Input: Check if the given request is valid. Validates the body and the query # Rules to validate the BODY: # Let's limit this to mime types that either contain 'text' or 'json' # 1. if body is None, there must not...
def _find_rule_no(self, mac): """Find rule number associated with a given mac.""" ipt_cmd = ['iptables', '-L', '--line-numbers'] cmdo = dsl.execute(ipt_cmd, self._root_helper, log_output=False) for o in cmdo.split('\n'): if mac in o.lower(): rule_no = o.split...
Find rule number associated with a given mac.
Below is the the instruction that describes the task: ### Input: Find rule number associated with a given mac. ### Response: def _find_rule_no(self, mac): """Find rule number associated with a given mac.""" ipt_cmd = ['iptables', '-L', '--line-numbers'] cmdo = dsl.execute(ipt_cmd, self._ro...
def modelsClearAll(self): """ Delete all models from the models table Parameters: ---------------------------------------------------------------- """ self._logger.info('Deleting all rows from models table %r', self.modelsTableName) with ConnectionFactory.get() as conn: ...
Delete all models from the models table Parameters: ----------------------------------------------------------------
Below is the the instruction that describes the task: ### Input: Delete all models from the models table Parameters: ---------------------------------------------------------------- ### Response: def modelsClearAll(self): """ Delete all models from the models table Parameters: ---------------...
def source(self, format='xml', accessible=False): """ Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json' """ if accessible: return self.http.get('/wda/accessibleSource').val...
Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json'
Below is the the instruction that describes the task: ### Input: Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json' ### Response: def source(self, format='xml', accessible=False): """ Args: ...
def _init_metadata(self): """stub""" super(LabelOrthoFacesAnswerFormRecord, self)._init_metadata() self._face_values_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'face...
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def _init_metadata(self): """stub""" super(LabelOrthoFacesAnswerFormRecord, self)._init_metadata() self._face_values_metadata = { 'element_id': Id(self.my_osid_object_form._authority, ...
def enable_apt_repositories(prefix, url, version, repositories): """ adds an apt repository """ with settings(hide('warnings', 'running', 'stdout'), warn_only=False, capture=True): sudo('apt-add-repository "%s %s %s %s"' % (prefix, url...
adds an apt repository
Below is the the instruction that describes the task: ### Input: adds an apt repository ### Response: def enable_apt_repositories(prefix, url, version, repositories): """ adds an apt repository """ with settings(hide('warnings', 'running', 'stdout'), warn_only=False, capture=True): ...
def plotres(psr,deleted=False,group=None,**kwargs): """Plot residuals, compute unweighted rms residual.""" res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs if (not deleted) and N.any(psr.deleted != 0): res, t, errs = res[psr.deleted == 0], t[psr.deleted == 0], errs[psr.deleted == 0] ...
Plot residuals, compute unweighted rms residual.
Below is the the instruction that describes the task: ### Input: Plot residuals, compute unweighted rms residual. ### Response: def plotres(psr,deleted=False,group=None,**kwargs): """Plot residuals, compute unweighted rms residual.""" res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs if (no...
def has_activity(graph: BELGraph, node: BaseEntity) -> bool: """Return true if over any of the node's edges, it has a molecular activity.""" return _node_has_modifier(graph, node, ACTIVITY)
Return true if over any of the node's edges, it has a molecular activity.
Below is the the instruction that describes the task: ### Input: Return true if over any of the node's edges, it has a molecular activity. ### Response: def has_activity(graph: BELGraph, node: BaseEntity) -> bool: """Return true if over any of the node's edges, it has a molecular activity.""" return _node_...
def thread( mafs, species ): """ Restrict an list of alignments to a given list of species by: 1) Removing components for any other species 2) Remove any columns containing all gaps Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( '''...
Restrict an list of alignments to a given list of species by: 1) Removing components for any other species 2) Remove any columns containing all gaps Example: >>> import bx.align.maf >>> block1 = bx.align.maf.from_string( ''' ... a score=4964.0 ... s hg18.ch...
Below is the the instruction that describes the task: ### Input: Restrict an list of alignments to a given list of species by: 1) Removing components for any other species 2) Remove any columns containing all gaps Example: >>> import bx.align.maf >>> block1 = b...
def get_component_tasks(self, component_id): """Returns the task ids allocated for the given component id""" ret = [] for task_id, comp_id in self.task_to_component_map.items(): if comp_id == component_id: ret.append(task_id) return ret
Returns the task ids allocated for the given component id
Below is the the instruction that describes the task: ### Input: Returns the task ids allocated for the given component id ### Response: def get_component_tasks(self, component_id): """Returns the task ids allocated for the given component id""" ret = [] for task_id, comp_id in self.task_to_component_m...
def check_stop_times( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: """ Analog of :func:`check_agency` for ``feed.stop_times``. """ table = "stop_times" problems = [] # Preliminary checks if feed.stop_times is None: problems.append(["error", "Mi...
Analog of :func:`check_agency` for ``feed.stop_times``.
Below is the the instruction that describes the task: ### Input: Analog of :func:`check_agency` for ``feed.stop_times``. ### Response: def check_stop_times( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: """ Analog of :func:`check_agency` for ``feed.stop_times``. ""...
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name ...
A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path o...
Below is the the instruction that describes the task: ### Input: A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for...
def _get_image(self, name): """ Returns the QImage stored as the ImageResource with 'name'. """ document = self._control.document() image = document.resource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(name)) return image
Returns the QImage stored as the ImageResource with 'name'.
Below is the the instruction that describes the task: ### Input: Returns the QImage stored as the ImageResource with 'name'. ### Response: def _get_image(self, name): """ Returns the QImage stored as the ImageResource with 'name'. """ document = self._control.document() image = docu...
def retrieve_metar(station_icao) -> typing.Tuple[typing.Optional[str], typing.Optional[str]]: """ Retrieves a METAR string from an online database Args: station_icao: ICAO of the station Returns: tuple of error, metar_str """ url = _BASE_METAR_URL.format(station=station_icao) ...
Retrieves a METAR string from an online database Args: station_icao: ICAO of the station Returns: tuple of error, metar_str
Below is the the instruction that describes the task: ### Input: Retrieves a METAR string from an online database Args: station_icao: ICAO of the station Returns: tuple of error, metar_str ### Response: def retrieve_metar(station_icao) -> typing.Tuple[typing.Optional[str], typing.Optional...
def _add_command(self, name, **parameters): """ Add a new command to the blueprint. :param name: The command name :type name: str :param parameters: The command parameters :type parameters: dict :rtype: Fluent """ command = self._create_command(...
Add a new command to the blueprint. :param name: The command name :type name: str :param parameters: The command parameters :type parameters: dict :rtype: Fluent
Below is the the instruction that describes the task: ### Input: Add a new command to the blueprint. :param name: The command name :type name: str :param parameters: The command parameters :type parameters: dict :rtype: Fluent ### Response: def _add_command(self, name, **...
def browser(i): """ Input: { (template) - use this web template (repo_uoa) - (module_uoa) - (data_uoa) - view a given entry (extra_url) - extra URL } Output: { return - return code = 0, if succes...
Input: { (template) - use this web template (repo_uoa) - (module_uoa) - (data_uoa) - view a given entry (extra_url) - extra URL } Output: { return - return code = 0, if successful ...
Below is the the instruction that describes the task: ### Input: Input: { (template) - use this web template (repo_uoa) - (module_uoa) - (data_uoa) - view a given entry (extra_url) - extra URL } Output: { r...
def read_file(filename): """Read contents of the specified file. Parameters: ----------- filename : str The name of the file to be read Returns: lines : list of str The contents of the file, split by line """ infile = open(filename, 'r') lines = infile.readlines() infile.cl...
Read contents of the specified file. Parameters: ----------- filename : str The name of the file to be read Returns: lines : list of str The contents of the file, split by line
Below is the the instruction that describes the task: ### Input: Read contents of the specified file. Parameters: ----------- filename : str The name of the file to be read Returns: lines : list of str The contents of the file, split by line ### Response: def read_file(filename): ""...