code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def closeEvent(self, event): """Send last file signal on close event :param event: The close event :type event: :returns: None :rtype: None :raises: None """ lf = self.browser.get_current_selection() if lf: self.last_file.emit(lf) ...
Send last file signal on close event :param event: The close event :type event: :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Send last file signal on close event :param event: The close event :type event: :returns: None :rtype: None :raises: None ### Response: def closeEvent(self, event): """Send last file signal on close ev...
def html_single_plot(self,abfID,launch=False,overwrite=False): """create ID_plot.html of just intrinsic properties.""" if type(abfID) is str: abfID=[abfID] for thisABFid in cm.abfSort(abfID): parentID=cm.parent(self.groups,thisABFid) saveAs=os.path.abspath("%s...
create ID_plot.html of just intrinsic properties.
Below is the the instruction that describes the task: ### Input: create ID_plot.html of just intrinsic properties. ### Response: def html_single_plot(self,abfID,launch=False,overwrite=False): """create ID_plot.html of just intrinsic properties.""" if type(abfID) is str: abfID=[abfID] ...
def ParseOptions(cls, options, configuration_object): """Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is o...
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type. BadConfigOption: when a configuration...
Below is the the instruction that describes the task: ### Input: Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration obj...
def proj2equidistant(network): """Defines conformal (e.g. WGS84) to ETRS (equidistant) projection Source CRS is loaded from Network's config. Parameters ---------- network : :class:`~.grid.network.Network` The eDisGo container object Returns ------- :py:func:`functools.partial`...
Defines conformal (e.g. WGS84) to ETRS (equidistant) projection Source CRS is loaded from Network's config. Parameters ---------- network : :class:`~.grid.network.Network` The eDisGo container object Returns ------- :py:func:`functools.partial`
Below is the the instruction that describes the task: ### Input: Defines conformal (e.g. WGS84) to ETRS (equidistant) projection Source CRS is loaded from Network's config. Parameters ---------- network : :class:`~.grid.network.Network` The eDisGo container object Returns ------- ...
def format_expose(expose): """ Converts a port number or multiple port numbers, as used in the Dockerfile ``EXPOSE`` command, to a tuple. :param: Port numbers, can be as integer, string, or a list/tuple of those. :type expose: int | unicode | str | list | tuple :return: A tuple, to be separated by ...
Converts a port number or multiple port numbers, as used in the Dockerfile ``EXPOSE`` command, to a tuple. :param: Port numbers, can be as integer, string, or a list/tuple of those. :type expose: int | unicode | str | list | tuple :return: A tuple, to be separated by spaces before inserting in a Dockerfile...
Below is the the instruction that describes the task: ### Input: Converts a port number or multiple port numbers, as used in the Dockerfile ``EXPOSE`` command, to a tuple. :param: Port numbers, can be as integer, string, or a list/tuple of those. :type expose: int | unicode | str | list | tuple :return...
def maybe_check_scalar_distribution(distribution, expected_base_dtype, validate_args): """Helper which checks validity of a scalar `distribution` init arg. Valid here means: * `distribution` has scalar batch and event shapes. * `distribution` is `FULLY_REPARAMETERIZED` * ...
Helper which checks validity of a scalar `distribution` init arg. Valid here means: * `distribution` has scalar batch and event shapes. * `distribution` is `FULLY_REPARAMETERIZED` * `distribution` has expected dtype. Args: distribution: `Distribution`-like object. expected_base_dtype: `TensorFlow...
Below is the the instruction that describes the task: ### Input: Helper which checks validity of a scalar `distribution` init arg. Valid here means: * `distribution` has scalar batch and event shapes. * `distribution` is `FULLY_REPARAMETERIZED` * `distribution` has expected dtype. Args: distributio...
def _event_size(event_shape, name=None): """Computes the number of elements in a tensor with shape `event_shape`. Args: event_shape: A tensor shape. name: The name to use for the tensor op to compute the number of elements (if such an op needs to be created). Returns: event_size: The number of...
Computes the number of elements in a tensor with shape `event_shape`. Args: event_shape: A tensor shape. name: The name to use for the tensor op to compute the number of elements (if such an op needs to be created). Returns: event_size: The number of elements in `tensor_shape`. Returns a numpy ...
Below is the the instruction that describes the task: ### Input: Computes the number of elements in a tensor with shape `event_shape`. Args: event_shape: A tensor shape. name: The name to use for the tensor op to compute the number of elements (if such an op needs to be created). Returns: ev...
def update(self, widget, widget_tree): """ for the selected widget are listed the relative signals for each signal there is a dropdown containing all the widgets the user will select the widget that have to listen a specific event """ self.listeners_list = [] self...
for the selected widget are listed the relative signals for each signal there is a dropdown containing all the widgets the user will select the widget that have to listen a specific event
Below is the the instruction that describes the task: ### Input: for the selected widget are listed the relative signals for each signal there is a dropdown containing all the widgets the user will select the widget that have to listen a specific event ### Response: def update(self, widget,...
def parse_mixed_delim_str(line): """Turns .obj face index string line into [verts, texcoords, normals] numeric tuples.""" arrs = [[], [], []] for group in line.split(' '): for col, coord in enumerate(group.split('/')): if coord: arrs[col].append(int(coord)) return [t...
Turns .obj face index string line into [verts, texcoords, normals] numeric tuples.
Below is the the instruction that describes the task: ### Input: Turns .obj face index string line into [verts, texcoords, normals] numeric tuples. ### Response: def parse_mixed_delim_str(line): """Turns .obj face index string line into [verts, texcoords, normals] numeric tuples.""" arrs = [[], [], []] ...
def rst_table(data, schema=None): """ Creates a reStructuredText simple table (list of strings) from a list of lists. """ # Process multi-rows (replaced by rows with empty columns when needed) pdata = [] for row in data: prow = [el if isinstance(el, list) else [el] for el in row] pdata.extend(pr f...
Creates a reStructuredText simple table (list of strings) from a list of lists.
Below is the the instruction that describes the task: ### Input: Creates a reStructuredText simple table (list of strings) from a list of lists. ### Response: def rst_table(data, schema=None): """ Creates a reStructuredText simple table (list of strings) from a list of lists. """ # Process multi-rows (...
def _set_dscp_exp_state(self, v, load=False): """ Setter method for dscp_exp_state, mapped from YANG variable /dscp_exp_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_dscp_exp_state is considered as a private method. Backends looking to populate th...
Setter method for dscp_exp_state, mapped from YANG variable /dscp_exp_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_dscp_exp_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_dscp...
Below is the the instruction that describes the task: ### Input: Setter method for dscp_exp_state, mapped from YANG variable /dscp_exp_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_dscp_exp_state is considered as a private method. Backends looking to ...
def set_dtreat_interp_indch(self, indch=None): """ Set the indices of the channels for which to interpolate data The index can be provided as: - A 1d np.ndarray of boolean or int indices of channels => interpolate data at these channels for all times - A dict wit...
Set the indices of the channels for which to interpolate data The index can be provided as: - A 1d np.ndarray of boolean or int indices of channels => interpolate data at these channels for all times - A dict with: * keys = int indices of times ...
Below is the the instruction that describes the task: ### Input: Set the indices of the channels for which to interpolate data The index can be provided as: - A 1d np.ndarray of boolean or int indices of channels => interpolate data at these channels for all times - ...
def get_storage_pool_by_name(self, name): """ Get ScaleIO StoragePool object by its name :param name: Name of StoragePool :return: ScaleIO StoragePool object :raise KeyError: No StoragePool with specified name found :rtype: StoragePool object """ for stora...
Get ScaleIO StoragePool object by its name :param name: Name of StoragePool :return: ScaleIO StoragePool object :raise KeyError: No StoragePool with specified name found :rtype: StoragePool object
Below is the the instruction that describes the task: ### Input: Get ScaleIO StoragePool object by its name :param name: Name of StoragePool :return: ScaleIO StoragePool object :raise KeyError: No StoragePool with specified name found :rtype: StoragePool object ### Response: def get...
def inspect_select_calculation(self): """Inspect the result of the CifSelectCalculation, verifying that it produced a CifData output node.""" try: node = self.ctx.cif_select self.ctx.cif = node.outputs.cif except exceptions.NotExistent: self.report('aborting: ...
Inspect the result of the CifSelectCalculation, verifying that it produced a CifData output node.
Below is the the instruction that describes the task: ### Input: Inspect the result of the CifSelectCalculation, verifying that it produced a CifData output node. ### Response: def inspect_select_calculation(self): """Inspect the result of the CifSelectCalculation, verifying that it produced a CifData outp...
def _route_message(self, message, data): """ Route message to any handlers on the message namespace """ # route message to handlers if message.namespace in self._handlers: # debug messages if message.namespace != NS_HEARTBEAT: self.logger.debug( ...
Route message to any handlers on the message namespace
Below is the the instruction that describes the task: ### Input: Route message to any handlers on the message namespace ### Response: def _route_message(self, message, data): """ Route message to any handlers on the message namespace """ # route message to handlers if message.namespace in s...
def file_add_tags(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /file-xxxx/addTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FaddTags """ return DXHTTPRequest('/%s/addTags' % object_id, input_para...
Invokes the /file-xxxx/addTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FaddTags
Below is the the instruction that describes the task: ### Input: Invokes the /file-xxxx/addTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FaddTags ### Response: def file_add_tags(object_id, input_params={}, always_retry=True, **kwargs)...
def destroy(name, conn=None, call=None): ''' Delete a single VM ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroy...
Delete a single VM
Below is the the instruction that describes the task: ### Input: Delete a single VM ### Response: def destroy(name, conn=None, call=None): ''' Delete a single VM ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' ...
def get_dicts(self): """Gets dicts in file :return: (generator of) of dicts with data from .csv file """ reader = csv.DictReader(open(self.path, "r", encoding=self.encoding)) for row in reader: if row: yield row
Gets dicts in file :return: (generator of) of dicts with data from .csv file
Below is the the instruction that describes the task: ### Input: Gets dicts in file :return: (generator of) of dicts with data from .csv file ### Response: def get_dicts(self): """Gets dicts in file :return: (generator of) of dicts with data from .csv file """ reader = csv...
def as_local_model(self): """ Makes sure our optimizer is wrapped into the global_optimizer meta. This is only relevant for distributed RL. """ super(MemoryModel, self).as_local_model() self.optimizer_spec = dict( type='global_optimizer', optimizer=self.op...
Makes sure our optimizer is wrapped into the global_optimizer meta. This is only relevant for distributed RL.
Below is the the instruction that describes the task: ### Input: Makes sure our optimizer is wrapped into the global_optimizer meta. This is only relevant for distributed RL. ### Response: def as_local_model(self): """ Makes sure our optimizer is wrapped into the global_optimizer meta. This is only...
def _get_and_start_work(self): "return (async_result, work_unit) or (None, None)" worker_id = nice_identifier() work_unit = self.task_master.get_work(worker_id, available_gb=self.available_gb()) if work_unit is None: return None, None async_result = self.pool.apply_as...
return (async_result, work_unit) or (None, None)
Below is the the instruction that describes the task: ### Input: return (async_result, work_unit) or (None, None) ### Response: def _get_and_start_work(self): "return (async_result, work_unit) or (None, None)" worker_id = nice_identifier() work_unit = self.task_master.get_work(worker_id, av...
def render_to_response(self, obj, **response_kwargs): """ Returns an ``HttpResponse`` object instance with Content-Type: application/json. The response body will be the return value of ``self.serialize(obj)`` """ return HttpResponse(self.serialize(obj), content_type='app...
Returns an ``HttpResponse`` object instance with Content-Type: application/json. The response body will be the return value of ``self.serialize(obj)``
Below is the the instruction that describes the task: ### Input: Returns an ``HttpResponse`` object instance with Content-Type: application/json. The response body will be the return value of ``self.serialize(obj)`` ### Response: def render_to_response(self, obj, **response_kwargs): """ ...
def _assign_new_thread_id(self, recursive=True): """ Assigns a new thread id to the task. :type recursive: bool :param recursive: Whether to assign the id to children recursively. :rtype: bool :returns: The new thread id. """ self.__class__.thread_id_po...
Assigns a new thread id to the task. :type recursive: bool :param recursive: Whether to assign the id to children recursively. :rtype: bool :returns: The new thread id.
Below is the the instruction that describes the task: ### Input: Assigns a new thread id to the task. :type recursive: bool :param recursive: Whether to assign the id to children recursively. :rtype: bool :returns: The new thread id. ### Response: def _assign_new_thread_id(self, ...
def start_notifications(self): """Start the notifications thread. If an external callback is not set up (using `update_webhook`) then calling this function is mandatory to get or set resource. .. code-block:: python >>> api.start_notifications() >>> print(api.g...
Start the notifications thread. If an external callback is not set up (using `update_webhook`) then calling this function is mandatory to get or set resource. .. code-block:: python >>> api.start_notifications() >>> print(api.get_resource_value(device, path)) ...
Below is the the instruction that describes the task: ### Input: Start the notifications thread. If an external callback is not set up (using `update_webhook`) then calling this function is mandatory to get or set resource. .. code-block:: python >>> api.start_notifications() ...
def choose_include_text(s, params, source_path): """Given the contents of a file and !inc[these params], return matching lines If there was a problem matching parameters, return empty list. :param s: file's text :param params: string like "start-at=foo&end-at=bar" :param source_path: path to source .md. Use...
Given the contents of a file and !inc[these params], return matching lines If there was a problem matching parameters, return empty list. :param s: file's text :param params: string like "start-at=foo&end-at=bar" :param source_path: path to source .md. Useful in error messages
Below is the the instruction that describes the task: ### Input: Given the contents of a file and !inc[these params], return matching lines If there was a problem matching parameters, return empty list. :param s: file's text :param params: string like "start-at=foo&end-at=bar" :param source_path: path to ...
def url_for(self, operation, _external=True, **kwargs): """ Construct a URL for an operation against a resource. :param kwargs: additional arguments for URL path expansion, which are passed to flask.url_for. In particular, _external=True produces absolute url. "...
Construct a URL for an operation against a resource. :param kwargs: additional arguments for URL path expansion, which are passed to flask.url_for. In particular, _external=True produces absolute url.
Below is the the instruction that describes the task: ### Input: Construct a URL for an operation against a resource. :param kwargs: additional arguments for URL path expansion, which are passed to flask.url_for. In particular, _external=True produces absolute url. ### Response: de...
def is_newer_b(a, bfiles): """ check that all b files have been modified more recently than a """ if isinstance(bfiles, basestring): bfiles = [bfiles] if not op.exists(a): return False if not all(op.exists(b) for b in bfiles): return False atime = os.stat(a).st_mtime # modification...
check that all b files have been modified more recently than a
Below is the the instruction that describes the task: ### Input: check that all b files have been modified more recently than a ### Response: def is_newer_b(a, bfiles): """ check that all b files have been modified more recently than a """ if isinstance(bfiles, basestring): bfiles = [bfiles...
def from_opcode(cls, opcode, arg=_no_arg): """ Create an instruction from an opcode and raw argument. Parameters ---------- opcode : int Opcode for the instruction to create. arg : int, optional The argument for the instruction. Returns ...
Create an instruction from an opcode and raw argument. Parameters ---------- opcode : int Opcode for the instruction to create. arg : int, optional The argument for the instruction. Returns ------- intsr : Instruction An insta...
Below is the the instruction that describes the task: ### Input: Create an instruction from an opcode and raw argument. Parameters ---------- opcode : int Opcode for the instruction to create. arg : int, optional The argument for the instruction. Ret...
def _parse_errback(self, error): """ Parse an error from an XML-RPC call. raises: ``IOError`` when the Twisted XML-RPC connection times out. raises: ``BugzillaNotFoundException`` raises: ``BugzillaNotAuthorizedException`` raises: ``BugzillaException`` if we got a respons...
Parse an error from an XML-RPC call. raises: ``IOError`` when the Twisted XML-RPC connection times out. raises: ``BugzillaNotFoundException`` raises: ``BugzillaNotAuthorizedException`` raises: ``BugzillaException`` if we got a response from the XML-RPC server but it is n...
Below is the the instruction that describes the task: ### Input: Parse an error from an XML-RPC call. raises: ``IOError`` when the Twisted XML-RPC connection times out. raises: ``BugzillaNotFoundException`` raises: ``BugzillaNotAuthorizedException`` raises: ``BugzillaException`` if ...
def add_eager_constraints(self, models): """ Set the constraints for an eager load of the relation. :type models: list """ super(MorphOneOrMany, self).add_eager_constraints(models) self._query.where(self._morph_type, self._morph_class)
Set the constraints for an eager load of the relation. :type models: list
Below is the the instruction that describes the task: ### Input: Set the constraints for an eager load of the relation. :type models: list ### Response: def add_eager_constraints(self, models): """ Set the constraints for an eager load of the relation. :type models: list "...
def parse_description(s): """ Returns a dictionary based on the FASTA header, assuming JCVI data """ s = "".join(s.split()[1:]).replace("/", ";") a = parse_qs(s) return a
Returns a dictionary based on the FASTA header, assuming JCVI data
Below is the the instruction that describes the task: ### Input: Returns a dictionary based on the FASTA header, assuming JCVI data ### Response: def parse_description(s): """ Returns a dictionary based on the FASTA header, assuming JCVI data """ s = "".join(s.split()[1:]).replace("/", ";") a =...
def PHASE(angle, qubit): """Produces the PHASE gate:: PHASE(phi) = [[1, 0], [0, exp(1j * phi)]] This is the same as the RZ gate. :param angle: The angle to rotate around the z-axis on the bloch sphere. :param qubit: The qubit apply the gate to. :returns: A Gate objec...
Produces the PHASE gate:: PHASE(phi) = [[1, 0], [0, exp(1j * phi)]] This is the same as the RZ gate. :param angle: The angle to rotate around the z-axis on the bloch sphere. :param qubit: The qubit apply the gate to. :returns: A Gate object.
Below is the the instruction that describes the task: ### Input: Produces the PHASE gate:: PHASE(phi) = [[1, 0], [0, exp(1j * phi)]] This is the same as the RZ gate. :param angle: The angle to rotate around the z-axis on the bloch sphere. :param qubit: The qubit apply th...
def update_query(self, query_update, project, query, undelete_descendants=None): """UpdateQuery. [Preview API] Update a query or a folder. This allows you to update, rename and move queries and folders. :param :class:`<QueryHierarchyItem> <azure.devops.v5_1.work_item_tracking.models.QueryHierarc...
UpdateQuery. [Preview API] Update a query or a folder. This allows you to update, rename and move queries and folders. :param :class:`<QueryHierarchyItem> <azure.devops.v5_1.work_item_tracking.models.QueryHierarchyItem>` query_update: The query to update. :param str project: Project ID or projec...
Below is the the instruction that describes the task: ### Input: UpdateQuery. [Preview API] Update a query or a folder. This allows you to update, rename and move queries and folders. :param :class:`<QueryHierarchyItem> <azure.devops.v5_1.work_item_tracking.models.QueryHierarchyItem>` query_update: ...
def set_status_return_level(self, srl_for_id, **kwargs): """ Sets status return level to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert if convert: srl_for_id = dict(zip(srl_for_id.keys(), [('never', '...
Sets status return level to the specified motors.
Below is the the instruction that describes the task: ### Input: Sets status return level to the specified motors. ### Response: def set_status_return_level(self, srl_for_id, **kwargs): """ Sets status return level to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else...
def set_default_pos(self, defaultPos): """Set the default starting location of our character.""" self.coords = defaultPos self.velocity = r.Vector2() self.desired_position = defaultPos r.Ragnarok.get_world().Camera.pan = self.coords r.Ragnarok.get_world().Camera.desired_p...
Set the default starting location of our character.
Below is the the instruction that describes the task: ### Input: Set the default starting location of our character. ### Response: def set_default_pos(self, defaultPos): """Set the default starting location of our character.""" self.coords = defaultPos self.velocity = r.Vector2() se...
def content_children(self): """ A sequence containing the text-container child elements of this ``<a:p>`` element, i.e. (a:r|a:br|a:fld). """ text_types = {CT_RegularTextRun, CT_TextLineBreak, CT_TextField} return tuple(elm for elm in self if type(elm) in text_types)
A sequence containing the text-container child elements of this ``<a:p>`` element, i.e. (a:r|a:br|a:fld).
Below is the the instruction that describes the task: ### Input: A sequence containing the text-container child elements of this ``<a:p>`` element, i.e. (a:r|a:br|a:fld). ### Response: def content_children(self): """ A sequence containing the text-container child elements of this ``...
def order_book(self, symbol, parameters=None): """ curl "https://api.bitfinex.com/v1/book/btcusd" {"bids":[{"price":"561.1101","amount":"0.985","timestamp":"1395557729.0"}],"asks":[{"price":"562.9999","amount":"0.985","timestamp":"1395557711.0"}]} The 'bids' and 'asks' arrays will have...
curl "https://api.bitfinex.com/v1/book/btcusd" {"bids":[{"price":"561.1101","amount":"0.985","timestamp":"1395557729.0"}],"asks":[{"price":"562.9999","amount":"0.985","timestamp":"1395557711.0"}]} The 'bids' and 'asks' arrays will have multiple bid and ask dicts. Optional parameters ...
Below is the the instruction that describes the task: ### Input: curl "https://api.bitfinex.com/v1/book/btcusd" {"bids":[{"price":"561.1101","amount":"0.985","timestamp":"1395557729.0"}],"asks":[{"price":"562.9999","amount":"0.985","timestamp":"1395557711.0"}]} The 'bids' and 'asks' arrays will ha...
def format_authors(self, format='html5', deparagraph=True, mathjax=False, smart=True, extra_args=None): """Get the document authors in the specified markup format. Parameters ---------- format : `str`, optional Output format (such as ``'html5'`` or ``'...
Get the document authors in the specified markup format. Parameters ---------- format : `str`, optional Output format (such as ``'html5'`` or ``'plain'``). deparagraph : `bool`, optional Remove the paragraph tags from single paragraph content. mathjax : `...
Below is the the instruction that describes the task: ### Input: Get the document authors in the specified markup format. Parameters ---------- format : `str`, optional Output format (such as ``'html5'`` or ``'plain'``). deparagraph : `bool`, optional Remove ...
def delete_vm(name, datacenter, placement=None, power_off=False, service_instance=None): ''' Deletes a virtual machine defined by name and placement name Name of the virtual machine datacenter Datacenter of the virtual machine placement Placement information ...
Deletes a virtual machine defined by name and placement name Name of the virtual machine datacenter Datacenter of the virtual machine placement Placement information of the virtual machine service_instance vCenter service instance for connection and configuration ...
Below is the the instruction that describes the task: ### Input: Deletes a virtual machine defined by name and placement name Name of the virtual machine datacenter Datacenter of the virtual machine placement Placement information of the virtual machine service_instance ...
def edit(self, data_src, value): """ Edit data layer. :param data_src: Name of :class:`DataSource` to edit. :type data_src: str :param value: Values to edit. :type value: dict """ # check if opening file if 'filename' in value: items =...
Edit data layer. :param data_src: Name of :class:`DataSource` to edit. :type data_src: str :param value: Values to edit. :type value: dict
Below is the the instruction that describes the task: ### Input: Edit data layer. :param data_src: Name of :class:`DataSource` to edit. :type data_src: str :param value: Values to edit. :type value: dict ### Response: def edit(self, data_src, value): """ Edit data l...
def inclusions_validation(tree:BubbleTree) -> iter: """Yield message about inclusions inconsistancies""" # search for powernode overlapping for one, two in it.combinations(tree.inclusions, 2): assert len(one) == len(one.strip()) assert len(two) == len(two.strip()) one_inc = set(inclu...
Yield message about inclusions inconsistancies
Below is the the instruction that describes the task: ### Input: Yield message about inclusions inconsistancies ### Response: def inclusions_validation(tree:BubbleTree) -> iter: """Yield message about inclusions inconsistancies""" # search for powernode overlapping for one, two in it.combinations(tree....
def patch(self, path=None, method='PATCH', **options): """ Equals :meth:`route` with a ``PATCH`` method parameter. """ return self.route(path, method, **options)
Equals :meth:`route` with a ``PATCH`` method parameter.
Below is the the instruction that describes the task: ### Input: Equals :meth:`route` with a ``PATCH`` method parameter. ### Response: def patch(self, path=None, method='PATCH', **options): """ Equals :meth:`route` with a ``PATCH`` method parameter. """ return self.route(path, method, **options)
def soft_threshold(x, threshold, name=None): """Soft Thresholding operator. This operator is defined by the equations ```none { x[i] - gamma, x[i] > gamma SoftThreshold(x, gamma)[i] = { 0, x[i] == gamma { x[i] + gamma, x[i] < -...
Soft Thresholding operator. This operator is defined by the equations ```none { x[i] - gamma, x[i] > gamma SoftThreshold(x, gamma)[i] = { 0, x[i] == gamma { x[i] + gamma, x[i] < -gamma ``` In the context of proximal gradient...
Below is the the instruction that describes the task: ### Input: Soft Thresholding operator. This operator is defined by the equations ```none { x[i] - gamma, x[i] > gamma SoftThreshold(x, gamma)[i] = { 0, x[i] == gamma { x[i] ...
def start_runs( logdir, steps, run_name, thresholds, mask_every_other_prediction=False): """Generate a PR curve with precision and recall evenly weighted. Arguments: logdir: The directory into which to store all the runs' data. steps: The number of steps to run for. run_name: The na...
Generate a PR curve with precision and recall evenly weighted. Arguments: logdir: The directory into which to store all the runs' data. steps: The number of steps to run for. run_name: The name of the run. thresholds: The number of thresholds to use for PR curves. mask_every_other_prediction: Whe...
Below is the the instruction that describes the task: ### Input: Generate a PR curve with precision and recall evenly weighted. Arguments: logdir: The directory into which to store all the runs' data. steps: The number of steps to run for. run_name: The name of the run. thresholds: The number of ...
def ReportConfiguration(self, f): """Report the boundary configuration details :param f: File (or standard out/err) :return: None """ if BoundaryCheck.chrom != -1: print >> f, BuildReportLine("CHROM", BoundaryCheck.chrom) if len(self.start_bounds) > 0: ...
Report the boundary configuration details :param f: File (or standard out/err) :return: None
Below is the the instruction that describes the task: ### Input: Report the boundary configuration details :param f: File (or standard out/err) :return: None ### Response: def ReportConfiguration(self, f): """Report the boundary configuration details :param f: File (or standard ou...
def create_top_level_index_entry(title, max_depth, subtitles): """Function for creating a text entry in index.rst for its content. :param title : Title for the content. :type title: str :param max_depth : Value for max_depth in the top level index content. :type max_depth: int :param subtitle...
Function for creating a text entry in index.rst for its content. :param title : Title for the content. :type title: str :param max_depth : Value for max_depth in the top level index content. :type max_depth: int :param subtitles : list of subtitles that is available. :type subtitles: list ...
Below is the the instruction that describes the task: ### Input: Function for creating a text entry in index.rst for its content. :param title : Title for the content. :type title: str :param max_depth : Value for max_depth in the top level index content. :type max_depth: int :param subtitles...
def pattern_logic_aeidon(): """Return patterns to be used for searching subtitles via aeidon.""" if Config.options.pattern_files: return prep_patterns(Config.options.pattern_files) elif Config.options.regex: return Config.REGEX else: return Config.TERMS
Return patterns to be used for searching subtitles via aeidon.
Below is the the instruction that describes the task: ### Input: Return patterns to be used for searching subtitles via aeidon. ### Response: def pattern_logic_aeidon(): """Return patterns to be used for searching subtitles via aeidon.""" if Config.options.pattern_files: return prep_patterns(Confi...
def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None): """ Get ann ids that satisfy given filter conditions. default skips that filter :param imgIds (int array) : get anns for given imgs catIds (int array) : get anns for given cats areaRng (f...
Get ann ids that satisfy given filter conditions. default skips that filter :param imgIds (int array) : get anns for given imgs catIds (int array) : get anns for given cats areaRng (float array) : get anns for given area range (e.g. [0 inf]) iscrowd (bool...
Below is the the instruction that describes the task: ### Input: Get ann ids that satisfy given filter conditions. default skips that filter :param imgIds (int array) : get anns for given imgs catIds (int array) : get anns for given cats areaRng (float array) : get ...
def get(self): """ Get a JSON-ready representation of this Ganalytics. :returns: This Ganalytics, ready for use in a request body. :rtype: dict """ keys = ["enable", "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign"] ganalytic...
Get a JSON-ready representation of this Ganalytics. :returns: This Ganalytics, ready for use in a request body. :rtype: dict
Below is the the instruction that describes the task: ### Input: Get a JSON-ready representation of this Ganalytics. :returns: This Ganalytics, ready for use in a request body. :rtype: dict ### Response: def get(self): """ Get a JSON-ready representation of this Ganalytics. ...
def evaluate_accuracy(data_iterator, network): """ Measure the accuracy of ResNet Parameters ---------- data_iterator: Iter examples of dataset network: ResNet Returns ---------- tuple of array element """ acc = mx.metric.Accuracy() # Iterate through data and l...
Measure the accuracy of ResNet Parameters ---------- data_iterator: Iter examples of dataset network: ResNet Returns ---------- tuple of array element
Below is the the instruction that describes the task: ### Input: Measure the accuracy of ResNet Parameters ---------- data_iterator: Iter examples of dataset network: ResNet Returns ---------- tuple of array element ### Response: def evaluate_accuracy(data_iterator, networ...
def get_version(self, dependency): """Return the installed version parsing the output of 'pip show'.""" logger.debug("getting installed version for %s", dependency) stdout = helpers.logged_exec([self.pip_exe, "show", str(dependency)]) version = [line for line in stdout if line.startswith...
Return the installed version parsing the output of 'pip show'.
Below is the the instruction that describes the task: ### Input: Return the installed version parsing the output of 'pip show'. ### Response: def get_version(self, dependency): """Return the installed version parsing the output of 'pip show'.""" logger.debug("getting installed version for %s", depe...
def id_to_word(self, word_id): """Returns the word string of an integer word id.""" if word_id >= len(self.reverse_vocab): return self.reverse_vocab[self.unk_id] else: return self.reverse_vocab[word_id]
Returns the word string of an integer word id.
Below is the the instruction that describes the task: ### Input: Returns the word string of an integer word id. ### Response: def id_to_word(self, word_id): """Returns the word string of an integer word id.""" if word_id >= len(self.reverse_vocab): return self.reverse_vocab[self.unk_id]...
def set_prefix(self, prefix): """ Set the prefix for the node (see Leaf class). DEPRECATED; use the prefix property directly. """ warnings.warn("set_prefix() is deprecated; use the prefix property", DeprecationWarning, stacklevel=2) self.prefix = pr...
Set the prefix for the node (see Leaf class). DEPRECATED; use the prefix property directly.
Below is the the instruction that describes the task: ### Input: Set the prefix for the node (see Leaf class). DEPRECATED; use the prefix property directly. ### Response: def set_prefix(self, prefix): """ Set the prefix for the node (see Leaf class). DEPRECATED; use the prefix pro...
def extract(self, extractor: Extractor, extractable: Extractable = None, tokenizer: Tokenizer = None, joiner: str = " ", **options) -> List[Extraction]: """ Invoke the extractor on the given extractable, accumulating all the extractions in a list. Args: extractor (...
Invoke the extractor on the given extractable, accumulating all the extractions in a list. Args: extractor (Extractor): extractable (extractable): tokenizer: user can pass custom tokenizer if extractor wants token joiner: user can pass joiner if extractor wants t...
Below is the the instruction that describes the task: ### Input: Invoke the extractor on the given extractable, accumulating all the extractions in a list. Args: extractor (Extractor): extractable (extractable): tokenizer: user can pass custom tokenizer if extractor want...
def unseen_videos_reset(self): """Reset the unseen videos counter.""" url = RESET_CAM_ENDPOINT.format(self.unique_id) ret = self._session.query(url).get('success') return ret
Reset the unseen videos counter.
Below is the the instruction that describes the task: ### Input: Reset the unseen videos counter. ### Response: def unseen_videos_reset(self): """Reset the unseen videos counter.""" url = RESET_CAM_ENDPOINT.format(self.unique_id) ret = self._session.query(url).get('success') return ...
async def query_firmware(self): """Query the firmware versions.""" _version = await self.request.get(join_path(self._base_path, "/fwversion")) _fw = _version.get("firmware") if _fw: _main = _fw.get("mainProcessor") if _main: self._main_processor_v...
Query the firmware versions.
Below is the the instruction that describes the task: ### Input: Query the firmware versions. ### Response: async def query_firmware(self): """Query the firmware versions.""" _version = await self.request.get(join_path(self._base_path, "/fwversion")) _fw = _version.get("firmware") ...
def pair_has_contradiction(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> bool: """Check if a pair of nodes has any contradictions in their causal relationships. Assumes both nodes are in the graph. """ relations = {data[RELATION] for data in graph[u][v].values()} return relation_set_has_contrad...
Check if a pair of nodes has any contradictions in their causal relationships. Assumes both nodes are in the graph.
Below is the the instruction that describes the task: ### Input: Check if a pair of nodes has any contradictions in their causal relationships. Assumes both nodes are in the graph. ### Response: def pair_has_contradiction(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> bool: """Check if a pair of nodes ...
def _parse_comma_list(self): """Parse a comma seperated list.""" if self._cur_token['type'] not in self._literals: raise Exception( "Parser failed, _parse_comma_list was called on non-literal" " {} on line {}.".format( repr(self._cur_token[...
Parse a comma seperated list.
Below is the the instruction that describes the task: ### Input: Parse a comma seperated list. ### Response: def _parse_comma_list(self): """Parse a comma seperated list.""" if self._cur_token['type'] not in self._literals: raise Exception( "Parser failed, _parse_comma_l...
def _aspect_preserving_resize(image, resize_min): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the...
Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the resized image.
Below is the the instruction that describes the task: ### Input: Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor ...
def resolve_font(name): """Turns font names into absolute filenames This is case sensitive. The extension should be omitted. For example:: >>> path = resolve_font('NotoSans-Bold') >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts') >>> noto_path = os.path.join(fontdir,...
Turns font names into absolute filenames This is case sensitive. The extension should be omitted. For example:: >>> path = resolve_font('NotoSans-Bold') >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts') >>> noto_path = os.path.join(fontdir, 'NotoSans-Bold.ttf') >...
Below is the the instruction that describes the task: ### Input: Turns font names into absolute filenames This is case sensitive. The extension should be omitted. For example:: >>> path = resolve_font('NotoSans-Bold') >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts') ...
def get_sort_function(order): """ Returns a callable similar to the built-in `cmp`, to be used on objects. Takes a list of dictionaries. In each, 'key' must be a string that is used to get an attribute of the objects to compare, and 'reverse' must be a boolean indicating whether the result should b...
Returns a callable similar to the built-in `cmp`, to be used on objects. Takes a list of dictionaries. In each, 'key' must be a string that is used to get an attribute of the objects to compare, and 'reverse' must be a boolean indicating whether the result should be reversed.
Below is the the instruction that describes the task: ### Input: Returns a callable similar to the built-in `cmp`, to be used on objects. Takes a list of dictionaries. In each, 'key' must be a string that is used to get an attribute of the objects to compare, and 'reverse' must be a boolean indicating ...
def _remove_live_points(self): """Remove the final set of live points if they were previously added to the current set of dead points.""" if self.added_live: self.added_live = False if self.save_samples: del self.saved_id[-self.nlive:] del...
Remove the final set of live points if they were previously added to the current set of dead points.
Below is the the instruction that describes the task: ### Input: Remove the final set of live points if they were previously added to the current set of dead points. ### Response: def _remove_live_points(self): """Remove the final set of live points if they were previously added to the curr...
def get_all_subs_satellites_by_type(self, sat_type, realms): """Get all satellites of the wanted type in this realm recursively :param sat_type: satellite type wanted (scheduler, poller ..) :type sat_type: :param realms: all realms :type realms: list of realm object :ret...
Get all satellites of the wanted type in this realm recursively :param sat_type: satellite type wanted (scheduler, poller ..) :type sat_type: :param realms: all realms :type realms: list of realm object :return: list of satellite in this realm :rtype: list
Below is the the instruction that describes the task: ### Input: Get all satellites of the wanted type in this realm recursively :param sat_type: satellite type wanted (scheduler, poller ..) :type sat_type: :param realms: all realms :type realms: list of realm object :return...
def prt_txt(prt, data_nts, prtfmt=None, nt_fields=None, **kws): """Print list of namedtuples into a table using prtfmt.""" lines = get_lines(data_nts, prtfmt, nt_fields, **kws) if lines: for line in lines: prt.write(line) else: sys.stdout.write(" 0 items. NOT WRITING\n")
Print list of namedtuples into a table using prtfmt.
Below is the the instruction that describes the task: ### Input: Print list of namedtuples into a table using prtfmt. ### Response: def prt_txt(prt, data_nts, prtfmt=None, nt_fields=None, **kws): """Print list of namedtuples into a table using prtfmt.""" lines = get_lines(data_nts, prtfmt, nt_fields, **kws...
def get_led_register_from_name(self, name): """Parse the name for led number :param name: attribute name, like: led_1 """ res = re.match('^led_([0-9]{1,2})$', name) if res is None: raise AttributeError("Unknown attribute: '%s'" % name) led_num = int(res.group...
Parse the name for led number :param name: attribute name, like: led_1
Below is the the instruction that describes the task: ### Input: Parse the name for led number :param name: attribute name, like: led_1 ### Response: def get_led_register_from_name(self, name): """Parse the name for led number :param name: attribute name, like: led_1 """ r...
def _to_ctfile(self): """Convert :class:`~ctfile.ctfile.CTfile` into `CTfile` formatted string. :return: ``CTfile`` formatted string. :rtype: :py:class:`str`. """ output = io.StringIO() for key in self: if key == 'HeaderBlock': for line in se...
Convert :class:`~ctfile.ctfile.CTfile` into `CTfile` formatted string. :return: ``CTfile`` formatted string. :rtype: :py:class:`str`.
Below is the the instruction that describes the task: ### Input: Convert :class:`~ctfile.ctfile.CTfile` into `CTfile` formatted string. :return: ``CTfile`` formatted string. :rtype: :py:class:`str`. ### Response: def _to_ctfile(self): """Convert :class:`~ctfile.ctfile.CTfile` into `CTfile`...
def _validate_channel_definition(self, jp2h, colr): """Validate the channel definition box.""" cdef_lst = [j for (j, box) in enumerate(jp2h.box) if box.box_id == 'cdef'] if len(cdef_lst) > 1: msg = ("Only one channel definition box is allowed in the " ...
Validate the channel definition box.
Below is the the instruction that describes the task: ### Input: Validate the channel definition box. ### Response: def _validate_channel_definition(self, jp2h, colr): """Validate the channel definition box.""" cdef_lst = [j for (j, box) in enumerate(jp2h.box) if box.box_id == '...
def _execute_with_retries(conn, function, **kwargs): ''' Retry if we're rate limited by AWS or blocked by another call. Give up and return error message if resource not found or argument is invalid. conn The connection established by the calling method via _get_conn() function The ...
Retry if we're rate limited by AWS or blocked by another call. Give up and return error message if resource not found or argument is invalid. conn The connection established by the calling method via _get_conn() function The function to call on conn. i.e. create_stream **kwargs ...
Below is the the instruction that describes the task: ### Input: Retry if we're rate limited by AWS or blocked by another call. Give up and return error message if resource not found or argument is invalid. conn The connection established by the calling method via _get_conn() function ...
def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ...
REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` ...
Below is the the instruction that describes the task: ### Input: REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: ...
def call_at(self, when, callback, *args, **kwargs): """Runs the ``callback`` at the absolute time designated by ``when``. ``when`` must be a number using the same reference point as `IOLoop.time`. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note ...
Runs the ``callback`` at the absolute time designated by ``when``. ``when`` must be a number using the same reference point as `IOLoop.time`. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note that unlike the `asyncio` method of the same name, the ...
Below is the the instruction that describes the task: ### Input: Runs the ``callback`` at the absolute time designated by ``when``. ``when`` must be a number using the same reference point as `IOLoop.time`. Returns an opaque handle that may be passed to `remove_timeout` to cancel. ...
def colRegex(self, colName): """ Selects column based on the column name specified as a regex and returns it as :class:`Column`. :param colName: string, column name specified as a regex. >>> df = spark.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["Col1", "Col2"]) >...
Selects column based on the column name specified as a regex and returns it as :class:`Column`. :param colName: string, column name specified as a regex. >>> df = spark.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["Col1", "Col2"]) >>> df.select(df.colRegex("`(Col1)?+.+`")).show() ...
Below is the the instruction that describes the task: ### Input: Selects column based on the column name specified as a regex and returns it as :class:`Column`. :param colName: string, column name specified as a regex. >>> df = spark.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["Col1"...
def floordiv(self, other, axis="columns", level=None, fill_value=None): """Divides this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the divide against this. axis: The axis to divide over. level: The Multilevel inde...
Divides this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the divide against this. axis: The axis to divide over. level: The Multilevel index level to apply divide over. fill_value: The value to fill NaNs with. ...
Below is the the instruction that describes the task: ### Input: Divides this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the divide against this. axis: The axis to divide over. level: The Multilevel index level to appl...
def get_spider_list(self, project_name, version=None): """ Get the list of spiders available in the last (unless overridden) version of some project. :param project_name: the project name :param version: the version of the project to examine :return: a dictionary that spider name...
Get the list of spiders available in the last (unless overridden) version of some project. :param project_name: the project name :param version: the version of the project to examine :return: a dictionary that spider name list example: {"status": "ok", "spiders": ["spider1", "sp...
Below is the the instruction that describes the task: ### Input: Get the list of spiders available in the last (unless overridden) version of some project. :param project_name: the project name :param version: the version of the project to examine :return: a dictionary that spider name list ...
def load_dataframe(self, df_loader_name): """ Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes we may want to just directly load a particular DataFrame. """ logger.debug("loading dataframe: {}".format(df_loader_name)) # Get the DataFrameLo...
Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes we may want to just directly load a particular DataFrame.
Below is the the instruction that describes the task: ### Input: Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes we may want to just directly load a particular DataFrame. ### Response: def load_dataframe(self, df_loader_name): """ Instead of joining a DataF...
def get_dtype_kinds(l): """ Parameters ---------- l : list of arrays Returns ------- a set of kinds that exist in this list of arrays """ typs = set() for arr in l: dtype = arr.dtype if is_categorical_dtype(dtype): typ = 'category' elif is_s...
Parameters ---------- l : list of arrays Returns ------- a set of kinds that exist in this list of arrays
Below is the the instruction that describes the task: ### Input: Parameters ---------- l : list of arrays Returns ------- a set of kinds that exist in this list of arrays ### Response: def get_dtype_kinds(l): """ Parameters ---------- l : list of arrays Returns -------...
def xloss(logits, labels, ignore=None): """ Cross entropy loss """ return F.cross_entropy(logits, Variable(labels), ignore_index=255)
Cross entropy loss
Below is the the instruction that describes the task: ### Input: Cross entropy loss ### Response: def xloss(logits, labels, ignore=None): """ Cross entropy loss """ return F.cross_entropy(logits, Variable(labels), ignore_index=255)
def trade_sell(self, market=None, order_type=None, quantity=None, rate=None, time_in_effect=None, condition_type=None, target=0.0): """ Enter a sell order into the book Endpoint 1.1 NO EQUIVALENT -- see sell_market or sell_limit 2.0 /key/market/tradesell ...
Enter a sell order into the book Endpoint 1.1 NO EQUIVALENT -- see sell_market or sell_limit 2.0 /key/market/tradesell :param market: String literal for the market (ex: BTC-LTC) :type market: str :param order_type: ORDERTYPE_LIMIT = 'LIMIT' or ORDERTYPE_MARKET = 'MARKET'...
Below is the the instruction that describes the task: ### Input: Enter a sell order into the book Endpoint 1.1 NO EQUIVALENT -- see sell_market or sell_limit 2.0 /key/market/tradesell :param market: String literal for the market (ex: BTC-LTC) :type market: str :param...
def lower(option,value): ''' Enforces lower case options and option values where appropriate ''' if type(option) is str: option=option.lower() if type(value) is str: value=value.lower() return (option,value)
Enforces lower case options and option values where appropriate
Below is the the instruction that describes the task: ### Input: Enforces lower case options and option values where appropriate ### Response: def lower(option,value): ''' Enforces lower case options and option values where appropriate ''' if type(option) is str: option=option.lower() i...
def get_cacheable(cache_key, cache_ttl, calculate, recalculate=False): """ Gets the result of a method call, using the given key and TTL as a cache """ if not recalculate: cached = cache.get(cache_key) if cached is not None: return json.loads(cached) calculated = calcula...
Gets the result of a method call, using the given key and TTL as a cache
Below is the the instruction that describes the task: ### Input: Gets the result of a method call, using the given key and TTL as a cache ### Response: def get_cacheable(cache_key, cache_ttl, calculate, recalculate=False): """ Gets the result of a method call, using the given key and TTL as a cache """...
def update_balances(self, recursive=True): """ Calculate tree balance factor """ if self.node: if recursive: if self.node.left: self.node.left.update_balances() if self.node.right: self.node.right.update...
Calculate tree balance factor
Below is the the instruction that describes the task: ### Input: Calculate tree balance factor ### Response: def update_balances(self, recursive=True): """ Calculate tree balance factor """ if self.node: if recursive: if self.node.left: ...
def identifier(self): """ A unique identifier for the path. Returns --------- identifier: (5,) float, unique identifier """ if len(self.polygons_full) != 1: raise TypeError('Identifier only valid for single body') return polygons.polygon_hash(...
A unique identifier for the path. Returns --------- identifier: (5,) float, unique identifier
Below is the the instruction that describes the task: ### Input: A unique identifier for the path. Returns --------- identifier: (5,) float, unique identifier ### Response: def identifier(self): """ A unique identifier for the path. Returns --------- ...
def illegal_doi(self, doi_string): """ DOI string did not match the regex. Determine what the data is. :param doi_string: (str) Malformed DOI string :return: None """ logger_doi_resolver.info("enter illegal_doi") # Ignores empty or irrelevant strings (blank, space...
DOI string did not match the regex. Determine what the data is. :param doi_string: (str) Malformed DOI string :return: None
Below is the the instruction that describes the task: ### Input: DOI string did not match the regex. Determine what the data is. :param doi_string: (str) Malformed DOI string :return: None ### Response: def illegal_doi(self, doi_string): """ DOI string did not match the regex. Deter...
def _note_remote_option(self, option, state): """Record the status of local negotiated Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].remote_option = state
Record the status of local negotiated Telnet options.
Below is the the instruction that describes the task: ### Input: Record the status of local negotiated Telnet options. ### Response: def _note_remote_option(self, option, state): """Record the status of local negotiated Telnet options.""" if not self.telnet_opt_dict.has_key(option): sel...
def fsqrt(q): ''' given a non-negative fraction q, return a pair (a,b) such that q = a * a * b where b is a square-free integer. if q is a perfect square, a is its square root and b is one. ''' if q == 0: return q, 1 if q < 0: raise ValueError('math domain error %s' % q...
given a non-negative fraction q, return a pair (a,b) such that q = a * a * b where b is a square-free integer. if q is a perfect square, a is its square root and b is one.
Below is the the instruction that describes the task: ### Input: given a non-negative fraction q, return a pair (a,b) such that q = a * a * b where b is a square-free integer. if q is a perfect square, a is its square root and b is one. ### Response: def fsqrt(q): ''' given a non-negative frac...
def gmtime_adj_notBefore(self, amount): """ Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None`` """ if not isinstance(amount, int): raise TypeError("amount ...
Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None``
Below is the the instruction that describes the task: ### Input: Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None`` ### Response: def gmtime_adj_notBefore(self, amount): """ Adju...
def _get_conn(opts, profile=None): ''' Establish a connection to etcd ''' if profile is None: profile = opts.get('etcd.returner') path = opts.get('etcd.returner_root', '/salt/return') return salt.utils.etcd_util.get_conn(opts, profile), path
Establish a connection to etcd
Below is the the instruction that describes the task: ### Input: Establish a connection to etcd ### Response: def _get_conn(opts, profile=None): ''' Establish a connection to etcd ''' if profile is None: profile = opts.get('etcd.returner') path = opts.get('etcd.returner_root', '/salt/re...
def __impl_read_chain(self, start, read_sector_f, read_fat_f): """Returns the entire contents of a chain starting at the given sector.""" sector = start check = [ sector ] # keep a list of sectors we've already read buffer = StringIO() while sector != ENDOFCHAIN: buff...
Returns the entire contents of a chain starting at the given sector.
Below is the the instruction that describes the task: ### Input: Returns the entire contents of a chain starting at the given sector. ### Response: def __impl_read_chain(self, start, read_sector_f, read_fat_f): """Returns the entire contents of a chain starting at the given sector.""" sector = star...
def _iterate_fields_cond(self, pkt, val, use_val): """Internal function used by _find_fld_pkt & _find_fld_pkt_val""" # Iterate through the fields for fld, cond in self.flds: if isinstance(cond, tuple): if use_val: if cond[1](pkt, val): ...
Internal function used by _find_fld_pkt & _find_fld_pkt_val
Below is the the instruction that describes the task: ### Input: Internal function used by _find_fld_pkt & _find_fld_pkt_val ### Response: def _iterate_fields_cond(self, pkt, val, use_val): """Internal function used by _find_fld_pkt & _find_fld_pkt_val""" # Iterate through the fields for fl...
def wait_for_success(self, interval=1): """ Wait for instance to complete, and check if the instance is successful. :param interval: time interval to check :return: None :raise: :class:`odps.errors.ODPSError` if the instance failed """ self.wait_for_completion(i...
Wait for instance to complete, and check if the instance is successful. :param interval: time interval to check :return: None :raise: :class:`odps.errors.ODPSError` if the instance failed
Below is the the instruction that describes the task: ### Input: Wait for instance to complete, and check if the instance is successful. :param interval: time interval to check :return: None :raise: :class:`odps.errors.ODPSError` if the instance failed ### Response: def wait_for_success(se...
def do(cmdline=None, runas=None): ''' Execute a python command with pyenv's shims from the user or the system. CLI Example: .. code-block:: bash salt '*' pyenv.do 'gem list bundler' salt '*' pyenv.do 'gem list bundler' deploy ''' path = _pyenv_path(runas) cmd_split = cmdli...
Execute a python command with pyenv's shims from the user or the system. CLI Example: .. code-block:: bash salt '*' pyenv.do 'gem list bundler' salt '*' pyenv.do 'gem list bundler' deploy
Below is the the instruction that describes the task: ### Input: Execute a python command with pyenv's shims from the user or the system. CLI Example: .. code-block:: bash salt '*' pyenv.do 'gem list bundler' salt '*' pyenv.do 'gem list bundler' deploy ### Response: def do(cmdline=None, ...
def _handle_response(response): """Internal helper for handling API responses from the Quoine server. Raises the appropriate exceptions when necessary; otherwise, returns the response. """ if not str(response.status_code).startswith('2'): raise KucoinAPIException(res...
Internal helper for handling API responses from the Quoine server. Raises the appropriate exceptions when necessary; otherwise, returns the response.
Below is the the instruction that describes the task: ### Input: Internal helper for handling API responses from the Quoine server. Raises the appropriate exceptions when necessary; otherwise, returns the response. ### Response: def _handle_response(response): """Internal helper for handlin...
def connect_with_username_and_password(cls, url=None, username=None, password=None): """ Returns an object that makes requests to the API, authenticated with a short-lived token retrieved from username and password. If username or password is n...
Returns an object that makes requests to the API, authenticated with a short-lived token retrieved from username and password. If username or password is not supplied, the method will prompt for a username and/or password to be entered interactively. See the connect method for more det...
Below is the the instruction that describes the task: ### Input: Returns an object that makes requests to the API, authenticated with a short-lived token retrieved from username and password. If username or password is not supplied, the method will prompt for a username and/or password to b...
def read_cache(stream): """Read a cache file from the given stream :return: tuple(version, entries_dict, extension_data, content_sha) * version is the integer version number * entries dict is a dictionary which maps IndexEntry instances to a path at a stage * extension_data is '' or 4 bytes of type ...
Read a cache file from the given stream :return: tuple(version, entries_dict, extension_data, content_sha) * version is the integer version number * entries dict is a dictionary which maps IndexEntry instances to a path at a stage * extension_data is '' or 4 bytes of type + 4 bytes of size + size bytes ...
Below is the the instruction that describes the task: ### Input: Read a cache file from the given stream :return: tuple(version, entries_dict, extension_data, content_sha) * version is the integer version number * entries dict is a dictionary which maps IndexEntry instances to a path at a stage * ex...
def _nucmer_hits_to_assembly_coords(nucmer_hits): '''Input is hits made by self._parse_nucmer_coords_file. Returns dictionary. key = contig name. Value = list of coords that match to the reference gene''' coords = {} for l in nucmer_hits.values(): for hit in l: ...
Input is hits made by self._parse_nucmer_coords_file. Returns dictionary. key = contig name. Value = list of coords that match to the reference gene
Below is the the instruction that describes the task: ### Input: Input is hits made by self._parse_nucmer_coords_file. Returns dictionary. key = contig name. Value = list of coords that match to the reference gene ### Response: def _nucmer_hits_to_assembly_coords(nucmer_hits): '''Inpu...
def encode(self, word, terminator='\0'): r"""Return the Burrows-Wheeler transformed form of a word. Parameters ---------- word : str The word to transform using BWT terminator : str A character added to signal the end of the string Returns ...
r"""Return the Burrows-Wheeler transformed form of a word. Parameters ---------- word : str The word to transform using BWT terminator : str A character added to signal the end of the string Returns ------- str Word encoded by...
Below is the the instruction that describes the task: ### Input: r"""Return the Burrows-Wheeler transformed form of a word. Parameters ---------- word : str The word to transform using BWT terminator : str A character added to signal the end of the string ...
def setup_panel_params(self, coord): """ Calculate the x & y range & breaks information for each panel Parameters ---------- coord : coord Coordinate """ if not self.panel_scales_x: raise PlotnineError('Missing an x scale') if not...
Calculate the x & y range & breaks information for each panel Parameters ---------- coord : coord Coordinate
Below is the the instruction that describes the task: ### Input: Calculate the x & y range & breaks information for each panel Parameters ---------- coord : coord Coordinate ### Response: def setup_panel_params(self, coord): """ Calculate the x & y range & break...
def fastas(self, download=False): """ Dict of filepaths for all fasta files associated with code. Parameters ---------- download : bool If True, downloads the fasta file from the PDB. If False, uses the ampal Protein.fasta property Defaults to False -...
Dict of filepaths for all fasta files associated with code. Parameters ---------- download : bool If True, downloads the fasta file from the PDB. If False, uses the ampal Protein.fasta property Defaults to False - this is definitely the recommended behaviour....
Below is the the instruction that describes the task: ### Input: Dict of filepaths for all fasta files associated with code. Parameters ---------- download : bool If True, downloads the fasta file from the PDB. If False, uses the ampal Protein.fasta property ...
def keyPressEvent( self, event ): """ Overloads the key press event to listen for escape calls to cancel the parts editing. :param event | <QKeyPressEvent> """ if ( self.scrollWidget().isHidden() ): if ( event.key() == Qt.Key_Escape ): ...
Overloads the key press event to listen for escape calls to cancel the parts editing. :param event | <QKeyPressEvent>
Below is the the instruction that describes the task: ### Input: Overloads the key press event to listen for escape calls to cancel the parts editing. :param event | <QKeyPressEvent> ### Response: def keyPressEvent( self, event ): """ Overloads the key press event to l...
def format(self, pattern='{head}{padding}{tail} [{ranges}]'): '''Return string representation as specified by *pattern*. Pattern can be any format accepted by Python's standard format function and will receive the following keyword arguments as context: * *head* - Common leading pa...
Return string representation as specified by *pattern*. Pattern can be any format accepted by Python's standard format function and will receive the following keyword arguments as context: * *head* - Common leading part of the collection. * *tail* - Common trailing part of the ...
Below is the the instruction that describes the task: ### Input: Return string representation as specified by *pattern*. Pattern can be any format accepted by Python's standard format function and will receive the following keyword arguments as context: * *head* - Common leading part o...
def graph(self, ig): """Specify the node and edge data. :param ig: Graph with node and edge attributes. :type ig: NetworkX graph or an IGraph graph. :returns: Plotter. :rtype: Plotter. """ res = copy.copy(self) res._edges = ig res._nodes = None ...
Specify the node and edge data. :param ig: Graph with node and edge attributes. :type ig: NetworkX graph or an IGraph graph. :returns: Plotter. :rtype: Plotter.
Below is the the instruction that describes the task: ### Input: Specify the node and edge data. :param ig: Graph with node and edge attributes. :type ig: NetworkX graph or an IGraph graph. :returns: Plotter. :rtype: Plotter. ### Response: def graph(self, ig): """Specify t...
def pages_siblings_menu(context, page, url='/'): """Get the parent page of the given page and render a nested list of its child pages. Good for rendering a secondary menu. :param page: the page where to start the menu from. :param url: not used anymore. """ lang = context.get('lang', pages_sett...
Get the parent page of the given page and render a nested list of its child pages. Good for rendering a secondary menu. :param page: the page where to start the menu from. :param url: not used anymore.
Below is the the instruction that describes the task: ### Input: Get the parent page of the given page and render a nested list of its child pages. Good for rendering a secondary menu. :param page: the page where to start the menu from. :param url: not used anymore. ### Response: def pages_siblings_me...