code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def portalAdmin(self): """gets a reference to a portal administration class""" from ..manageportal import PortalAdministration return PortalAdministration(admin_url="https://%s/portaladmin" % self.portalHostname, securityHandler=self._securityHandler, ...
gets a reference to a portal administration class
Below is the the instruction that describes the task: ### Input: gets a reference to a portal administration class ### Response: def portalAdmin(self): """gets a reference to a portal administration class""" from ..manageportal import PortalAdministration return PortalAdministration(admin_u...
def MI_deleteInstance(self, env, instanceName): # pylint: disable=invalid-name """Delete a CIM instance Implements the WBEM operation DeleteInstance in terms of the delete_instance method. A derived class will not normally ove...
Delete a CIM instance Implements the WBEM operation DeleteInstance in terms of the delete_instance method. A derived class will not normally override this method.
Below is the the instruction that describes the task: ### Input: Delete a CIM instance Implements the WBEM operation DeleteInstance in terms of the delete_instance method. A derived class will not normally override this method. ### Response: def MI_deleteInstance(self, ...
def fileUpd(self, buffer=None, filename=None, ufilename=None, desc=None): """Update annotation attached file.""" CheckParent(self) return _fitz.Annot_fileUpd(self, buffer, filename, ufilename, desc)
Update annotation attached file.
Below is the the instruction that describes the task: ### Input: Update annotation attached file. ### Response: def fileUpd(self, buffer=None, filename=None, ufilename=None, desc=None): """Update annotation attached file.""" CheckParent(self) return _fitz.Annot_fileUpd(self, buffer, file...
def get_comments(self): """Gets the comment list resulting from a search. return: (osid.commenting.CommentList) - the comment list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: ...
Gets the comment list resulting from a search. return: (osid.commenting.CommentList) - the comment list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the comment list resulting from a search. return: (osid.commenting.CommentList) - the comment list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.* ### Res...
def get_mock_personalization_dict(): """Get a dict of personalization mock.""" mock_pers = dict() mock_pers['to_list'] = [To("test1@example.com", "Example User"), To("test2@example.com", "Example User")] mo...
Get a dict of personalization mock.
Below is the the instruction that describes the task: ### Input: Get a dict of personalization mock. ### Response: def get_mock_personalization_dict(): """Get a dict of personalization mock.""" mock_pers = dict() mock_pers['to_list'] = [To("test1@example.com", "Exampl...
def deserialize(self, mimetypes): # pylint: disable=arguments-differ """ Invoke the deserializer Upon successful deserialization a dict will be returned containing the following key/vals: { 'content': <uploaded object>, 'content-type': <content-type...
Invoke the deserializer Upon successful deserialization a dict will be returned containing the following key/vals: { 'content': <uploaded object>, 'content-type': <content-type of content>, 'file-ext': <file extension based on content-type>, ...
Below is the the instruction that describes the task: ### Input: Invoke the deserializer Upon successful deserialization a dict will be returned containing the following key/vals: { 'content': <uploaded object>, 'content-type': <content-type of content>,...
def get_direct_fields_from_model(model_class): """ Direct, not m2m, not FK """ direct_fields = [] all_fields_names = _get_all_field_names(model_class) for field_name in all_fields_names: field, model, direct, m2m = _get_field_by_name(model_class, field_name) if direct and not m2m and not...
Direct, not m2m, not FK
Below is the the instruction that describes the task: ### Input: Direct, not m2m, not FK ### Response: def get_direct_fields_from_model(model_class): """ Direct, not m2m, not FK """ direct_fields = [] all_fields_names = _get_all_field_names(model_class) for field_name in all_fields_names: f...
def xtob(data, sep=''): """Interpret the hex encoding of a blob (string).""" # remove the non-hex characters data = re.sub("[^0-9a-fA-F]", '', data) # interpret the hex return binascii.unhexlify(data)
Interpret the hex encoding of a blob (string).
Below is the the instruction that describes the task: ### Input: Interpret the hex encoding of a blob (string). ### Response: def xtob(data, sep=''): """Interpret the hex encoding of a blob (string).""" # remove the non-hex characters data = re.sub("[^0-9a-fA-F]", '', data) # interpret the hex ...
def join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity, result_selector=lambda outer, inner: (outer, inner)): '''Perform an inner join with a second sequence using selected keys. The order of elements from outer is maintained. For each of these...
Perform an inner join with a second sequence using selected keys. The order of elements from outer is maintained. For each of these the order of elements from inner is also preserved. Note: This method uses deferred execution. Args: inner_iterable: The sequence to join wit...
Below is the the instruction that describes the task: ### Input: Perform an inner join with a second sequence using selected keys. The order of elements from outer is maintained. For each of these the order of elements from inner is also preserved. Note: This method uses deferred execution...
def set(self, val): """ set value of this param """ assert not self.__isReadOnly, \ ("This parameter(%s) was locked" " and now it can not be changed" % self.name) assert self.replacedWith is None, \ ("This param was replaced with new one and t...
set value of this param
Below is the the instruction that describes the task: ### Input: set value of this param ### Response: def set(self, val): """ set value of this param """ assert not self.__isReadOnly, \ ("This parameter(%s) was locked" " and now it can not be changed" % sel...
def format_sdist_header_metadata(data, filename): """ Format the metadata of pypi packages stored in email header format. Currently only used as backup on the wheel (compressed) file format. """ description = get_header_description(data) config_items = python_version_check(data) attrs = dic...
Format the metadata of pypi packages stored in email header format. Currently only used as backup on the wheel (compressed) file format.
Below is the the instruction that describes the task: ### Input: Format the metadata of pypi packages stored in email header format. Currently only used as backup on the wheel (compressed) file format. ### Response: def format_sdist_header_metadata(data, filename): """ Format the metadata of pypi pack...
def report(self, stream): """Writes an Xunit-formatted XML file The file includes a report of test errors and failures. """ self.stats['encoding'] = self.encoding self.stats['total'] = (self.stats['errors'] + self.stats['failures'] + self.stats['p...
Writes an Xunit-formatted XML file The file includes a report of test errors and failures.
Below is the the instruction that describes the task: ### Input: Writes an Xunit-formatted XML file The file includes a report of test errors and failures. ### Response: def report(self, stream): """Writes an Xunit-formatted XML file The file includes a report of test errors and failures....
def delete_record(self, name, recordid, username, password): ''' Delete record ''' #headers = {'key': username, 'secret': password} req = requests.delete(self.api_server + '/api/' + name + '/' + str(recordid), auth=(username, password)) return req
Delete record
Below is the the instruction that describes the task: ### Input: Delete record ### Response: def delete_record(self, name, recordid, username, password): ''' Delete record ''' #headers = {'key': username, 'secret': password} req = requests.delete(self.api_server + '/api/' + name + '/' + ...
def univec(self, databasepath): """ Download the UniVec core database :param databasepath: path to use to save the database """ logging.info('Downloading univec database') databasepath = self.create_database_folder(databasepath, 'univec') # Set the name of the out...
Download the UniVec core database :param databasepath: path to use to save the database
Below is the the instruction that describes the task: ### Input: Download the UniVec core database :param databasepath: path to use to save the database ### Response: def univec(self, databasepath): """ Download the UniVec core database :param databasepath: path to use to save the d...
def get_choices(field): """ Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices """ empty_label = getattr(field.field, "empty_label", False) needs_empty_value = False choices = [] # Data is the choices if ha...
Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices
Below is the the instruction that describes the task: ### Input: Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices ### Response: def get_choices(field): """ Find choices of a field, whether it has choices or ...
def read_request_line(self, request_line): """ Read HTTP-request line :param request_line: line to parse for HTTP/0.9 is GET <Request-URI> for HTTP/1.0 and 1.1 is <METHOD> <Request-URI> HTTP/<HTTP-Version>, where HTTP-Version is 1.0 or 1.1. for HTTP/2: binary headers are used """ request = self.__...
Read HTTP-request line :param request_line: line to parse for HTTP/0.9 is GET <Request-URI> for HTTP/1.0 and 1.1 is <METHOD> <Request-URI> HTTP/<HTTP-Version>, where HTTP-Version is 1.0 or 1.1. for HTTP/2: binary headers are used
Below is the the instruction that describes the task: ### Input: Read HTTP-request line :param request_line: line to parse for HTTP/0.9 is GET <Request-URI> for HTTP/1.0 and 1.1 is <METHOD> <Request-URI> HTTP/<HTTP-Version>, where HTTP-Version is 1.0 or 1.1. for HTTP/2: binary headers are used ### Re...
def default_logging_dict(*loggers: str, **kwargs: Any) -> DictStrAny: r"""Prepare logging dict suitable with ``logging.config.dictConfig``. **Usage**:: from logging.config import dictConfig dictConfig(default_logging_dict('yourlogger')) :param \*loggers: Enable logging for each logger in ...
r"""Prepare logging dict suitable with ``logging.config.dictConfig``. **Usage**:: from logging.config import dictConfig dictConfig(default_logging_dict('yourlogger')) :param \*loggers: Enable logging for each logger in sequence. :param \*\*kwargs: Setup additional logger params via keywor...
Below is the the instruction that describes the task: ### Input: r"""Prepare logging dict suitable with ``logging.config.dictConfig``. **Usage**:: from logging.config import dictConfig dictConfig(default_logging_dict('yourlogger')) :param \*loggers: Enable logging for each logger in seque...
def get(self, name): """Get the vrrp configurations for a single node interface Args: name (string): The name of the interface for which vrrp configurations will be retrieved. Returns: A dictionary containing the vrrp configurations on the interface. ...
Get the vrrp configurations for a single node interface Args: name (string): The name of the interface for which vrrp configurations will be retrieved. Returns: A dictionary containing the vrrp configurations on the interface. Returns None if no vrrp...
Below is the the instruction that describes the task: ### Input: Get the vrrp configurations for a single node interface Args: name (string): The name of the interface for which vrrp configurations will be retrieved. Returns: A dictionary containing the vrrp...
def field(self, field_name, boost=1, extractor=None): """Adds a field to the list of document fields that will be indexed. Every document being indexed should have this field. None values for this field in indexed documents will not cause errors but will limit the chance of that documen...
Adds a field to the list of document fields that will be indexed. Every document being indexed should have this field. None values for this field in indexed documents will not cause errors but will limit the chance of that document being retrieved by searches. All fields should be adde...
Below is the the instruction that describes the task: ### Input: Adds a field to the list of document fields that will be indexed. Every document being indexed should have this field. None values for this field in indexed documents will not cause errors but will limit the chance of that doc...
def call_task_fn(self): """Call the function attached to the task.""" if not self.fn: return self.log_finished() future = asyncio.Future() future.add_done_callback(lambda x: self.log_finished()) if inspect.iscoroutinefunction(self.fn): f = asyncio.ensure_future(self.fn()) f.add_done_callback(lambda...
Call the function attached to the task.
Below is the the instruction that describes the task: ### Input: Call the function attached to the task. ### Response: def call_task_fn(self): """Call the function attached to the task.""" if not self.fn: return self.log_finished() future = asyncio.Future() future.add_done_callback(lambda x: self.log_f...
def createMenu( self ): """ Creates a new menu with the given name. """ name, accepted = QInputDialog.getText( self, 'Create Menu', 'Name: ') if ( accepted ): self.a...
Creates a new menu with the given name.
Below is the the instruction that describes the task: ### Input: Creates a new menu with the given name. ### Response: def createMenu( self ): """ Creates a new menu with the given name. """ name, accepted = QInputDialog.getText( self, ...
def getGroup(self, networkId, groupNodeId, verbose=None): """ Returns the group specified by the `groupNodeId` and `networkId` parameters. :param networkId: SUID of the Network :param groupNodeId: SUID of the Node representing the Group :param verbose: print more :retur...
Returns the group specified by the `groupNodeId` and `networkId` parameters. :param networkId: SUID of the Network :param groupNodeId: SUID of the Node representing the Group :param verbose: print more :returns: 200: successful operation
Below is the the instruction that describes the task: ### Input: Returns the group specified by the `groupNodeId` and `networkId` parameters. :param networkId: SUID of the Network :param groupNodeId: SUID of the Node representing the Group :param verbose: print more :returns: 200: ...
def addinnode(self, otherplus, node, objectname): """add an item to the node. example: add a new zone to the element 'ZONE' """ # do a test for unique object here newelement = otherplus.dt[node.upper()]
add an item to the node. example: add a new zone to the element 'ZONE'
Below is the the instruction that describes the task: ### Input: add an item to the node. example: add a new zone to the element 'ZONE' ### Response: def addinnode(self, otherplus, node, objectname): """add an item to the node. example: add a new zone to the element 'ZONE' """ # do ...
def filelines(fname,strip=False): '''read lines from a file into lines...optional strip''' with open(fname,'r') as f: lines = f.readlines(); if strip: lines[:] = [line.strip() for line in lines] return lines;
read lines from a file into lines...optional strip
Below is the the instruction that describes the task: ### Input: read lines from a file into lines...optional strip ### Response: def filelines(fname,strip=False): '''read lines from a file into lines...optional strip''' with open(fname,'r') as f: lines = f.readlines(); if strip: lines[...
def message(self, body, room_id, style='text'): ''' Send a message to the given room ''' # TODO Automatically detect body format ? path = 'rooms/message' data = { 'room_id': room_id, 'message': body, 'from': self.name, 'notify': 1, ...
Send a message to the given room
Below is the the instruction that describes the task: ### Input: Send a message to the given room ### Response: def message(self, body, room_id, style='text'): ''' Send a message to the given room ''' # TODO Automatically detect body format ? path = 'rooms/message' data = { ...
def _prepare_io_handler(self, handler): """Call the `interfaces.IOHandler.prepare` method and remove the handler from unprepared handler list when done. """ logger.debug(" preparing handler: {0!r}".format(handler)) self._unprepared_pending.discard(handler) ret = handler.p...
Call the `interfaces.IOHandler.prepare` method and remove the handler from unprepared handler list when done.
Below is the the instruction that describes the task: ### Input: Call the `interfaces.IOHandler.prepare` method and remove the handler from unprepared handler list when done. ### Response: def _prepare_io_handler(self, handler): """Call the `interfaces.IOHandler.prepare` method and remove t...
def db_stats(self): """Get database statistics. Returns: DBStats: Total clicks and links statistics. Raises: requests.exceptions.HTTPError: Generic HTTP Error """ data = dict(action='db-stats') jsondata = self._api_request(params=data) s...
Get database statistics. Returns: DBStats: Total clicks and links statistics. Raises: requests.exceptions.HTTPError: Generic HTTP Error
Below is the the instruction that describes the task: ### Input: Get database statistics. Returns: DBStats: Total clicks and links statistics. Raises: requests.exceptions.HTTPError: Generic HTTP Error ### Response: def db_stats(self): """Get database statistics. ...
def get_parse(self, show=True, proxy=None, timeout=0): """ GET MediaWiki:API action=parse request https://en.wikipedia.org/w/api.php?action=help&modules=parse Required {params}: title OR pageid - title: <str> article title - pageid: <int> Wikipedia database ID O...
GET MediaWiki:API action=parse request https://en.wikipedia.org/w/api.php?action=help&modules=parse Required {params}: title OR pageid - title: <str> article title - pageid: <int> Wikipedia database ID Optional arguments: - [show]: <bool> echo page data if true ...
Below is the the instruction that describes the task: ### Input: GET MediaWiki:API action=parse request https://en.wikipedia.org/w/api.php?action=help&modules=parse Required {params}: title OR pageid - title: <str> article title - pageid: <int> Wikipedia database ID Optiona...
def get_addresses_details(address_list, coin_symbol='btc', txn_limit=None, api_key=None, before_bh=None, after_bh=None, unspent_only=False, show_confidence=False, confirmations=0, include_script=False): ''' Batch version of get_address_details method ''' for address in address_list: ...
Batch version of get_address_details method
Below is the the instruction that describes the task: ### Input: Batch version of get_address_details method ### Response: def get_addresses_details(address_list, coin_symbol='btc', txn_limit=None, api_key=None, before_bh=None, after_bh=None, unspent_only=False, show_confidence=False, confirmations...
def join_all(domain, *parts): """ Join all url components. Example:: >>> join_all("https://www.apple.com", "iphone") https://www.apple.com/iphone :param domain: Domain parts, example: https://www.python.org :param parts: Other parts, example: "/doc", "/py27" :return: url "...
Join all url components. Example:: >>> join_all("https://www.apple.com", "iphone") https://www.apple.com/iphone :param domain: Domain parts, example: https://www.python.org :param parts: Other parts, example: "/doc", "/py27" :return: url
Below is the the instruction that describes the task: ### Input: Join all url components. Example:: >>> join_all("https://www.apple.com", "iphone") https://www.apple.com/iphone :param domain: Domain parts, example: https://www.python.org :param parts: Other parts, example: "/doc", "/p...
def writejar(self, jar): """Schedules all entries from the given ``jar``'s to be added to this jar save for the manifest. :param string jar: the path to the pre-existing jar to graft into this jar """ if not jar or not isinstance(jar, string_types): raise ValueError('The jar path must be a non-em...
Schedules all entries from the given ``jar``'s to be added to this jar save for the manifest. :param string jar: the path to the pre-existing jar to graft into this jar
Below is the the instruction that describes the task: ### Input: Schedules all entries from the given ``jar``'s to be added to this jar save for the manifest. :param string jar: the path to the pre-existing jar to graft into this jar ### Response: def writejar(self, jar): """Schedules all entries from the...
def get_activity_admin_session_for_objective_bank(self, objective_bank_id, proxy, *args, **kwargs): """Gets the ``OsidSession`` associated with the activity admin service for the given objective bank. :param objective_bank_id: the ``Id`` of the objective bank :type objective_bank_id: ``osid.id....
Gets the ``OsidSession`` associated with the activity admin service for the given objective bank. :param objective_bank_id: the ``Id`` of the objective bank :type objective_bank_id: ``osid.id.Id`` :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: a ``ActivityAdmin...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the activity admin service for the given objective bank. :param objective_bank_id: the ``Id`` of the objective bank :type objective_bank_id: ``osid.id.Id`` :param proxy: a proxy ...
def remove_core_element(self, model): """Remove respective core element of handed global variable name :param str model: String that is the key/gv_name of core element which should be removed :return: """ gv_name = model if self.global_variable_is_editable(gv_name, "Dele...
Remove respective core element of handed global variable name :param str model: String that is the key/gv_name of core element which should be removed :return:
Below is the the instruction that describes the task: ### Input: Remove respective core element of handed global variable name :param str model: String that is the key/gv_name of core element which should be removed :return: ### Response: def remove_core_element(self, model): """Remove res...
def which(program, path=None): """ Returns the full path of shell commands. Replicates the functionality of system which (1) command. Looks for the named program in the directories indicated in the $PATH environment variable, and returns the full path if found. Examples: >>> system.wh...
Returns the full path of shell commands. Replicates the functionality of system which (1) command. Looks for the named program in the directories indicated in the $PATH environment variable, and returns the full path if found. Examples: >>> system.which("ls") "/bin/ls" >>> sy...
Below is the the instruction that describes the task: ### Input: Returns the full path of shell commands. Replicates the functionality of system which (1) command. Looks for the named program in the directories indicated in the $PATH environment variable, and returns the full path if found. Exampl...
def get_document_field(instance): """ Returns which field the search index has marked as it's `document=True` field. """ for name, field in instance.searchindex.fields.items(): if field.document is True: return name
Returns which field the search index has marked as it's `document=True` field.
Below is the the instruction that describes the task: ### Input: Returns which field the search index has marked as it's `document=True` field. ### Response: def get_document_field(instance): """ Returns which field the search index has marked as it's `document=True` field. ...
def pem2der(pem_string): """Convert PEM string to DER format""" # Encode all lines between the first '-----\n' and the 2nd-to-last '-----'. pem_string = pem_string.replace(b"\r", b"") first_idx = pem_string.find(b"-----\n") + 6 if pem_string.find(b"-----BEGIN", first_idx) != -1: raise Except...
Convert PEM string to DER format
Below is the the instruction that describes the task: ### Input: Convert PEM string to DER format ### Response: def pem2der(pem_string): """Convert PEM string to DER format""" # Encode all lines between the first '-----\n' and the 2nd-to-last '-----'. pem_string = pem_string.replace(b"\r", b"") fir...
def list_datastores_full(kwargs=None, call=None): ''' List all the datastores for this VMware environment, with extra information CLI Example: .. code-block:: bash salt-cloud -f list_datastores_full my-vmware-config ''' if call != 'function': raise SaltCloudSystemExit( ...
List all the datastores for this VMware environment, with extra information CLI Example: .. code-block:: bash salt-cloud -f list_datastores_full my-vmware-config
Below is the the instruction that describes the task: ### Input: List all the datastores for this VMware environment, with extra information CLI Example: .. code-block:: bash salt-cloud -f list_datastores_full my-vmware-config ### Response: def list_datastores_full(kwargs=None, call=None): '...
def cancel_job(self, job_resource_name: str): """Cancels the given job. See also the cancel method on EngineJob. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. """ self.service.projects().progra...
Cancels the given job. See also the cancel method on EngineJob. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`.
Below is the the instruction that describes the task: ### Input: Cancels the given job. See also the cancel method on EngineJob. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. ### Response: def cancel_job(self, jo...
def get_print_list(): """ get_print_list """ profiler = start_profile() meth1() meth2() meth3() meth4() return end_profile(profiler, returnvalue=True)
get_print_list
Below is the the instruction that describes the task: ### Input: get_print_list ### Response: def get_print_list(): """ get_print_list """ profiler = start_profile() meth1() meth2() meth3() meth4() return end_profile(profiler, returnvalue=True)
async def create( cls, node: Union[Node, str], cache_device: Union[BlockDevice, Partition]): """ Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to...
Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to create the cache set on. :type cache_device: `BlockDevice` or `Partition`
Below is the the instruction that describes the task: ### Input: Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to create the cache set on. :type cache_device: `B...
def ndim(self): """If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays.""" if self.is_raster(): return { FeatureType.DATA: 4, FeatureType.MASK: 4, FeatureType.SCALAR: 2, FeatureType.LA...
If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays.
Below is the the instruction that describes the task: ### Input: If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays. ### Response: def ndim(self): """If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays.""" if s...
def each_object_id(collection): """Yields each object ID in the given ``collection``. The objects are not loaded.""" c_path = collection_path(collection) paths = glob('%s/*.%s' % (c_path, _ext)) for path in paths: match = regex.match(r'.+/(.+)\.%s$' % _ext, path) yield match.groups()...
Yields each object ID in the given ``collection``. The objects are not loaded.
Below is the the instruction that describes the task: ### Input: Yields each object ID in the given ``collection``. The objects are not loaded. ### Response: def each_object_id(collection): """Yields each object ID in the given ``collection``. The objects are not loaded.""" c_path = collection_path...
def apply_cast(scope, input_name, output_name, container, operator_name=None, to=None): ''' :param to: enum defined in ONNX TensorProto.DataType, for example, TensorProto.FLOAT and TensorProto.INT64. ''' name = _create_name_or_use_existing_one(scope, 'Cast', operator_name) attrs = {'name': name} ...
:param to: enum defined in ONNX TensorProto.DataType, for example, TensorProto.FLOAT and TensorProto.INT64.
Below is the the instruction that describes the task: ### Input: :param to: enum defined in ONNX TensorProto.DataType, for example, TensorProto.FLOAT and TensorProto.INT64. ### Response: def apply_cast(scope, input_name, output_name, container, operator_name=None, to=None): ''' :param to: enum defined in O...
def headers_as_list(self): """ Does the same as 'headers' except it is returned as a list. """ headers = self.headers headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)] return headers_list
Does the same as 'headers' except it is returned as a list.
Below is the the instruction that describes the task: ### Input: Does the same as 'headers' except it is returned as a list. ### Response: def headers_as_list(self): """ Does the same as 'headers' except it is returned as a list. """ headers = self.headers headers_list = ['{...
def parse(self, arguments): """Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item. """ if not isinstance(a...
Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item.
Below is the the instruction that describes the task: ### Input: Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one ite...
def authorized(self, request_token): """Create a verifier for an user authorized client""" verifier = generate_token(length=self.verifier_length[1]) self.save_verifier(request_token, verifier) response = [ (u'oauth_token', request_token), (u'oauth_verifier', verif...
Create a verifier for an user authorized client
Below is the the instruction that describes the task: ### Input: Create a verifier for an user authorized client ### Response: def authorized(self, request_token): """Create a verifier for an user authorized client""" verifier = generate_token(length=self.verifier_length[1]) self.save_verif...
def ReadHuntCounters(self, hunt_id): """Reads hunt counters.""" num_clients = self.CountHuntFlows(hunt_id) num_successful_clients = self.CountHuntFlows( hunt_id, filter_condition=db.HuntFlowsCondition.SUCCEEDED_FLOWS_ONLY) num_failed_clients = self.CountHuntFlows( hunt_id, filter_conditi...
Reads hunt counters.
Below is the the instruction that describes the task: ### Input: Reads hunt counters. ### Response: def ReadHuntCounters(self, hunt_id): """Reads hunt counters.""" num_clients = self.CountHuntFlows(hunt_id) num_successful_clients = self.CountHuntFlows( hunt_id, filter_condition=db.HuntFlowsCond...
def tile(lt, width=70, gap=1): """ Pretty print list of items. """ from jcvi.utils.iter import grouper max_len = max(len(x) for x in lt) + gap items_per_line = max(width // max_len, 1) lt = [x.rjust(max_len) for x in lt] g = list(grouper(lt, items_per_line, fillvalue="")) return "\...
Pretty print list of items.
Below is the the instruction that describes the task: ### Input: Pretty print list of items. ### Response: def tile(lt, width=70, gap=1): """ Pretty print list of items. """ from jcvi.utils.iter import grouper max_len = max(len(x) for x in lt) + gap items_per_line = max(width // max_len, 1...
def delete(cls, repo, *refs, **kwargs): """Delete the given remote references :note: kwargs are given for comparability with the base class method as we should not narrow the signature.""" repo.git.branch("-d", "-r", *refs) # the official deletion method will ign...
Delete the given remote references :note: kwargs are given for comparability with the base class method as we should not narrow the signature.
Below is the the instruction that describes the task: ### Input: Delete the given remote references :note: kwargs are given for comparability with the base class method as we should not narrow the signature. ### Response: def delete(cls, repo, *refs, **kwargs): """Delete th...
def move(self, fnames=None, directory=None): """Move files/directories""" if fnames is None: fnames = self.get_selected_filenames() orig = fixpath(osp.dirname(fnames[0])) while True: self.redirect_stdio.emit(False) if directory is None: ...
Move files/directories
Below is the the instruction that describes the task: ### Input: Move files/directories ### Response: def move(self, fnames=None, directory=None): """Move files/directories""" if fnames is None: fnames = self.get_selected_filenames() orig = fixpath(osp.dirname(fnames[0])) ...
def Emboss(alpha=0, strength=1, name=None, deterministic=False, random_state=None): """ Augmenter that embosses images and overlays the result with the original image. The embossed version pronounces highlights and shadows, letting the image look as if it was recreated on a metal plate ("embossed")...
Augmenter that embosses images and overlays the result with the original image. The embossed version pronounces highlights and shadows, letting the image look as if it was recreated on a metal plate ("embossed"). dtype support:: See ``imgaug.augmenters.convolutional.Convolve``. Parameter...
Below is the the instruction that describes the task: ### Input: Augmenter that embosses images and overlays the result with the original image. The embossed version pronounces highlights and shadows, letting the image look as if it was recreated on a metal plate ("embossed"). dtype support:: ...
def add_port_to_free_pool(self, port): """Add a new port to the free pool for allocation.""" if port < 1 or port > 65535: raise ValueError( 'Port must be in the [1, 65535] range, not %d.' % port) port_info = _PortInfo(port=port) self._port_queue.append(port_in...
Add a new port to the free pool for allocation.
Below is the the instruction that describes the task: ### Input: Add a new port to the free pool for allocation. ### Response: def add_port_to_free_pool(self, port): """Add a new port to the free pool for allocation.""" if port < 1 or port > 65535: raise ValueError( 'Por...
def parse_navigation_html_to_tree(html, id): """Parse the given ``html`` (an etree object) to a tree. The ``id`` is required in order to assign the top-level tree id value. """ def xpath(x): return html.xpath(x, namespaces=HTML_DOCUMENT_NAMESPACES) try: value = xpath('//*[@data-type=...
Parse the given ``html`` (an etree object) to a tree. The ``id`` is required in order to assign the top-level tree id value.
Below is the the instruction that describes the task: ### Input: Parse the given ``html`` (an etree object) to a tree. The ``id`` is required in order to assign the top-level tree id value. ### Response: def parse_navigation_html_to_tree(html, id): """Parse the given ``html`` (an etree object) to a tree. ...
def quaternion_about_axis(angle, axis): """Return quaternion for rotation about axis. >>> q = quaternion_about_axis(0.123, (1, 0, 0)) >>> numpy.allclose(q, [0.06146124, 0, 0, 0.99810947]) True """ quaternion = numpy.zeros((4, ), dtype=numpy.float64) quaternion[:3] = axis[:3] qlen = vec...
Return quaternion for rotation about axis. >>> q = quaternion_about_axis(0.123, (1, 0, 0)) >>> numpy.allclose(q, [0.06146124, 0, 0, 0.99810947]) True
Below is the the instruction that describes the task: ### Input: Return quaternion for rotation about axis. >>> q = quaternion_about_axis(0.123, (1, 0, 0)) >>> numpy.allclose(q, [0.06146124, 0, 0, 0.99810947]) True ### Response: def quaternion_about_axis(angle, axis): """Return quaternion for rota...
def check_for_cores(self): """! @brief Init task: verify that at least one core was discovered.""" if not len(self.cores): # Allow the user to override the exception to enable uses like chip bringup. if self.session.options.get('allow_no_cores', False): logging.er...
! @brief Init task: verify that at least one core was discovered.
Below is the the instruction that describes the task: ### Input: ! @brief Init task: verify that at least one core was discovered. ### Response: def check_for_cores(self): """! @brief Init task: verify that at least one core was discovered.""" if not len(self.cores): # Allow the user to...
def src_builder(self): """Fetch the source code builder for this node. If there isn't one, we cache the source code builder specified for the directory (which in turn will cache the value from its parent directory, and so on up to the file system root). """ try: ...
Fetch the source code builder for this node. If there isn't one, we cache the source code builder specified for the directory (which in turn will cache the value from its parent directory, and so on up to the file system root).
Below is the the instruction that describes the task: ### Input: Fetch the source code builder for this node. If there isn't one, we cache the source code builder specified for the directory (which in turn will cache the value from its parent directory, and so on up to the file system root)...
def random_seed(seed=42): """ sets the random seed of Python within the context. Example ------- >>> import random >>> with random_seed(seed=0): ... random.randint(0, 1000) # doctest: +SKIP 864 """ old_state = random.getstate() random.seed(seed) try: yield fin...
sets the random seed of Python within the context. Example ------- >>> import random >>> with random_seed(seed=0): ... random.randint(0, 1000) # doctest: +SKIP 864
Below is the the instruction that describes the task: ### Input: sets the random seed of Python within the context. Example ------- >>> import random >>> with random_seed(seed=0): ... random.randint(0, 1000) # doctest: +SKIP 864 ### Response: def random_seed(seed=42): """ sets the r...
def get_instance(self, payload): """ Build an instance of ConferenceInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.conference.ConferenceInstance :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance """ ...
Build an instance of ConferenceInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.conference.ConferenceInstance :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance
Below is the the instruction that describes the task: ### Input: Build an instance of ConferenceInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.conference.ConferenceInstance :rtype: twilio.rest.api.v2010.account.conference.ConferenceInsta...
def _sample_3d(self, n, seed=None): """Specialized inversion sampler for 3D.""" seed = seed_stream.SeedStream(seed, salt='von_mises_fisher_3d') u_shape = tf.concat([[n], self._batch_shape_tensor()], axis=0) z = tf.random.uniform(u_shape, seed=seed(), dtype=self.dtype) # TODO(bjp): Higher-order odd d...
Specialized inversion sampler for 3D.
Below is the the instruction that describes the task: ### Input: Specialized inversion sampler for 3D. ### Response: def _sample_3d(self, n, seed=None): """Specialized inversion sampler for 3D.""" seed = seed_stream.SeedStream(seed, salt='von_mises_fisher_3d') u_shape = tf.concat([[n], self._batch_shap...
def importPreflibFile(self, fileName): """ Imports a preflib format file that contains all the information of a Profile. This function will completely override all members of the current Profile object. Currently, we assume that in an election where incomplete ordering are allowed, if a...
Imports a preflib format file that contains all the information of a Profile. This function will completely override all members of the current Profile object. Currently, we assume that in an election where incomplete ordering are allowed, if a voter ranks only one candidate, then the voter di...
Below is the the instruction that describes the task: ### Input: Imports a preflib format file that contains all the information of a Profile. This function will completely override all members of the current Profile object. Currently, we assume that in an election where incomplete ordering are all...
def randomTraversal(sensations, numTraversals): """ Given a list of sensations, return the SDRs that would be obtained by numTraversals random traversals of that set of sensations. Each sensation is a dict mapping cortical column index to a pair of SDR's (one location and one feature). """ ...
Given a list of sensations, return the SDRs that would be obtained by numTraversals random traversals of that set of sensations. Each sensation is a dict mapping cortical column index to a pair of SDR's (one location and one feature).
Below is the the instruction that describes the task: ### Input: Given a list of sensations, return the SDRs that would be obtained by numTraversals random traversals of that set of sensations. Each sensation is a dict mapping cortical column index to a pair of SDR's (one location and one feature). ###...
def actually_start_agent(self, descriptor, **kwargs): """ This method will be run only on the master agency. """ factory = IAgentFactory( applications.lookup_agent(descriptor.type_name)) if factory.standalone: return self.start_standalone_agent(descriptor,...
This method will be run only on the master agency.
Below is the the instruction that describes the task: ### Input: This method will be run only on the master agency. ### Response: def actually_start_agent(self, descriptor, **kwargs): """ This method will be run only on the master agency. """ factory = IAgentFactory( app...
def hash_trees(self): "hash ladderized tree topologies" observed = {} for idx, tree in enumerate(self.treelist): nwk = tree.write(tree_format=9) hashed = md5(nwk.encode("utf-8")).hexdigest() if hashed not in observed: observed[hashed] = ...
hash ladderized tree topologies
Below is the the instruction that describes the task: ### Input: hash ladderized tree topologies ### Response: def hash_trees(self): "hash ladderized tree topologies" observed = {} for idx, tree in enumerate(self.treelist): nwk = tree.write(tree_format=9) hash...
def end_segment(self, end_time=None): """ End the current active segment. :param int end_time: epoch in seconds. If not specified the current system time will be used. """ entity = self.get_trace_entity() if not entity: log.warning("No segment to ...
End the current active segment. :param int end_time: epoch in seconds. If not specified the current system time will be used.
Below is the the instruction that describes the task: ### Input: End the current active segment. :param int end_time: epoch in seconds. If not specified the current system time will be used. ### Response: def end_segment(self, end_time=None): """ End the current active segment....
def get_students( self, gradebook_id='', simple=False, section_name='', include_photo=False, include_grade_info=False, include_grade_history=False, include_makeup_grades=False ): """Get students for a gradebook. ...
Get students for a gradebook. Get a list of students for a given gradebook, specified by a gradebook id. Does not include grade data. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): if ``True``, just return diction...
Below is the the instruction that describes the task: ### Input: Get students for a gradebook. Get a list of students for a given gradebook, specified by a gradebook id. Does not include grade data. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` ...
def _startGenresNode(self, name, attrs): """Process the start of a node under xtvd/genres""" if name == 'programGenre': self._programId = attrs.get('program') elif name == 'genre': self._genre = None self._relevance = None
Process the start of a node under xtvd/genres
Below is the the instruction that describes the task: ### Input: Process the start of a node under xtvd/genres ### Response: def _startGenresNode(self, name, attrs): """Process the start of a node under xtvd/genres""" if name == 'programGenre': self._programId = attrs.get('program') ...
def _get_inline_fragment(ast): """Return the inline fragment at the current AST node, or None if no fragment exists.""" if not ast.selection_set: # There is nothing selected here, so no fragment. return None fragments = [ ast_node for ast_node in ast.selection_set.selections...
Return the inline fragment at the current AST node, or None if no fragment exists.
Below is the the instruction that describes the task: ### Input: Return the inline fragment at the current AST node, or None if no fragment exists. ### Response: def _get_inline_fragment(ast): """Return the inline fragment at the current AST node, or None if no fragment exists.""" if not ast.selection_set:...
def read_some(self): """Read at least one byte of cooked data unless EOF is hit. Return '' if EOF is hit. Block if no data is immediately available. """ self.process_rawq() while self.cookedq.tell() == 0 and not self.eof: self.fill_rawq() self.p...
Read at least one byte of cooked data unless EOF is hit. Return '' if EOF is hit. Block if no data is immediately available.
Below is the the instruction that describes the task: ### Input: Read at least one byte of cooked data unless EOF is hit. Return '' if EOF is hit. Block if no data is immediately available. ### Response: def read_some(self): """Read at least one byte of cooked data unless EOF is hit. ...
def _submit(self, body, future): """Enqueue a problem for submission to the server. This method is thread safe. """ self._submission_queue.put(self._submit.Message(body, future))
Enqueue a problem for submission to the server. This method is thread safe.
Below is the the instruction that describes the task: ### Input: Enqueue a problem for submission to the server. This method is thread safe. ### Response: def _submit(self, body, future): """Enqueue a problem for submission to the server. This method is thread safe. """ se...
def get_creation_datetime(filepath): """ Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None """ if platform.system() == 'Windows': return datetime.fromtimestamp(os.path.getctime(filepa...
Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None
Below is the the instruction that describes the task: ### Input: Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None ### Response: def get_creation_datetime(filepath): """ Get the date that a file...
def update_counts(self, current): """ updates counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts """ for item in current: try: self.counts[item] += 1 ...
updates counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts
Below is the the instruction that describes the task: ### Input: updates counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts ### Response: def update_counts(self, current): """ updates counts for th...
def create_mixin(self): """ This will create the custom Model Mixin to attach to your custom field enabled model. :return: """ _builder = self class CustomModelMixin(object): @cached_property def _content_type(self): retu...
This will create the custom Model Mixin to attach to your custom field enabled model. :return:
Below is the the instruction that describes the task: ### Input: This will create the custom Model Mixin to attach to your custom field enabled model. :return: ### Response: def create_mixin(self): """ This will create the custom Model Mixin to attach to your custom field e...
def __dump_docker_compose(path, content, already_existed): ''' Dumps :param path: :param content: the not-yet dumped content :return: ''' try: dumped = yaml.safe_dump(content, indent=2, default_flow_style=False) return __write_docker_compose(path, dumped, already_existed) ...
Dumps :param path: :param content: the not-yet dumped content :return:
Below is the the instruction that describes the task: ### Input: Dumps :param path: :param content: the not-yet dumped content :return: ### Response: def __dump_docker_compose(path, content, already_existed): ''' Dumps :param path: :param content: the not-yet dumped content :retur...
def _from_dict(cls, _dict): """Initialize a Log object from a json dictionary.""" args = {} if 'request' in _dict: args['request'] = MessageRequest._from_dict(_dict.get('request')) else: raise ValueError( 'Required property \'request\' not present ...
Initialize a Log object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a Log object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a Log object from a json dictionary.""" args = {} if 'request' in _dict: args['request'] = MessageRequest._fro...
def _report_container_count(self, containers_by_id): """Report container count per state""" m_func = FUNC_MAP[GAUGE][self.use_histogram] per_state_count = defaultdict(int) filterlambda = lambda ctr: not self._is_container_excluded(ctr) containers = list(filter(filterlambda, con...
Report container count per state
Below is the the instruction that describes the task: ### Input: Report container count per state ### Response: def _report_container_count(self, containers_by_id): """Report container count per state""" m_func = FUNC_MAP[GAUGE][self.use_histogram] per_state_count = defaultdict(int) ...
def create(self, order_increment_id, items_qty, comment=None, email=True, include_comment=False): """ Create new shipment for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param items_qty: items qty to ship :type items_qty...
Create new shipment for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param items_qty: items qty to ship :type items_qty: associative array (order_item_id ⇒ qty) as dict :param comment: Shipment Comment :type comment: str :par...
Below is the the instruction that describes the task: ### Input: Create new shipment for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param items_qty: items qty to ship :type items_qty: associative array (order_item_id ⇒ qty) as dict :pa...
def _find_by_id(self, id): """ Expected response: { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], ...
Expected response: { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { ...
Below is the the instruction that describes the task: ### Input: Expected response: { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", ...
def on_get(resc, req, resp, rid): """ Find the model by id & serialize it back """ signals.pre_req.send(resc.model) signals.pre_req_find.send(resc.model) model = find(resc.model, rid) props = to_rest_model(model, includes=req.includes) resp.last_modified = model.updated resp.serialize(pro...
Find the model by id & serialize it back
Below is the the instruction that describes the task: ### Input: Find the model by id & serialize it back ### Response: def on_get(resc, req, resp, rid): """ Find the model by id & serialize it back """ signals.pre_req.send(resc.model) signals.pre_req_find.send(resc.model) model = find(resc.model...
def from_ast( pyast_node, node=None, node_cls=None, Node=Node, iter_fields=ast.iter_fields, AST=ast.AST): '''Convert the ast tree to a tater tree. ''' node_cls = node_cls or Node node = node or node_cls() name = pyast_node.__class__.__name__ attrs = [] for field, value in it...
Convert the ast tree to a tater tree.
Below is the the instruction that describes the task: ### Input: Convert the ast tree to a tater tree. ### Response: def from_ast( pyast_node, node=None, node_cls=None, Node=Node, iter_fields=ast.iter_fields, AST=ast.AST): '''Convert the ast tree to a tater tree. ''' node_cls = node_cls...
def get_extra(cls, name=None): """Gets extra configuration parameters. These parameters should be loaded through load_extra or load_extra_data. Args: name: str, the name of the configuration data to load. Returns: A dictionary containing the requested configuration data. None if dat...
Gets extra configuration parameters. These parameters should be loaded through load_extra or load_extra_data. Args: name: str, the name of the configuration data to load. Returns: A dictionary containing the requested configuration data. None if data was never loaded under that name.
Below is the the instruction that describes the task: ### Input: Gets extra configuration parameters. These parameters should be loaded through load_extra or load_extra_data. Args: name: str, the name of the configuration data to load. Returns: A dictionary containing the requested config...
def previous(self): """Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates. """ return self.mod...
Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates.
Below is the the instruction that describes the task: ### Input: Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates...
def blink_figure(self): """Blink figure once.""" if self.fig: self._blink_flag = not self._blink_flag self.repaint() if self._blink_flag: timer = QTimer() timer.singleShot(40, self.blink_figure)
Blink figure once.
Below is the the instruction that describes the task: ### Input: Blink figure once. ### Response: def blink_figure(self): """Blink figure once.""" if self.fig: self._blink_flag = not self._blink_flag self.repaint() if self._blink_flag: timer = QTi...
def select_loose_in(pl,k): ''' pl = ['bcd','xabcxx','x','y'] select_loose_in(pl,'abc') ''' def cond_func(ele,index,k): if(type(ele) == type([])): cond = loose_in(ele,k) else: cond = (k in ele) return(cond) arr = cond_select_values_all2(pl,c...
pl = ['bcd','xabcxx','x','y'] select_loose_in(pl,'abc')
Below is the the instruction that describes the task: ### Input: pl = ['bcd','xabcxx','x','y'] select_loose_in(pl,'abc') ### Response: def select_loose_in(pl,k): ''' pl = ['bcd','xabcxx','x','y'] select_loose_in(pl,'abc') ''' def cond_func(ele,index,k): if(type(ele) == t...
def list_roles(self, service_id=None, limit=None, marker=None): """ Returns a list of all global roles for users, optionally limited by service. Pagination can be handled through the standard 'limit' and 'marker' parameters. """ uri = "OS-KSADM/roles" pagination_i...
Returns a list of all global roles for users, optionally limited by service. Pagination can be handled through the standard 'limit' and 'marker' parameters.
Below is the the instruction that describes the task: ### Input: Returns a list of all global roles for users, optionally limited by service. Pagination can be handled through the standard 'limit' and 'marker' parameters. ### Response: def list_roles(self, service_id=None, limit=None, marker=None):...
def make_lib(self, version): """ Packs everything into a single lib/ directory. """ if os.path.exists(POETRY_LIB_BACKUP): shutil.rmtree(POETRY_LIB_BACKUP) # Backup the current installation if os.path.exists(POETRY_LIB): shutil.copytree(POETRY_LIB,...
Packs everything into a single lib/ directory.
Below is the the instruction that describes the task: ### Input: Packs everything into a single lib/ directory. ### Response: def make_lib(self, version): """ Packs everything into a single lib/ directory. """ if os.path.exists(POETRY_LIB_BACKUP): shutil.rmtree(POETRY_LI...
def delete_model(self, model): """Delete a specific session.""" if SessionActivity.is_current(sid_s=model.sid_s): flash('You could not remove your current session', 'error') return delete_session(sid_s=model.sid_s) db.session.commit()
Delete a specific session.
Below is the the instruction that describes the task: ### Input: Delete a specific session. ### Response: def delete_model(self, model): """Delete a specific session.""" if SessionActivity.is_current(sid_s=model.sid_s): flash('You could not remove your current session', 'error') ...
def read_mutiple_items(f, container_type, item_type, separator=" "): """ Extract an iterable from the current line of a file-like object. Args: f (file): the file-like object to read from container_type (type): type of the iterable that will be returned item_type (type): type of the va...
Extract an iterable from the current line of a file-like object. Args: f (file): the file-like object to read from container_type (type): type of the iterable that will be returned item_type (type): type of the values that will be elements of the returned iterable separator (str): t...
Below is the the instruction that describes the task: ### Input: Extract an iterable from the current line of a file-like object. Args: f (file): the file-like object to read from container_type (type): type of the iterable that will be returned item_type (type): type of the values that...
def _draw_line_numbers(self): """ Create drawables for the line numbers. """ if not self.line_numbers: return for p in xrange(self.maxlineno): n = p + self.line_number_start if (n % self.line_number_step) == 0: self._draw_linenu...
Create drawables for the line numbers.
Below is the the instruction that describes the task: ### Input: Create drawables for the line numbers. ### Response: def _draw_line_numbers(self): """ Create drawables for the line numbers. """ if not self.line_numbers: return for p in xrange(self.maxlineno): ...
def get(cls, group, admin): """Get specific GroupAdmin object.""" try: ga = cls.query.filter_by( group=group, admin_id=admin.get_id(), admin_type=resolve_admin_type(admin)).one() return ga except Exception: return None
Get specific GroupAdmin object.
Below is the the instruction that describes the task: ### Input: Get specific GroupAdmin object. ### Response: def get(cls, group, admin): """Get specific GroupAdmin object.""" try: ga = cls.query.filter_by( group=group, admin_id=admin.get_id(), admin_typ...
def sync(self): """ Fetch the list of apps from Marathon, find the domains that require certificates, and issue certificates for any domains that don't already have a certificate. """ self.log.info('Starting a sync...') def log_success(result): self.l...
Fetch the list of apps from Marathon, find the domains that require certificates, and issue certificates for any domains that don't already have a certificate.
Below is the the instruction that describes the task: ### Input: Fetch the list of apps from Marathon, find the domains that require certificates, and issue certificates for any domains that don't already have a certificate. ### Response: def sync(self): """ Fetch the list of apps f...
def contains_list(longer, shorter): """Check if longer list starts with shorter list""" if len(longer) <= len(shorter): return False for a, b in zip(shorter, longer): if a != b: return False return True
Check if longer list starts with shorter list
Below is the the instruction that describes the task: ### Input: Check if longer list starts with shorter list ### Response: def contains_list(longer, shorter): """Check if longer list starts with shorter list""" if len(longer) <= len(shorter): return False for a, b in zip(shorter, longer): ...
def _task_instances_for_dag_run(self, dag_run, session=None): """ Returns a map of task instance key to task instance object for the tasks to run in the given dag run. :param dag_run: the dag run to get the tasks from :type dag_run: airflow.models.DagRun :param session: ...
Returns a map of task instance key to task instance object for the tasks to run in the given dag run. :param dag_run: the dag run to get the tasks from :type dag_run: airflow.models.DagRun :param session: the database session object :type session: sqlalchemy.orm.session.Session
Below is the the instruction that describes the task: ### Input: Returns a map of task instance key to task instance object for the tasks to run in the given dag run. :param dag_run: the dag run to get the tasks from :type dag_run: airflow.models.DagRun :param session: the database ...
def waznlike(word1, wazn): """If the word1 is like a wazn (pattern), the letters must be equal, the wazn has FEH, AIN, LAM letters. this are as generic letters. The two words can be full vocalized, or partial vocalized @param word1: input word @type word1: unicode @param wazn: given...
If the word1 is like a wazn (pattern), the letters must be equal, the wazn has FEH, AIN, LAM letters. this are as generic letters. The two words can be full vocalized, or partial vocalized @param word1: input word @type word1: unicode @param wazn: given word template وزن @type wazn...
Below is the the instruction that describes the task: ### Input: If the word1 is like a wazn (pattern), the letters must be equal, the wazn has FEH, AIN, LAM letters. this are as generic letters. The two words can be full vocalized, or partial vocalized @param word1: input word @type wo...
def plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='Feature importance', ylabel='Features', importance_type='split', max_num_features=None, ignore_zero=True, figsize=None, grid=True, ...
Plot model's feature importances. Parameters ---------- booster : Booster or LGBMModel Booster or LGBMModel instance which feature importance should be plotted. ax : matplotlib.axes.Axes or None, optional (default=None) Target axes instance. If None, new figure and axes will be ...
Below is the the instruction that describes the task: ### Input: Plot model's feature importances. Parameters ---------- booster : Booster or LGBMModel Booster or LGBMModel instance which feature importance should be plotted. ax : matplotlib.axes.Axes or None, optional (default=None) ...
def metadata_converter_help(): """Help message for metadata converter Dialog. .. versionadded:: 4.3 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(conte...
Help message for metadata converter Dialog. .. versionadded:: 4.3 :returns: A message object containing helpful information. :rtype: messaging.message.Message
Below is the the instruction that describes the task: ### Input: Help message for metadata converter Dialog. .. versionadded:: 4.3 :returns: A message object containing helpful information. :rtype: messaging.message.Message ### Response: def metadata_converter_help(): """Help message for metadata...
def get_previous(self): """Returns the previous :obj:`Gtk.TreeModelRow` or None""" prev_iter = self.model.iter_previous(self.iter) if prev_iter: return TreeModelRow(self.model, prev_iter)
Returns the previous :obj:`Gtk.TreeModelRow` or None
Below is the the instruction that describes the task: ### Input: Returns the previous :obj:`Gtk.TreeModelRow` or None ### Response: def get_previous(self): """Returns the previous :obj:`Gtk.TreeModelRow` or None""" prev_iter = self.model.iter_previous(self.iter) if prev_iter: r...
def write_backup_meta_data(self): """Write the auto backup meta data into the current tmp-storage path""" auto_backup_meta_file = os.path.join(self._tmp_storage_path, FILE_NAME_AUTO_BACKUP) storage.storage_utils.write_dict_to_json(self.meta, auto_backup_meta_file)
Write the auto backup meta data into the current tmp-storage path
Below is the the instruction that describes the task: ### Input: Write the auto backup meta data into the current tmp-storage path ### Response: def write_backup_meta_data(self): """Write the auto backup meta data into the current tmp-storage path""" auto_backup_meta_file = os.path.join(self._tmp_s...
def runExperiment(): """ Experiment 1: Calculate error rate as a function of training sequence numbers :return: """ trainSeqN = [5, 10, 20, 50, 100, 200] rptPerCondition = 5 correctRateAll = np.zeros((len(trainSeqN), rptPerCondition)) missRateAll = np.zeros((len(trainSeqN), rptPerCondition)) fpRateAll...
Experiment 1: Calculate error rate as a function of training sequence numbers :return:
Below is the the instruction that describes the task: ### Input: Experiment 1: Calculate error rate as a function of training sequence numbers :return: ### Response: def runExperiment(): """ Experiment 1: Calculate error rate as a function of training sequence numbers :return: """ trainSeqN = [5, 10, 2...
def leaveEvent( self, event ): """ Toggles the display for the tracker item. """ item = self.trackerItem() if ( item ): item.setVisible(False)
Toggles the display for the tracker item.
Below is the the instruction that describes the task: ### Input: Toggles the display for the tracker item. ### Response: def leaveEvent( self, event ): """ Toggles the display for the tracker item. """ item = self.trackerItem() if ( item ): item.setVisible(...
def _gtu8(ins): """ Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 8 bit unsigned version """ output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True) output.append('cp h') o...
Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 8 bit unsigned version
Below is the the instruction that describes the task: ### Input: Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 8 bit unsigned version ### Response: def _gtu8(ins): """ Compares & pops top 2...