code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def parse_legacy_argstring(argstring): ''' Preparses CLI input: ``arg1,arg2`` => ``['arg1', 'arg2']`` ``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]`` ''' argstring = argstring.replace(',', ' , ') argstring = argstring.replace('[', ' [ ') argstring = argstring.replace(']', ' ]...
Preparses CLI input: ``arg1,arg2`` => ``['arg1', 'arg2']`` ``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]``
Below is the the instruction that describes the task: ### Input: Preparses CLI input: ``arg1,arg2`` => ``['arg1', 'arg2']`` ``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]`` ### Response: def parse_legacy_argstring(argstring): ''' Preparses CLI input: ``arg1,arg2`` => ``['arg1', 'arg2...
def apply(self, **kwargs): """Return a new FeatureCollection with the results of applying the statements in the arguments to each element. """ def _apply(f): properties = copy.deepcopy(f.properties) for prop, value in kwargs.items(): if callable(value): ...
Return a new FeatureCollection with the results of applying the statements in the arguments to each element.
Below is the the instruction that describes the task: ### Input: Return a new FeatureCollection with the results of applying the statements in the arguments to each element. ### Response: def apply(self, **kwargs): """Return a new FeatureCollection with the results of applying the statements in the argumen...
def verify_password(password, password_hash): """Returns ``True`` if the password matches the supplied hash. :param password: A plaintext password to verify :param password_hash: The expected hash value of the password (usually from your database) """ if use_double_hash(pa...
Returns ``True`` if the password matches the supplied hash. :param password: A plaintext password to verify :param password_hash: The expected hash value of the password (usually from your database)
Below is the the instruction that describes the task: ### Input: Returns ``True`` if the password matches the supplied hash. :param password: A plaintext password to verify :param password_hash: The expected hash value of the password (usually from your database) ### Response: de...
def create(self): """ Create item under file system with its path. Returns: True if its path does not exist, False otherwise. """ if os.path.isfile(self.path): if not os.path.exists(self.path): with open(self.path, 'w') as fileobj: ...
Create item under file system with its path. Returns: True if its path does not exist, False otherwise.
Below is the the instruction that describes the task: ### Input: Create item under file system with its path. Returns: True if its path does not exist, False otherwise. ### Response: def create(self): """ Create item under file system with its path. Returns: ...
def run_suite(self, suite, **kwargs): """This is the version from Django 1.7.""" return self.test_runner( verbosity=self.verbosity, failfast=self.failfast, no_colour=self.no_colour, ).run(suite)
This is the version from Django 1.7.
Below is the the instruction that describes the task: ### Input: This is the version from Django 1.7. ### Response: def run_suite(self, suite, **kwargs): """This is the version from Django 1.7.""" return self.test_runner( verbosity=self.verbosity, failfast=self.failfast, ...
def format_rpc(self, address, rpc_id, payload): """Create a formated word list that encodes this rpc.""" addr_word = (rpc_id | (address << 16) | ((1 << 1) << 24)) send_length = len(payload) if len(payload) < 20: payload = payload + b'\0'*(20 - len(payload)) payload...
Create a formated word list that encodes this rpc.
Below is the the instruction that describes the task: ### Input: Create a formated word list that encodes this rpc. ### Response: def format_rpc(self, address, rpc_id, payload): """Create a formated word list that encodes this rpc.""" addr_word = (rpc_id | (address << 16) | ((1 << 1) << 24)) ...
def try_convert(value): """Convert value to a numeric value or raise a ValueError if that isn't possible. """ convertible = ForceNumeric.is_convertible(value) if not convertible or isinstance(value, bool): raise ValueError if isinstance(str(value), str): ...
Convert value to a numeric value or raise a ValueError if that isn't possible.
Below is the the instruction that describes the task: ### Input: Convert value to a numeric value or raise a ValueError if that isn't possible. ### Response: def try_convert(value): """Convert value to a numeric value or raise a ValueError if that isn't possible. """ conver...
def parse(self, data, extent): # type: (bytes, int) -> None ''' Parse the passed in data into a UDF Descriptor tag. Parameters: data - The data to parse. extent - The extent to compare against for the tag location. Returns: Nothing. ''' ...
Parse the passed in data into a UDF Descriptor tag. Parameters: data - The data to parse. extent - The extent to compare against for the tag location. Returns: Nothing.
Below is the the instruction that describes the task: ### Input: Parse the passed in data into a UDF Descriptor tag. Parameters: data - The data to parse. extent - The extent to compare against for the tag location. Returns: Nothing. ### Response: def parse(self, data, e...
def has(self, name, ignore_empty=False): """Return ``True`` if any parameter in the template is named *name*. With *ignore_empty*, ``False`` will be returned even if the template contains a parameter with the name *name*, if the parameter's value is empty. Note that a template may have ...
Return ``True`` if any parameter in the template is named *name*. With *ignore_empty*, ``False`` will be returned even if the template contains a parameter with the name *name*, if the parameter's value is empty. Note that a template may have multiple parameters with the same name, but ...
Below is the the instruction that describes the task: ### Input: Return ``True`` if any parameter in the template is named *name*. With *ignore_empty*, ``False`` will be returned even if the template contains a parameter with the name *name*, if the parameter's value is empty. Note that a t...
def object_id(self): """(:class:`numbers.Integral`) The identifier number of the image. It uses the primary key if it's integer, but can be overridden, and must be implemented when the primary key is not integer or composite key. .. versionchanged:: 1.1.0 Since 1.1.0,...
(:class:`numbers.Integral`) The identifier number of the image. It uses the primary key if it's integer, but can be overridden, and must be implemented when the primary key is not integer or composite key. .. versionchanged:: 1.1.0 Since 1.1.0, it provides a more default impl...
Below is the the instruction that describes the task: ### Input: (:class:`numbers.Integral`) The identifier number of the image. It uses the primary key if it's integer, but can be overridden, and must be implemented when the primary key is not integer or composite key. .. versionch...
def config_set(self, parameter, value): """Set a configuration parameter to the given value.""" if not isinstance(parameter, str): raise TypeError("parameter must be str") fut = self.execute(b'CONFIG', b'SET', parameter, value) return wait_ok(fut)
Set a configuration parameter to the given value.
Below is the the instruction that describes the task: ### Input: Set a configuration parameter to the given value. ### Response: def config_set(self, parameter, value): """Set a configuration parameter to the given value.""" if not isinstance(parameter, str): raise TypeError("parameter ...
def join(input_files, output_file): ''' Join geojsons into one. The spatial reference system of the output file is the same as the one of the last file in the list. Args: input_files (list): List of file name strings. output_file (str): Output file name. ''' # get feature c...
Join geojsons into one. The spatial reference system of the output file is the same as the one of the last file in the list. Args: input_files (list): List of file name strings. output_file (str): Output file name.
Below is the the instruction that describes the task: ### Input: Join geojsons into one. The spatial reference system of the output file is the same as the one of the last file in the list. Args: input_files (list): List of file name strings. output_file (str): Output file name. ### Res...
def extract_stack(start=0): """ SNAGGED FROM traceback.py Altered to return Data Extract the raw traceback from the current stack frame. Each item in the returned list is a quadruple (filename, line number, function name, text), and the entries are in order from newest to oldest """ ...
SNAGGED FROM traceback.py Altered to return Data Extract the raw traceback from the current stack frame. Each item in the returned list is a quadruple (filename, line number, function name, text), and the entries are in order from newest to oldest
Below is the the instruction that describes the task: ### Input: SNAGGED FROM traceback.py Altered to return Data Extract the raw traceback from the current stack frame. Each item in the returned list is a quadruple (filename, line number, function name, text), and the entries are in order fro...
def _on_client_connect(self, data): """Handle client connect.""" client = None if data.get('id') in self._clients: client = self._clients[data.get('id')] client.update_connected(True) else: client = Snapclient(self, data.get('client')) self...
Handle client connect.
Below is the the instruction that describes the task: ### Input: Handle client connect. ### Response: def _on_client_connect(self, data): """Handle client connect.""" client = None if data.get('id') in self._clients: client = self._clients[data.get('id')] client.upda...
def branchpoints(image, mask=None): '''Remove all pixels from an image except for branchpoints image - a skeletonized image mask - a mask of pixels excluded from consideration 1 0 1 ? 0 ? 0 1 0 -> 0 1 0 0 1 0 0 ? 0 ''' global branchpoints_table if mask is None: ...
Remove all pixels from an image except for branchpoints image - a skeletonized image mask - a mask of pixels excluded from consideration 1 0 1 ? 0 ? 0 1 0 -> 0 1 0 0 1 0 0 ? 0
Below is the the instruction that describes the task: ### Input: Remove all pixels from an image except for branchpoints image - a skeletonized image mask - a mask of pixels excluded from consideration 1 0 1 ? 0 ? 0 1 0 -> 0 1 0 0 1 0 0 ? 0 ### Response: def branchpoints(image,...
def build_bootdisk(self, image, size=10, auto_delete=True): """Buid a disk struct. :param image: Base image name. :type image: ``str`` :param size: Persistent disk size. :type size: ``int`` :param auto_delete: Wether to auto delete disk on instance termination. ...
Buid a disk struct. :param image: Base image name. :type image: ``str`` :param size: Persistent disk size. :type size: ``int`` :param auto_delete: Wether to auto delete disk on instance termination. :type auto_delete: ``bool``
Below is the the instruction that describes the task: ### Input: Buid a disk struct. :param image: Base image name. :type image: ``str`` :param size: Persistent disk size. :type size: ``int`` :param auto_delete: Wether to auto delete disk on instance termination. ...
def resolve_global_executable(path, is_version_required=False): """ :param path: A string which is supposed to identify a global executable (app or workflow) :type path: string :param is_version_required: If set to True, the path has to specify a specific version/alias, e.g. "myapp/1.0.0" :type is_v...
:param path: A string which is supposed to identify a global executable (app or workflow) :type path: string :param is_version_required: If set to True, the path has to specify a specific version/alias, e.g. "myapp/1.0.0" :type is_version_required: boolean :returns: The describe hash of the global execu...
Below is the the instruction that describes the task: ### Input: :param path: A string which is supposed to identify a global executable (app or workflow) :type path: string :param is_version_required: If set to True, the path has to specify a specific version/alias, e.g. "myapp/1.0.0" :type is_version_...
def find_version(): """Only define version in one place""" version_file = read_file('__init__.py') version_match = re.search(r'^__version__ = ["\']([^"\']*)["\']', version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to ...
Only define version in one place
Below is the the instruction that describes the task: ### Input: Only define version in one place ### Response: def find_version(): """Only define version in one place""" version_file = read_file('__init__.py') version_match = re.search(r'^__version__ = ["\']([^"\']*)["\']', ...
def create(parser_func: Union[ParsingMethodForStream, ParsingMethodForFile], caught: Exception): """ Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param parser_func: :par...
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param parser_func: :param caught: :return:
Below is the the instruction that describes the task: ### Input: Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param parser_func: :param caught: :return: ### Response: def c...
def get_hosts(self): """ Return a list of parsed hosts info, with the limit applied if required. """ limited_hosts = {} if self.limit is not None: # Find hosts and groups of hosts to include for include in self.limit['include']: # Include w...
Return a list of parsed hosts info, with the limit applied if required.
Below is the the instruction that describes the task: ### Input: Return a list of parsed hosts info, with the limit applied if required. ### Response: def get_hosts(self): """ Return a list of parsed hosts info, with the limit applied if required. """ limited_hosts = {} if s...
def t_DOUBLECOLON(self, t): r"::" t.endlexpos = t.lexpos + len(t.value) return t
r"::
Below is the the instruction that describes the task: ### Input: r":: ### Response: def t_DOUBLECOLON(self, t): r"::" t.endlexpos = t.lexpos + len(t.value) return t
def clear(board, term, height): """Clear the droppings of the given board.""" for y in xrange(height): print term.move(y, 0) + term.clear_eol,
Clear the droppings of the given board.
Below is the the instruction that describes the task: ### Input: Clear the droppings of the given board. ### Response: def clear(board, term, height): """Clear the droppings of the given board.""" for y in xrange(height): print term.move(y, 0) + term.clear_eol,
def deserialize(json_text=None): """Returns a generator of deserialized objects. Wraps django deserialize with defaults for JSON and natural keys. See https://docs.djangoproject.com/en/2.1/topics/serialization/ """ return serializers.deserialize( "json", json_text, ens...
Returns a generator of deserialized objects. Wraps django deserialize with defaults for JSON and natural keys. See https://docs.djangoproject.com/en/2.1/topics/serialization/
Below is the the instruction that describes the task: ### Input: Returns a generator of deserialized objects. Wraps django deserialize with defaults for JSON and natural keys. See https://docs.djangoproject.com/en/2.1/topics/serialization/ ### Response: def deserialize(json_text=None): """Returns...
def to_unicode(value: Union[None, str, bytes]) -> Optional[str]: # noqa: F811 """Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, _TO_U...
Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8.
Below is the the instruction that describes the task: ### Input: Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. ### Response: def to_unicode(value: Union[None, str, b...
def textMerge(self, second): """Merge two text nodes into one """ if second is None: second__o = None else: second__o = second._o ret = libxml2mod.xmlTextMerge(self._o, second__o) if ret is None:raise treeError('xmlTextMerge() failed') __tmp = xmlNode(_obj=ret) re...
Merge two text nodes into one
Below is the the instruction that describes the task: ### Input: Merge two text nodes into one ### Response: def textMerge(self, second): """Merge two text nodes into one """ if second is None: second__o = None else: second__o = second._o ret = libxml2mod.xmlTextMerge(self._o, secon...
def get_signature_candidate(lines): """Return lines that could hold signature The lines should: * be among last SIGNATURE_MAX_LINES non-empty lines. * not include first line * be shorter than TOO_LONG_SIGNATURE_LINE * not include more than one line that starts with dashes """ # non emp...
Return lines that could hold signature The lines should: * be among last SIGNATURE_MAX_LINES non-empty lines. * not include first line * be shorter than TOO_LONG_SIGNATURE_LINE * not include more than one line that starts with dashes
Below is the the instruction that describes the task: ### Input: Return lines that could hold signature The lines should: * be among last SIGNATURE_MAX_LINES non-empty lines. * not include first line * be shorter than TOO_LONG_SIGNATURE_LINE * not include more than one line that starts with da...
def get_aspect(self, xspan, yspan): """ Computes the aspect ratio of the plot """ if self.data_aspect: return (yspan/xspan)*self.data_aspect elif self.aspect == 'equal': return xspan/yspan elif self.aspect == 'square': return 1 ...
Computes the aspect ratio of the plot
Below is the the instruction that describes the task: ### Input: Computes the aspect ratio of the plot ### Response: def get_aspect(self, xspan, yspan): """ Computes the aspect ratio of the plot """ if self.data_aspect: return (yspan/xspan)*self.data_aspect elif ...
def normalize_partial_name(decl): """ Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name """ if decl.cache.normalized_partial_name is None: decl.cache.normalized_partial_name = normalize(decl.partial_name) ...
Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name
Below is the the instruction that describes the task: ### Input: Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name ### Response: def normalize_partial_name(decl): """ Cached variant of normalize Args: dec...
def flags(self, index): """ Returns the item flags for the given index. """ if not index.isValid(): return 0 cti = self.getItem(index) result = Qt.ItemIsSelectable if cti.enabled: result |= Qt.ItemIsEnabled if index.column() == self.COL...
Returns the item flags for the given index.
Below is the the instruction that describes the task: ### Input: Returns the item flags for the given index. ### Response: def flags(self, index): """ Returns the item flags for the given index. """ if not index.isValid(): return 0 cti = self.getItem(index) res...
def copy(self, dest, src): """Copy element from sequence, member from mapping. :param dest: the destination :type dest: Pointer :param src: the source :type src: Pointer :return: resolved document :rtype: Target """ doc = fragment = deepcopy(self....
Copy element from sequence, member from mapping. :param dest: the destination :type dest: Pointer :param src: the source :type src: Pointer :return: resolved document :rtype: Target
Below is the the instruction that describes the task: ### Input: Copy element from sequence, member from mapping. :param dest: the destination :type dest: Pointer :param src: the source :type src: Pointer :return: resolved document :rtype: Target ### Response: def c...
def phylogeny(sequences=None, project_dir=None, name=None, aln_file=None, tree_file=None, seq_field=None, name_field=None, aa=False, species='human', unrooted=False, ladderize=True, root=None, root_name=None, show_root_name=False, color_dict=None, color_function=None, order_dict=None, order_func...
Generates a lineage phylogeny figure. Args: sequences (list(Sequence)): A list of ``Sequence`` objects from which a phylogeny will be calculated. Strictly speaking, they do not need to be ``Sequence`` objects, rather, any object that contains the sequence name as the ``id`` attribu...
Below is the the instruction that describes the task: ### Input: Generates a lineage phylogeny figure. Args: sequences (list(Sequence)): A list of ``Sequence`` objects from which a phylogeny will be calculated. Strictly speaking, they do not need to be ``Sequence`` objects, rat...
def _writeFeatures(self, i, image): """ Write a text file containing the features as a table. @param i: The number of the image in self._images. @param image: A member of self._images. @return: The C{str} features file name - just the base name, not including the pat...
Write a text file containing the features as a table. @param i: The number of the image in self._images. @param image: A member of self._images. @return: The C{str} features file name - just the base name, not including the path to the file.
Below is the the instruction that describes the task: ### Input: Write a text file containing the features as a table. @param i: The number of the image in self._images. @param image: A member of self._images. @return: The C{str} features file name - just the base name, not incl...
def canonical_dataset_to_grib(dataset, path, mode='wb', no_warn=False, grib_keys={}, **kwargs): # type: (xr.Dataset, str, str, bool, T.Dict[str, T.Any] T.Any) -> None """ Write a ``xr.Dataset`` in *canonical* form to a GRIB file. """ if not no_warn: warnings.warn("GRIB write support is exper...
Write a ``xr.Dataset`` in *canonical* form to a GRIB file.
Below is the the instruction that describes the task: ### Input: Write a ``xr.Dataset`` in *canonical* form to a GRIB file. ### Response: def canonical_dataset_to_grib(dataset, path, mode='wb', no_warn=False, grib_keys={}, **kwargs): # type: (xr.Dataset, str, str, bool, T.Dict[str, T.Any] T.Any) -> None ""...
def set_c_prototype(self, c_decl): """ Set the prototype of a function in the form of a C-style function declaration. :param str c_decl: The C-style declaration of the function. :return: A tuple of (function name, function prototype) :rtype: tuple ""...
Set the prototype of a function in the form of a C-style function declaration. :param str c_decl: The C-style declaration of the function. :return: A tuple of (function name, function prototype) :rtype: tuple
Below is the the instruction that describes the task: ### Input: Set the prototype of a function in the form of a C-style function declaration. :param str c_decl: The C-style declaration of the function. :return: A tuple of (function name, function prototype) :rtype: tu...
def _encode(self): """Generate a recursive JSON representation of the ent.""" obj = {k: v for k, v in self.__dict__.items() if not k.startswith('_') and type(v) in SAFE_TYPES} obj.update({k: v._encode() for k, v in self.__dict__.items() if isinstance(v, Ent)}) ...
Generate a recursive JSON representation of the ent.
Below is the the instruction that describes the task: ### Input: Generate a recursive JSON representation of the ent. ### Response: def _encode(self): """Generate a recursive JSON representation of the ent.""" obj = {k: v for k, v in self.__dict__.items() if not k.startswith('_') and...
def remove_constraint(self,name): """ Remove a constraint (make it "hidden") :param name: Name of constraint. """ constraints = self.constraints hidden_constraints = self.hidden_constraints my_distribution_skip = self.distribution_skip my_sele...
Remove a constraint (make it "hidden") :param name: Name of constraint.
Below is the the instruction that describes the task: ### Input: Remove a constraint (make it "hidden") :param name: Name of constraint. ### Response: def remove_constraint(self,name): """ Remove a constraint (make it "hidden") :param name: Name of constrai...
def LockRetryWrapper(self, subject, retrywrap_timeout=1, retrywrap_max_timeout=10, blocking=True, lease_time=None): """Retry a DBSubjectLock until it succeeds. Args: subject: The subject whi...
Retry a DBSubjectLock until it succeeds. Args: subject: The subject which the lock applies to. retrywrap_timeout: How long to wait before retrying the lock. retrywrap_max_timeout: The maximum time to wait for a retry until we raise. blocking: If False, raise on first lock failure. ...
Below is the the instruction that describes the task: ### Input: Retry a DBSubjectLock until it succeeds. Args: subject: The subject which the lock applies to. retrywrap_timeout: How long to wait before retrying the lock. retrywrap_max_timeout: The maximum time to wait for a retry until we ...
def val_to_bin(edges, x): """Convert axis coordinate to bin index.""" ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
Convert axis coordinate to bin index.
Below is the the instruction that describes the task: ### Input: Convert axis coordinate to bin index. ### Response: def val_to_bin(edges, x): """Convert axis coordinate to bin index.""" ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
def _extension_module_tags(): """ Returns valid tags an extension module might have """ import sysconfig tags = [] if six.PY2: # see also 'SHLIB_EXT' multiarch = sysconfig.get_config_var('MULTIARCH') if multiarch is not None: tags.append(multiarch) else: ...
Returns valid tags an extension module might have
Below is the the instruction that describes the task: ### Input: Returns valid tags an extension module might have ### Response: def _extension_module_tags(): """ Returns valid tags an extension module might have """ import sysconfig tags = [] if six.PY2: # see also 'SHLIB_EXT' ...
def get_auth_from_user(msg_type): """Get the required 'auth' from the user and return as a dict.""" auth = [] for k, v in CONFIG[msg_type]["auth"].items(): auth.append((k, getpass(v + ": "))) return OrderedDict(auth)
Get the required 'auth' from the user and return as a dict.
Below is the the instruction that describes the task: ### Input: Get the required 'auth' from the user and return as a dict. ### Response: def get_auth_from_user(msg_type): """Get the required 'auth' from the user and return as a dict.""" auth = [] for k, v in CONFIG[msg_type]["auth"].items(): ...
def add_scalar_data(self, token, community_id, producer_display_name, metric_name, producer_revision, submit_time, value, **kwargs): """ Create a new scalar data point. :param token: A valid token for the user in question. :type token: str...
Create a new scalar data point. :param token: A valid token for the user in question. :type token: string :param community_id: The id of the community that owns the producer. :type community_id: int | long :param producer_display_name: The display name of the producer. :...
Below is the the instruction that describes the task: ### Input: Create a new scalar data point. :param token: A valid token for the user in question. :type token: string :param community_id: The id of the community that owns the producer. :type community_id: int | long :par...
def heading_title(self): """ Makes the Article Title for the Heading. Metadata element, content derived from FrontMatter """ art_title = self.article.root.xpath('./front/article-meta/title-group/article-title')[0] article_title = deepcopy(art_title) article_title...
Makes the Article Title for the Heading. Metadata element, content derived from FrontMatter
Below is the the instruction that describes the task: ### Input: Makes the Article Title for the Heading. Metadata element, content derived from FrontMatter ### Response: def heading_title(self): """ Makes the Article Title for the Heading. Metadata element, content derived from F...
def remove_alert_tag(self, id, tag_value, **kwargs): # noqa: E501 """Remove a tag from a specific alert # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove...
Remove a tag from a specific alert # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_alert_tag(id, tag_value, async_req=True) >>> result = thread.get() ...
Below is the the instruction that describes the task: ### Input: Remove a tag from a specific alert # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_alert_ta...
def offset(self): """ If this is a constant access (e.g. A(1)) return the offset in bytes from the beginning of the variable in memory. Otherwise, if it's not constant (e.g. A(i)) returns None """ offset = 0 # Now we must typecast each argument to a u16 (...
If this is a constant access (e.g. A(1)) return the offset in bytes from the beginning of the variable in memory. Otherwise, if it's not constant (e.g. A(i)) returns None
Below is the the instruction that describes the task: ### Input: If this is a constant access (e.g. A(1)) return the offset in bytes from the beginning of the variable in memory. Otherwise, if it's not constant (e.g. A(i)) returns None ### Response: def offset(self): """ If...
def execute(self, elem_list): """ If condition, return a new elem_list provided by executing action. """ if self.condition.is_true(elem_list): return self.action.act(elem_list) else: return elem_list
If condition, return a new elem_list provided by executing action.
Below is the the instruction that describes the task: ### Input: If condition, return a new elem_list provided by executing action. ### Response: def execute(self, elem_list): """ If condition, return a new elem_list provided by executing action. """ if self.condition.is_true(elem_l...
def combine_count_files(files, out_file=None, ext=".fpkm"): """ combine a set of count files into a single combined file """ files = list(files) if not files: return None assert all([file_exists(x) for x in files]), \ "Some count files in %s do not exist." % files for f in fi...
combine a set of count files into a single combined file
Below is the the instruction that describes the task: ### Input: combine a set of count files into a single combined file ### Response: def combine_count_files(files, out_file=None, ext=".fpkm"): """ combine a set of count files into a single combined file """ files = list(files) if not files: ...
def consecutive_frame(self): """Return a DataFrame with columns cnt, pids, pl. cnt is the number of pids in the sequence. pl is the pl sum""" if self._frame.empty: return pd.DataFrame(columns=['pids', 'pl', 'cnt', 'is_win']) else: vals = (self._frame[PC.RET] >= 0).astype(...
Return a DataFrame with columns cnt, pids, pl. cnt is the number of pids in the sequence. pl is the pl sum
Below is the the instruction that describes the task: ### Input: Return a DataFrame with columns cnt, pids, pl. cnt is the number of pids in the sequence. pl is the pl sum ### Response: def consecutive_frame(self): """Return a DataFrame with columns cnt, pids, pl. cnt is the number of pids in the sequence....
def SetUseSSL(self, use_ssl): """Sets the use of ssl. Args: use_ssl (bool): enforces use of ssl. """ self._use_ssl = use_ssl logger.debug('Elasticsearch use_ssl: {0!s}'.format(use_ssl))
Sets the use of ssl. Args: use_ssl (bool): enforces use of ssl.
Below is the the instruction that describes the task: ### Input: Sets the use of ssl. Args: use_ssl (bool): enforces use of ssl. ### Response: def SetUseSSL(self, use_ssl): """Sets the use of ssl. Args: use_ssl (bool): enforces use of ssl. """ self._use_ssl = use_ssl logger.de...
def _generate_permutation(self, npoints): """ Create shuffle and deshuffle vectors """ i = np.arange(0, npoints) # permutation p = np.random.permutation(npoints) ip = np.empty_like(p) # inverse permutation ip[p[i]] = i return p, ip
Create shuffle and deshuffle vectors
Below is the the instruction that describes the task: ### Input: Create shuffle and deshuffle vectors ### Response: def _generate_permutation(self, npoints): """ Create shuffle and deshuffle vectors """ i = np.arange(0, npoints) # permutation p = np.random.permutatio...
def find_template_companion(template, extension='', check=True): """ Returns the first found template companion file """ if check and not os.path.isfile(template): yield '' return # May be '<stdin>' (click) template = os.path.abspath(template) template_dirname = os.path.dirname...
Returns the first found template companion file
Below is the the instruction that describes the task: ### Input: Returns the first found template companion file ### Response: def find_template_companion(template, extension='', check=True): """ Returns the first found template companion file """ if check and not os.path.isfile(template): ...
def __add_frozen(self): """ Adds _frozen attribute to this instance and all its child configurations. """ setattr(self, "_frozen", False) for attr, val in self.__dict__.items(): if isinstance(val, Config): val.__add_frozen()
Adds _frozen attribute to this instance and all its child configurations.
Below is the the instruction that describes the task: ### Input: Adds _frozen attribute to this instance and all its child configurations. ### Response: def __add_frozen(self): """ Adds _frozen attribute to this instance and all its child configurations. """ setattr(self, "_frozen",...
def parse(self, file, outfile=None): """Parse a BGI (basic gene info) JSON file """ file = self._ensure_file(file) obj = json.load(file) items = obj['data'] return [self.transform_item(item) for item in items]
Parse a BGI (basic gene info) JSON file
Below is the the instruction that describes the task: ### Input: Parse a BGI (basic gene info) JSON file ### Response: def parse(self, file, outfile=None): """Parse a BGI (basic gene info) JSON file """ file = self._ensure_file(file) obj = json.load(file) items = obj['data']...
def get_all_service_user_objects(self, include_machine = False): """ Fetches all service user objects from the AD, and returns MSADUser object. Service user refers to an user whith SPN (servicePrincipalName) attribute set """ logger.debug('Polling AD for all user objects, machine accounts included: %s'% inclu...
Fetches all service user objects from the AD, and returns MSADUser object. Service user refers to an user whith SPN (servicePrincipalName) attribute set
Below is the the instruction that describes the task: ### Input: Fetches all service user objects from the AD, and returns MSADUser object. Service user refers to an user whith SPN (servicePrincipalName) attribute set ### Response: def get_all_service_user_objects(self, include_machine = False): """ Fetches ...
def commit(self, session): """Commit phase for session. :param session: sqlalchemy session """ sp_key, sp_hkey = self._keygen(session) with self.r.pipeline(transaction=False) as p: p.srem(sp_key, session.meepo_unique_id) p.expire(sp_hkey, 60 * 60) ...
Commit phase for session. :param session: sqlalchemy session
Below is the the instruction that describes the task: ### Input: Commit phase for session. :param session: sqlalchemy session ### Response: def commit(self, session): """Commit phase for session. :param session: sqlalchemy session """ sp_key, sp_hkey = self._keygen(session...
def get_transport(socket, host, kerberos_service_name, auth_mechanism='NOSASL', user=None, password=None): """ Creates a new Thrift Transport using the specified auth_mechanism. Supported auth_mechanisms are: - None or 'NOSASL' - returns simple buffered transport (default) - 'PLAIN...
Creates a new Thrift Transport using the specified auth_mechanism. Supported auth_mechanisms are: - None or 'NOSASL' - returns simple buffered transport (default) - 'PLAIN' - returns a SASL transport with the PLAIN mechanism - 'GSSAPI' - returns a SASL transport with the GSSAPI mechanism
Below is the the instruction that describes the task: ### Input: Creates a new Thrift Transport using the specified auth_mechanism. Supported auth_mechanisms are: - None or 'NOSASL' - returns simple buffered transport (default) - 'PLAIN' - returns a SASL transport with the PLAIN mechanism - 'GSSAPI...
def use_comparative_assessment_offered_view(self): """Pass through to provider AssessmentOfferedLookupSession.use_comparative_assessment_offered_view""" self._object_views['assessment_offered'] = COMPARATIVE # self._get_provider_session('assessment_offered_lookup_session') # To make sure the ses...
Pass through to provider AssessmentOfferedLookupSession.use_comparative_assessment_offered_view
Below is the the instruction that describes the task: ### Input: Pass through to provider AssessmentOfferedLookupSession.use_comparative_assessment_offered_view ### Response: def use_comparative_assessment_offered_view(self): """Pass through to provider AssessmentOfferedLookupSession.use_comparative_assess...
def retry_failure_fab_dev_delete(self, tenant_id, fw_data, fw_dict): """Retry the failure cases for delete. This module calls routine in fabric to retry the failure cases for delete. If device is not successfully cfg/uncfg, it calls the device manager routine to cfg/uncfg the de...
Retry the failure cases for delete. This module calls routine in fabric to retry the failure cases for delete. If device is not successfully cfg/uncfg, it calls the device manager routine to cfg/uncfg the device.
Below is the the instruction that describes the task: ### Input: Retry the failure cases for delete. This module calls routine in fabric to retry the failure cases for delete. If device is not successfully cfg/uncfg, it calls the device manager routine to cfg/uncfg the device. ### R...
def _significant_pathways_dataframe(pvalue_information, side_information, alpha): """Create the significant pathways pandas.DataFrame. Given the p-values corresponding to each pathway in a feature, apply the FDR correction for multiple ...
Create the significant pathways pandas.DataFrame. Given the p-values corresponding to each pathway in a feature, apply the FDR correction for multiple testing and remove those that do not have a q-value of less than `alpha`.
Below is the the instruction that describes the task: ### Input: Create the significant pathways pandas.DataFrame. Given the p-values corresponding to each pathway in a feature, apply the FDR correction for multiple testing and remove those that do not have a q-value of less than `alpha`. ### Response: ...
def removeCategory(self, categoryToRemove): """ There are two caveats. First, this is a potentially slow operation. Second, pattern indices will shift if patterns before them are removed. :param categoryToRemove: Category label to remove """ removedRows = 0 if self._Memory is None: re...
There are two caveats. First, this is a potentially slow operation. Second, pattern indices will shift if patterns before them are removed. :param categoryToRemove: Category label to remove
Below is the the instruction that describes the task: ### Input: There are two caveats. First, this is a potentially slow operation. Second, pattern indices will shift if patterns before them are removed. :param categoryToRemove: Category label to remove ### Response: def removeCategory(self, categoryToRe...
def load_plugin_configuration(self): """Call the configuration hook for plugins This walks through the list of plugins, grabs the "load_configuration" hook, if exposed, and calls it to allow plugins to configure specific settings. """ for modname in self._dynamic_plugins...
Call the configuration hook for plugins This walks through the list of plugins, grabs the "load_configuration" hook, if exposed, and calls it to allow plugins to configure specific settings.
Below is the the instruction that describes the task: ### Input: Call the configuration hook for plugins This walks through the list of plugins, grabs the "load_configuration" hook, if exposed, and calls it to allow plugins to configure specific settings. ### Response: def load_plugin_conf...
def abort_transaction(self): """Abort a multi-statement transaction. .. versionadded:: 3.7 """ self._check_ended() state = self._transaction.state if state is _TxnState.NONE: raise InvalidOperation("No transaction started") elif state is _TxnState.ST...
Abort a multi-statement transaction. .. versionadded:: 3.7
Below is the the instruction that describes the task: ### Input: Abort a multi-statement transaction. .. versionadded:: 3.7 ### Response: def abort_transaction(self): """Abort a multi-statement transaction. .. versionadded:: 3.7 """ self._check_ended() state = sel...
def add_node(self, node, xtra=None, branch=None): """ Adds a **node object** to the ``DictGraph``. Returns ``True`` if a new **node object** has been added. If the **node object** is already in the ``DictGraph`` returns ``False``. Arguments: - node(``...
Adds a **node object** to the ``DictGraph``. Returns ``True`` if a new **node object** has been added. If the **node object** is already in the ``DictGraph`` returns ``False``. Arguments: - node(``object``) Node to be added. Any hashable Python ``object``. ...
Below is the the instruction that describes the task: ### Input: Adds a **node object** to the ``DictGraph``. Returns ``True`` if a new **node object** has been added. If the **node object** is already in the ``DictGraph`` returns ``False``. Arguments: - node(``o...
async def _call_async(self, method_name: str, *args, **kwargs): """ Sends a request to the socket and then wait for the reply. To deal with multiple, asynchronous requests we do not expect that the receive reply task scheduled from this call is the one that receives this call's reply an...
Sends a request to the socket and then wait for the reply. To deal with multiple, asynchronous requests we do not expect that the receive reply task scheduled from this call is the one that receives this call's reply and instead rely on Events to signal across multiple _async_call/_recv_reply t...
Below is the the instruction that describes the task: ### Input: Sends a request to the socket and then wait for the reply. To deal with multiple, asynchronous requests we do not expect that the receive reply task scheduled from this call is the one that receives this call's reply and instead rely ...
def do_email_authors(self, comment, entry, site): """ Send email notification of a new comment to the authors of the entry. """ if not self.email_authors: return exclude_list = self.mail_comment_notification_recipients + [''] recipient_list = ( ...
Send email notification of a new comment to the authors of the entry.
Below is the the instruction that describes the task: ### Input: Send email notification of a new comment to the authors of the entry. ### Response: def do_email_authors(self, comment, entry, site): """ Send email notification of a new comment to the authors of the entry. ""...
def make_block_same_class(self, values, placement=None, ndim=None, dtype=None): """ Wrap given values in a block of same type as self. """ if dtype is not None: # issue 19431 fastparquet is passing this warnings.warn("dtype argument is deprecated, wi...
Wrap given values in a block of same type as self.
Below is the the instruction that describes the task: ### Input: Wrap given values in a block of same type as self. ### Response: def make_block_same_class(self, values, placement=None, ndim=None, dtype=None): """ Wrap given values in a block of same type as self. """ ...
def resumable(self): '''Find all the jobs that we'd previously been working on''' # First, find the jids of all the jobs registered to this client. # Then, get the corresponding job objects jids = self.client.workers[self.client.worker_name]['jobs'] jobs = self.client.jobs.get(*j...
Find all the jobs that we'd previously been working on
Below is the the instruction that describes the task: ### Input: Find all the jobs that we'd previously been working on ### Response: def resumable(self): '''Find all the jobs that we'd previously been working on''' # First, find the jids of all the jobs registered to this client. # Then, g...
def sanitize_type(raw_type): """Sanitize the raw type string.""" cleaned = get_printable(raw_type).strip() for bad in [ r'__drv_aliasesMem', r'__drv_freesMem', r'__drv_strictTypeMatch\(\w+\)', r'__out_data_source\(\w+\)', r'_In_NLS_string_\(\w+\)', ...
Sanitize the raw type string.
Below is the the instruction that describes the task: ### Input: Sanitize the raw type string. ### Response: def sanitize_type(raw_type): """Sanitize the raw type string.""" cleaned = get_printable(raw_type).strip() for bad in [ r'__drv_aliasesMem', r'__drv_freesMem', r'__drv_st...
def get_thumbnail(self, video_path, at_time=0.5): """ Extracts an image of a video and returns its path. If the requested thumbnail is not within the duration of the video an `InvalidTimeError` is thrown. """ filename = os.path.basename(video_path) filename, __ =...
Extracts an image of a video and returns its path. If the requested thumbnail is not within the duration of the video an `InvalidTimeError` is thrown.
Below is the the instruction that describes the task: ### Input: Extracts an image of a video and returns its path. If the requested thumbnail is not within the duration of the video an `InvalidTimeError` is thrown. ### Response: def get_thumbnail(self, video_path, at_time=0.5): """ ...
def interact_GxG(pheno,snps1,snps2=None,K=None,covs=None): """ Epistasis test between two sets of SNPs Args: pheno: [N x 1] SP.array of 1 phenotype for N individuals snps1: [N x S1] SP.array of S1 SNPs for N individuals snps2: [N x S2] SP.array of S2 SNPs for N individuals ...
Epistasis test between two sets of SNPs Args: pheno: [N x 1] SP.array of 1 phenotype for N individuals snps1: [N x S1] SP.array of S1 SNPs for N individuals snps2: [N x S2] SP.array of S2 SNPs for N individuals K: [N x N] SP.array of LMM-covariance/kinship koefficients (opti...
Below is the the instruction that describes the task: ### Input: Epistasis test between two sets of SNPs Args: pheno: [N x 1] SP.array of 1 phenotype for N individuals snps1: [N x S1] SP.array of S1 SNPs for N individuals snps2: [N x S2] SP.array of S2 SNPs for N individuals ...
def make_model_info(self, modelkey): """ Build a dictionary with the information for a particular model. Parameters ---------- modelkey : str Key used to identify this particular model Return `ModelInfo` """ model = self.read_model_yaml(modelkey) ...
Build a dictionary with the information for a particular model. Parameters ---------- modelkey : str Key used to identify this particular model Return `ModelInfo`
Below is the the instruction that describes the task: ### Input: Build a dictionary with the information for a particular model. Parameters ---------- modelkey : str Key used to identify this particular model Return `ModelInfo` ### Response: def make_model_info(self, ...
def encode_example(self, example_data): """See base class for details.""" np_dtype = np.dtype(self._dtype.as_numpy_dtype) # Convert to numpy if possible if not isinstance(example_data, np.ndarray): example_data = np.array(example_data, dtype=np_dtype) # Ensure the shape and dtype match if ...
See base class for details.
Below is the the instruction that describes the task: ### Input: See base class for details. ### Response: def encode_example(self, example_data): """See base class for details.""" np_dtype = np.dtype(self._dtype.as_numpy_dtype) # Convert to numpy if possible if not isinstance(example_data, np.ndar...
def register(self, id): """ Registers a configuration. Returns True if the configuration has been added and False if it already exists. Reports an error if the configuration is 'used'. """ assert isinstance(id, basestring) if id in self.used_: ...
Registers a configuration. Returns True if the configuration has been added and False if it already exists. Reports an error if the configuration is 'used'.
Below is the the instruction that describes the task: ### Input: Registers a configuration. Returns True if the configuration has been added and False if it already exists. Reports an error if the configuration is 'used'. ### Response: def register(self, id): """ Regist...
def attr(self, kw=None, _attributes=None, **attrs): """Add a general or graph/node/edge attribute statement. Args: kw: Attributes target (``None`` or ``'graph'``, ``'node'``, ``'edge'``). attrs: Attributes to be set (must be strings, may be empty). See the :ref:`usage e...
Add a general or graph/node/edge attribute statement. Args: kw: Attributes target (``None`` or ``'graph'``, ``'node'``, ``'edge'``). attrs: Attributes to be set (must be strings, may be empty). See the :ref:`usage examples in the User Guide <attributes>`.
Below is the the instruction that describes the task: ### Input: Add a general or graph/node/edge attribute statement. Args: kw: Attributes target (``None`` or ``'graph'``, ``'node'``, ``'edge'``). attrs: Attributes to be set (must be strings, may be empty). See the :ref:`u...
def annotate_orfs(fa, seqs, threads, threshold = 1e-6): """ search orfs against pfam # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, {orf: annotations}], ...]] """ db = '%s/pfam/Pfam-A.hmm' % os.environ['databases'] base = fa.rsplit('.', ...
search orfs against pfam # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, {orf: annotations}], ...]]
Below is the the instruction that describes the task: ### Input: search orfs against pfam # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, {orf: annotations}], ...]] ### Response: def annotate_orfs(fa, seqs, threads, threshold = 1e-6): """ search...
def get_iface_mode(iface): """Return the interface mode. params: - iface: the iwconfig interface """ p = subprocess.Popen(["iwconfig", iface], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, err = p.communicate() match = re.search(br"mode:([a-zA-Z]*)", out...
Return the interface mode. params: - iface: the iwconfig interface
Below is the the instruction that describes the task: ### Input: Return the interface mode. params: - iface: the iwconfig interface ### Response: def get_iface_mode(iface): """Return the interface mode. params: - iface: the iwconfig interface """ p = subprocess.Popen(["iwconfig", ifac...
def add_symbols(namespace, registry): """Adds the unit symbols from :mod:`unyt.unit_symbols` to a namespace Parameters ---------- namespace : dict The dict to insert unit symbols into. The keys will be string unit names and values will be the corresponding unit objects. registry : :c...
Adds the unit symbols from :mod:`unyt.unit_symbols` to a namespace Parameters ---------- namespace : dict The dict to insert unit symbols into. The keys will be string unit names and values will be the corresponding unit objects. registry : :class:`unyt.unit_registry.UnitRegistry` ...
Below is the the instruction that describes the task: ### Input: Adds the unit symbols from :mod:`unyt.unit_symbols` to a namespace Parameters ---------- namespace : dict The dict to insert unit symbols into. The keys will be string unit names and values will be the corresponding unit ob...
def _splash(): """Print the splash""" splash_title = "{pkg} [{version}] - {url}".format(pkg=PKG_NAME, version=version, url=PKG_URL) log.to_stdout(splash_title, colorf=log.yellow, bold=True) log.to_stdout('-' * len(splash_title), colorf=log.yellow, bo...
Print the splash
Below is the the instruction that describes the task: ### Input: Print the splash ### Response: def _splash(): """Print the splash""" splash_title = "{pkg} [{version}] - {url}".format(pkg=PKG_NAME, version=version, url=PKG_URL) log.to_stdout(splash_...
def project_transfer(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /project-xxxx/transfer API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2Ftransfer """ return DXHTTPRequest(...
Invokes the /project-xxxx/transfer API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2Ftransfer
Below is the the instruction that describes the task: ### Input: Invokes the /project-xxxx/transfer API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2Ftransfer ### Response: def project_transfer(object_id, input_pa...
def set_extana_led(self, r, g, b, check_state=True): """Update the colour of the RGB LED on the SK8-ExtAna board. Args: r (int): red channel, 0-255 g (int): green channel, 0-255 b (int): blue channel, 0-255 check_state (bool): if True (default) and the lo...
Update the colour of the RGB LED on the SK8-ExtAna board. Args: r (int): red channel, 0-255 g (int): green channel, 0-255 b (int): blue channel, 0-255 check_state (bool): if True (default) and the locally cached LED state matches the given (r, g, ...
Below is the the instruction that describes the task: ### Input: Update the colour of the RGB LED on the SK8-ExtAna board. Args: r (int): red channel, 0-255 g (int): green channel, 0-255 b (int): blue channel, 0-255 check_state (bool): if True (default) and t...
def _compatible_small_variants(data, items): """Retrieve small variant (SNP, indel) VCFs compatible with CNVkit. """ from bcbio import heterogeneity VarFile = collections.namedtuple("VarFile", ["name", "sample", "normal"]) out = [] paired = vcfutils.get_paired(items) for v in heterogeneity.g...
Retrieve small variant (SNP, indel) VCFs compatible with CNVkit.
Below is the the instruction that describes the task: ### Input: Retrieve small variant (SNP, indel) VCFs compatible with CNVkit. ### Response: def _compatible_small_variants(data, items): """Retrieve small variant (SNP, indel) VCFs compatible with CNVkit. """ from bcbio import heterogeneity VarFil...
def scale_sections(sections, scaling_scope): ''' input: unscaled sections. returns: sections scaled to [0, 255] ''' new_sections = [] if scaling_scope == 'layer': for section in sections: new_sections.append(scale_image_for_display(section)) elif scaling_scope == 'network': global_min, glo...
input: unscaled sections. returns: sections scaled to [0, 255]
Below is the the instruction that describes the task: ### Input: input: unscaled sections. returns: sections scaled to [0, 255] ### Response: def scale_sections(sections, scaling_scope): ''' input: unscaled sections. returns: sections scaled to [0, 255] ''' new_sections = [] if scaling_scope == 'lay...
def callproc(self, name, params, param_types=None): """Calls a procedure. :param name: the name of the procedure :param params: a list or tuple of parameters to pass to the procedure. :param param_types: a list or tuple of type names. If given, each param will be cast via sql_wr...
Calls a procedure. :param name: the name of the procedure :param params: a list or tuple of parameters to pass to the procedure. :param param_types: a list or tuple of type names. If given, each param will be cast via sql_writers typecast method. This is useful to disambiguate proce...
Below is the the instruction that describes the task: ### Input: Calls a procedure. :param name: the name of the procedure :param params: a list or tuple of parameters to pass to the procedure. :param param_types: a list or tuple of type names. If given, each param will be cast via ...
def timestamp(num_params, p_levels, k_choices, N): """ Returns a uniform timestamp with parameter values for file identification """ string = "_v%s_l%s_gs%s_k%s_N%s_%s.txt" % (num_params, p_levels, k_choices, ...
Returns a uniform timestamp with parameter values for file identification
Below is the the instruction that describes the task: ### Input: Returns a uniform timestamp with parameter values for file identification ### Response: def timestamp(num_params, p_levels, k_choices, N): """ Returns a uniform timestamp with parameter values for file identification """ string = "_v%...
def encrypt_cbc(self, data, init_vector): """ Return an iterator that encrypts `data` using the Cipher-Block Chaining (CBC) mode of operation. CBC mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`bytes` object (i...
Return an iterator that encrypts `data` using the Cipher-Block Chaining (CBC) mode of operation. CBC mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes) containing the encrypted bytes of the...
Below is the the instruction that describes the task: ### Input: Return an iterator that encrypts `data` using the Cipher-Block Chaining (CBC) mode of operation. CBC mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`b...
def closure(self, rules): """Fills out the entire closure based on some initial dotted rules. Args: rules - an iterable of DottedRules Returns: frozenset of DottedRules """ closure = set() todo = set(rules) while todo: rule = todo.pop()...
Fills out the entire closure based on some initial dotted rules. Args: rules - an iterable of DottedRules Returns: frozenset of DottedRules
Below is the the instruction that describes the task: ### Input: Fills out the entire closure based on some initial dotted rules. Args: rules - an iterable of DottedRules Returns: frozenset of DottedRules ### Response: def closure(self, rules): """Fills out the entire closure ...
def DiffDataObjects(self, oldObj, newObj): """Diff Data Objects""" if oldObj == newObj: return True if not oldObj or not newObj: __Log__.debug('DiffDataObjects: One of the objects in None') return False oldType = Type(oldObj) newType = Type(newObj) if oldTy...
Diff Data Objects
Below is the the instruction that describes the task: ### Input: Diff Data Objects ### Response: def DiffDataObjects(self, oldObj, newObj): """Diff Data Objects""" if oldObj == newObj: return True if not oldObj or not newObj: __Log__.debug('DiffDataObjects: One of the objects in...
def undo(ui, repo, clname, **opts): """undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. """ if repo[None].branch() != "default": raise hg_util.Abort("cannot run hg undo outsi...
undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description.
Below is the the instruction that describes the task: ### Input: undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. ### Response: def undo(ui, repo, clname, **opts): """undo t...
def _tumor_normal_genotypes(ref, alt, info, fname, coords): """Retrieve standard 0/0, 0/1, 1/1 style genotypes from INFO field. Normal -- NT field (ref, het, hom, conflict) Tumor -- SGT field - for SNPs specified as GG->TT for the normal and tumor diploid alleles. These can also represent mor...
Retrieve standard 0/0, 0/1, 1/1 style genotypes from INFO field. Normal -- NT field (ref, het, hom, conflict) Tumor -- SGT field - for SNPs specified as GG->TT for the normal and tumor diploid alleles. These can also represent more complex alleles in which case we set at heterozygotes pen...
Below is the the instruction that describes the task: ### Input: Retrieve standard 0/0, 0/1, 1/1 style genotypes from INFO field. Normal -- NT field (ref, het, hom, conflict) Tumor -- SGT field - for SNPs specified as GG->TT for the normal and tumor diploid alleles. These can also represent m...
def list(self, pattern='*'): """Returns a list of groups that match the filters. Args: pattern: An optional pattern to filter the groups based on their display name. This can include Unix shell-style wildcards. E.g. ``"Production*"``. Returns: A list of Group objects that m...
Returns a list of groups that match the filters. Args: pattern: An optional pattern to filter the groups based on their display name. This can include Unix shell-style wildcards. E.g. ``"Production*"``. Returns: A list of Group objects that match the filters.
Below is the the instruction that describes the task: ### Input: Returns a list of groups that match the filters. Args: pattern: An optional pattern to filter the groups based on their display name. This can include Unix shell-style wildcards. E.g. ``"Production*"``. Returns: ...
def _set_book_view(self, session): """Sets the underlying book view to match current view""" if self._book_view == COMPARATIVE: try: session.use_comparative_book_view() except AttributeError: pass else: try: sess...
Sets the underlying book view to match current view
Below is the the instruction that describes the task: ### Input: Sets the underlying book view to match current view ### Response: def _set_book_view(self, session): """Sets the underlying book view to match current view""" if self._book_view == COMPARATIVE: try: session...
def image_list_detailed(request, marker=None, sort_dir='desc', sort_key='created_at', filters=None, paginate=False, reversed_order=False, **kwargs): """Thin layer above glanceclient, for handling pagination issues. It provides iterating both forward and backward ...
Thin layer above glanceclient, for handling pagination issues. It provides iterating both forward and backward on top of ascetic OpenStack pagination API - which natively supports only iterating forward through the entries. Thus in order to retrieve list of objects at previous page, a request with the ...
Below is the the instruction that describes the task: ### Input: Thin layer above glanceclient, for handling pagination issues. It provides iterating both forward and backward on top of ascetic OpenStack pagination API - which natively supports only iterating forward through the entries. Thus in order ...
def FormatSOAPDateTime(value): """Format a SOAP DateTime object for printing. Args: value: The DateTime object to format. Returns: A string representing the value. """ value_date = value['date'] return '%s-%s-%s %s:%s:%s (%s)' % ( value_date['year'], value_date['month'], value_date['day'], ...
Format a SOAP DateTime object for printing. Args: value: The DateTime object to format. Returns: A string representing the value.
Below is the the instruction that describes the task: ### Input: Format a SOAP DateTime object for printing. Args: value: The DateTime object to format. Returns: A string representing the value. ### Response: def FormatSOAPDateTime(value): """Format a SOAP DateTime object for printing. Args: ...
def add(self, *args, **kwargs): """Add a Question instance to the questions dict. Each key points to a list of Question instances with that key. Use the `question` kwarg to pass a Question instance if you want, or pass in the same args you would pass to instantiate a question. ""...
Add a Question instance to the questions dict. Each key points to a list of Question instances with that key. Use the `question` kwarg to pass a Question instance if you want, or pass in the same args you would pass to instantiate a question.
Below is the the instruction that describes the task: ### Input: Add a Question instance to the questions dict. Each key points to a list of Question instances with that key. Use the `question` kwarg to pass a Question instance if you want, or pass in the same args you would pass to instanti...
def canMove(self): """ test if a move is possible """ if not self.filled(): return True for y in self.__size_range: for x in self.__size_range: c = self.getCell(x, y) if (x < self.__size-1 and c == self.getCell(x+1, y)) \ ...
test if a move is possible
Below is the the instruction that describes the task: ### Input: test if a move is possible ### Response: def canMove(self): """ test if a move is possible """ if not self.filled(): return True for y in self.__size_range: for x in self.__size_range: ...
def blob_handler(self, cmd): """Process a BlobCommand.""" # These never pass through directly. We buffer them and only # output them if referenced by an interesting command. self.blobs[cmd.id] = cmd self.keep = False
Process a BlobCommand.
Below is the the instruction that describes the task: ### Input: Process a BlobCommand. ### Response: def blob_handler(self, cmd): """Process a BlobCommand.""" # These never pass through directly. We buffer them and only # output them if referenced by an interesting command. self.bl...
def get_attribute(cls, soup, key, unknown=None): """ Get attribute for Beautifulsoup object :param soup: Beautifulsoup object :param key: attribute key :param unknown: attribute key not exists value(default:None) :return: attribute value """ if key in soup...
Get attribute for Beautifulsoup object :param soup: Beautifulsoup object :param key: attribute key :param unknown: attribute key not exists value(default:None) :return: attribute value
Below is the the instruction that describes the task: ### Input: Get attribute for Beautifulsoup object :param soup: Beautifulsoup object :param key: attribute key :param unknown: attribute key not exists value(default:None) :return: attribute value ### Response: def get_attribute(c...
def save_fileAs(self, file=None): """ Saves the editor file content either using given file or user chosen file. :return: Method success. :rtype: bool :note: May require user interaction. """ file = file or umbra.ui.common.store_last_browsed_path( Q...
Saves the editor file content either using given file or user chosen file. :return: Method success. :rtype: bool :note: May require user interaction.
Below is the the instruction that describes the task: ### Input: Saves the editor file content either using given file or user chosen file. :return: Method success. :rtype: bool :note: May require user interaction. ### Response: def save_fileAs(self, file=None): """ Saves ...
def cheby_rect(G, bounds, signal, **kwargs): r""" Fast filtering using Chebyshev polynomial for a perfect rectangle filter. Parameters ---------- G : Graph bounds : array_like The bounds of the pass-band filter signal : array_like Signal to filter order : int (optional) ...
r""" Fast filtering using Chebyshev polynomial for a perfect rectangle filter. Parameters ---------- G : Graph bounds : array_like The bounds of the pass-band filter signal : array_like Signal to filter order : int (optional) Order of the Chebyshev polynomial (defaul...
Below is the the instruction that describes the task: ### Input: r""" Fast filtering using Chebyshev polynomial for a perfect rectangle filter. Parameters ---------- G : Graph bounds : array_like The bounds of the pass-band filter signal : array_like Signal to filter ord...
def observe(self, key: str, callback: Callable[[Any, Any], None]): """Subscribes to key changes""" if key not in self._callbacks: self._add_key(key) self._callbacks[key].append(callback)
Subscribes to key changes
Below is the the instruction that describes the task: ### Input: Subscribes to key changes ### Response: def observe(self, key: str, callback: Callable[[Any, Any], None]): """Subscribes to key changes""" if key not in self._callbacks: self._add_key(key) self._callbacks[key].appe...
def build_transaction(self, inputs, outputs): """ Thin wrapper around ``bitcoin.mktx(inputs, outputs)`` Args: inputs (dict): inputs in the form of ``{'output': 'txid:vout', 'value': amount in satoshi}`` outputs (dict): outputs in the form of ...
Thin wrapper around ``bitcoin.mktx(inputs, outputs)`` Args: inputs (dict): inputs in the form of ``{'output': 'txid:vout', 'value': amount in satoshi}`` outputs (dict): outputs in the form of ``{'address': to_address, 'value': amount in satoshi}`` ...
Below is the the instruction that describes the task: ### Input: Thin wrapper around ``bitcoin.mktx(inputs, outputs)`` Args: inputs (dict): inputs in the form of ``{'output': 'txid:vout', 'value': amount in satoshi}`` outputs (dict): outputs in the form of ...