code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def check_syntax(self): """Only logs that this URL is unknown.""" super(ItmsServicesUrl, self).check_syntax() if u"url=" not in self.urlparts[3]: self.set_result(_("Missing required url parameter"), valid=False)
Only logs that this URL is unknown.
Below is the the instruction that describes the task: ### Input: Only logs that this URL is unknown. ### Response: def check_syntax(self): """Only logs that this URL is unknown.""" super(ItmsServicesUrl, self).check_syntax() if u"url=" not in self.urlparts[3]: self.set_result(_(...
def get_node_annotation_layers(docgraph): """ WARNING: this is higly inefficient! Fix this via Issue #36. Returns ------- all_layers : set or dict the set of all annotation layers used for annotating nodes in the given graph """ all_layers = set() for node_id, node_a...
WARNING: this is higly inefficient! Fix this via Issue #36. Returns ------- all_layers : set or dict the set of all annotation layers used for annotating nodes in the given graph
Below is the the instruction that describes the task: ### Input: WARNING: this is higly inefficient! Fix this via Issue #36. Returns ------- all_layers : set or dict the set of all annotation layers used for annotating nodes in the given graph ### Response: def get_node_annotation_...
def iter(self, bucket): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Get table and fallbacks table = self.__get_table(bucket) schema = tableschema.Schema(self.describe(bucket)) # Open and close transaction with self.__connection.begin(...
https://github.com/frictionlessdata/tableschema-sql-py#storage
Below is the the instruction that describes the task: ### Input: https://github.com/frictionlessdata/tableschema-sql-py#storage ### Response: def iter(self, bucket): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Get table and fallbacks table = self.__get_t...
def removeUnconnectedSignals(netlist): """ If signal is not driving anything remove it """ toDelete = set() toSearch = netlist.signals while toSearch: _toSearch = set() for sig in toSearch: if not sig.endpoints: try: if sig._inte...
If signal is not driving anything remove it
Below is the the instruction that describes the task: ### Input: If signal is not driving anything remove it ### Response: def removeUnconnectedSignals(netlist): """ If signal is not driving anything remove it """ toDelete = set() toSearch = netlist.signals while toSearch: _toSear...
def send_file(self, filename, status=200): """ Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK) """ ...
Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK)
Below is the the instruction that describes the task: ### Input: Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK) ### Res...
def python_executable(self): """The absolute pathname of the Python executable (a string).""" return self.get(property_name='python_executable', default=sys.executable or os.path.join(self.install_prefix, 'bin', 'python'))
The absolute pathname of the Python executable (a string).
Below is the the instruction that describes the task: ### Input: The absolute pathname of the Python executable (a string). ### Response: def python_executable(self): """The absolute pathname of the Python executable (a string).""" return self.get(property_name='python_executable', ...
def fetch_and_parse(method, uri, params_prefix=None, **params): """Fetch the given uri and return python dictionary with parsed data-types.""" response = fetch(method, uri, params_prefix, **params) return _parse(json.loads(response.text))
Fetch the given uri and return python dictionary with parsed data-types.
Below is the the instruction that describes the task: ### Input: Fetch the given uri and return python dictionary with parsed data-types. ### Response: def fetch_and_parse(method, uri, params_prefix=None, **params): """Fetch the given uri and return python dictionary with parsed data-types.""" response = f...
def get_default_config(self): """ Returns the default collector settings """ config = super(CPUCollector, self).get_default_config() config.update({ 'path': 'cpu', 'percore': 'True', 'xenfix': None, 'simple': 'False', ...
Returns the default collector settings
Below is the the instruction that describes the task: ### Input: Returns the default collector settings ### Response: def get_default_config(self): """ Returns the default collector settings """ config = super(CPUCollector, self).get_default_config() config.update({ ...
def _get_row_within_width(self, row): """Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after it has been processed...
Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after it has been processed according to width exceed policy.
Below is the the instruction that describes the task: ### Input: Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after i...
def update_subnet(self, subnet, name=None): ''' Updates a subnet ''' subnet_id = self._find_subnet_id(subnet) return self.network_conn.update_subnet( subnet=subnet_id, body={'subnet': {'name': name}})
Updates a subnet
Below is the the instruction that describes the task: ### Input: Updates a subnet ### Response: def update_subnet(self, subnet, name=None): ''' Updates a subnet ''' subnet_id = self._find_subnet_id(subnet) return self.network_conn.update_subnet( subnet=subnet_id,...
def do_version(): """Return version details of the running server api""" v = ApiPool.ping.model.Version( name=ApiPool().current_server_name, version=ApiPool().current_server_api.get_version(), container=get_container_version(), ) log.info("/version: " + pprint.pformat(v)) ret...
Return version details of the running server api
Below is the the instruction that describes the task: ### Input: Return version details of the running server api ### Response: def do_version(): """Return version details of the running server api""" v = ApiPool.ping.model.Version( name=ApiPool().current_server_name, version=ApiPool().curr...
def parse_html(infile, xpath): """Filter HTML using XPath.""" if not isinstance(infile, lh.HtmlElement): infile = lh.fromstring(infile) infile = infile.xpath(xpath) if not infile: raise ValueError('XPath {0} returned no results.'.format(xpath)) return infile
Filter HTML using XPath.
Below is the the instruction that describes the task: ### Input: Filter HTML using XPath. ### Response: def parse_html(infile, xpath): """Filter HTML using XPath.""" if not isinstance(infile, lh.HtmlElement): infile = lh.fromstring(infile) infile = infile.xpath(xpath) if not infile: ...
def create_from_xmlfile(cls, xmlfile, extdir=None): """Create a Source object from an XML file. Parameters ---------- xmlfile : str Path to XML file. extdir : str Path to the extended source archive. """ root = ElementTree.ElementTree(fil...
Create a Source object from an XML file. Parameters ---------- xmlfile : str Path to XML file. extdir : str Path to the extended source archive.
Below is the the instruction that describes the task: ### Input: Create a Source object from an XML file. Parameters ---------- xmlfile : str Path to XML file. extdir : str Path to the extended source archive. ### Response: def create_from_xmlfile(cls, xmlf...
def router_del(self, cluster_id, router_id): """remove router from the ShardedCluster""" cluster = self._storage[cluster_id] result = cluster.router_remove(router_id) self._storage[cluster_id] = cluster return result
remove router from the ShardedCluster
Below is the the instruction that describes the task: ### Input: remove router from the ShardedCluster ### Response: def router_del(self, cluster_id, router_id): """remove router from the ShardedCluster""" cluster = self._storage[cluster_id] result = cluster.router_remove(router_id) ...
def _flatten_dict(original_dict): """Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any dicts in the original dict ha...
Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any dicts in the original dict have their keys as prefixes in the ...
Below is the the instruction that describes the task: ### Input: Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any...
def assign_composition_to_repository(self, composition_id, repository_id): """Adds an existing ``Composition`` to a ``Repository``. arg: composition_id (osid.id.Id): the ``Id`` of the ``Composition`` arg: repository_id (osid.id.Id): the ``Id`` of the ``Repo...
Adds an existing ``Composition`` to a ``Repository``. arg: composition_id (osid.id.Id): the ``Id`` of the ``Composition`` arg: repository_id (osid.id.Id): the ``Id`` of the ``Repository`` raise: AlreadyExists - ``composition_id`` already assigned to ...
Below is the the instruction that describes the task: ### Input: Adds an existing ``Composition`` to a ``Repository``. arg: composition_id (osid.id.Id): the ``Id`` of the ``Composition`` arg: repository_id (osid.id.Id): the ``Id`` of the ``Repository`` ...
def start_transport(self): """If a transport object has been defined then connect it now.""" if self.transport: if self.transport.connect(): self.log.debug("Service successfully connected to transport layer") else: raise RuntimeError("Service could...
If a transport object has been defined then connect it now.
Below is the the instruction that describes the task: ### Input: If a transport object has been defined then connect it now. ### Response: def start_transport(self): """If a transport object has been defined then connect it now.""" if self.transport: if self.transport.connect(): ...
def flatten(self, lst): """Turn a list of lists into a list.""" if lst == []: return lst if isinstance(lst[0], list): return self.flatten(lst[0]) + self.flatten(lst[1:]) return lst[:1] + self.flatten(lst[1:])
Turn a list of lists into a list.
Below is the the instruction that describes the task: ### Input: Turn a list of lists into a list. ### Response: def flatten(self, lst): """Turn a list of lists into a list.""" if lst == []: return lst if isinstance(lst[0], list): return self.flatten(lst[0]) + self.f...
def find_threshold_near_density(img, density, low=0, high=255): """Find a threshold where the fraction of pixels above the threshold is closest to density where density is (count of pixels above threshold / count of pixels). The highest threshold closest to the desired density will be returned. ...
Find a threshold where the fraction of pixels above the threshold is closest to density where density is (count of pixels above threshold / count of pixels). The highest threshold closest to the desired density will be returned. Use low and high to exclude undesirable thresholds. :param i...
Below is the the instruction that describes the task: ### Input: Find a threshold where the fraction of pixels above the threshold is closest to density where density is (count of pixels above threshold / count of pixels). The highest threshold closest to the desired density will be returned. ...
def _extract_columns(d, tmp_tso, pc): """ Extract data from one paleoData column :param dict d: Column dictionary :param dict tmp_tso: TSO dictionary with only root items :return dict: Finished TSO """ logger_ts.info("enter extract_columns") for k, v in d.items(): if isinstance(v...
Extract data from one paleoData column :param dict d: Column dictionary :param dict tmp_tso: TSO dictionary with only root items :return dict: Finished TSO
Below is the the instruction that describes the task: ### Input: Extract data from one paleoData column :param dict d: Column dictionary :param dict tmp_tso: TSO dictionary with only root items :return dict: Finished TSO ### Response: def _extract_columns(d, tmp_tso, pc): """ Extract data from ...
def delete_comment(self, msg_data_id, index, user_comment_id): """ 删除评论 """ return self._post( 'comment/delete', data={ 'msg_data_id': msg_data_id, 'index': index, 'user_comment_id': user_comment_id, })
删除评论
Below is the the instruction that describes the task: ### Input: 删除评论 ### Response: def delete_comment(self, msg_data_id, index, user_comment_id): """ 删除评论 """ return self._post( 'comment/delete', data={ 'msg_data_id': msg_data_id, ...
def params(self): """ Return a list of parameters in this task's request. If self.request is already a list, simply return it. If self.request is a raw XML-RPC string, parse it and return the params. """ if isinstance(self.request, list): return unmu...
Return a list of parameters in this task's request. If self.request is already a list, simply return it. If self.request is a raw XML-RPC string, parse it and return the params.
Below is the the instruction that describes the task: ### Input: Return a list of parameters in this task's request. If self.request is already a list, simply return it. If self.request is a raw XML-RPC string, parse it and return the params. ### Response: def params(self): """ ...
def convert(self, request, response, data): """ Performs the desired formatting. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
Performs the desired formatting. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary list returned by the prepa...
Below is the the instruction that describes the task: ### Input: Performs the desired formatting. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data...
def read_upload(up_file, data_model=None): """ take a file that should be ready for upload using the data model, check that all required columns are full, and that all numeric data is in fact numeric. print out warnings for any validation problems return True if there were no problems, otherwise...
take a file that should be ready for upload using the data model, check that all required columns are full, and that all numeric data is in fact numeric. print out warnings for any validation problems return True if there were no problems, otherwise return False
Below is the the instruction that describes the task: ### Input: take a file that should be ready for upload using the data model, check that all required columns are full, and that all numeric data is in fact numeric. print out warnings for any validation problems return True if there were no probl...
def from_table(cls, table, length, prefix=0, flatten=False): """ Extract from the given table a tree for word length, taking only prefixes of prefix length (if greater than 0) into account to compute successors. :param table: the table to extract the tree from; :...
Extract from the given table a tree for word length, taking only prefixes of prefix length (if greater than 0) into account to compute successors. :param table: the table to extract the tree from; :param length: the length of words generated by the extracted tree; ...
Below is the the instruction that describes the task: ### Input: Extract from the given table a tree for word length, taking only prefixes of prefix length (if greater than 0) into account to compute successors. :param table: the table to extract the tree from; :param length...
def set_principal_credit_string(self, credit_string=None): """Sets the principal credit string. :param credit_string: the new credit string :type credit_string: ``string`` :raise: ``InvalidArgument`` -- ``credit_string`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()...
Sets the principal credit string. :param credit_string: the new credit string :type credit_string: ``string`` :raise: ``InvalidArgument`` -- ``credit_string`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true`` :raise: ``NullArgument`` -- ``credit_string`` i...
Below is the the instruction that describes the task: ### Input: Sets the principal credit string. :param credit_string: the new credit string :type credit_string: ``string`` :raise: ``InvalidArgument`` -- ``credit_string`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()`...
def publish_events( self, topic_hostname, events, custom_headers=None, raw=False, **operation_config): """Publishes a batch of events to an Azure Event Grid topic. :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net :type topic_hostn...
Publishes a batch of events to an Azure Event Grid topic. :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net :type topic_hostname: str :param events: An array of events to be published to Event Grid. :type events: list[~azure.eventgrid....
Below is the the instruction that describes the task: ### Input: Publishes a batch of events to an Azure Event Grid topic. :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net :type topic_hostname: str :param events: An array of events to be ...
def findFlippedSNPs(goldFrqFile1, sourceAlleles, outPrefix): """Find flipped SNPs and flip them in the data1.""" goldAlleles = {} with open(goldFrqFile1, "r") as inputFile: headerIndex = None for i, line in enumerate(inputFile): row = createRowFromPlinkSpacedOutput(line) ...
Find flipped SNPs and flip them in the data1.
Below is the the instruction that describes the task: ### Input: Find flipped SNPs and flip them in the data1. ### Response: def findFlippedSNPs(goldFrqFile1, sourceAlleles, outPrefix): """Find flipped SNPs and flip them in the data1.""" goldAlleles = {} with open(goldFrqFile1, "r") as inputFile: ...
def nl2br(self, text): """ Replace \'\n\' with \'<br/>\\n\' """ if isinstance(text, bytes): return text.replace(b'\n', b'<br/>\n') else: return text.replace('\n', '<br/>\n')
Replace \'\n\' with \'<br/>\\n\'
Below is the the instruction that describes the task: ### Input: Replace \'\n\' with \'<br/>\\n\' ### Response: def nl2br(self, text): """ Replace \'\n\' with \'<br/>\\n\' """ if isinstance(text, bytes): return text.replace(b'\n', b'<br/>\n') else: re...
def update_cb(self, context, t, idx, userdata): """A sink property changed, calls request_update""" if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVER: pa_operation_unref( pa_context_get_server_info(context, self._server_info_cb, None)) self....
A sink property changed, calls request_update
Below is the the instruction that describes the task: ### Input: A sink property changed, calls request_update ### Response: def update_cb(self, context, t, idx, userdata): """A sink property changed, calls request_update""" if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVE...
def mcc(tp, tn, fp, fn): """ Matthew's Correlation Coefficient [-1, 1] 0 = you're just guessing :param int tp: number of true positives :param int tn: number of true negatives :param int fp: number of false positives :param int fn: number of false negatives :rtype: float """ ...
Matthew's Correlation Coefficient [-1, 1] 0 = you're just guessing :param int tp: number of true positives :param int tn: number of true negatives :param int fp: number of false positives :param int fn: number of false negatives :rtype: float
Below is the the instruction that describes the task: ### Input: Matthew's Correlation Coefficient [-1, 1] 0 = you're just guessing :param int tp: number of true positives :param int tn: number of true negatives :param int fp: number of false positives :param int fn: number of false ne...
def set_abort_pending(self, newstate): """ Method to set Abort state if something goes wrong during provisioning Method also used to finish provisioning process when all is completed Method: POST """ self.logger.debug("set_abort_pending(" + "{})".format(newstate)) ...
Method to set Abort state if something goes wrong during provisioning Method also used to finish provisioning process when all is completed Method: POST
Below is the the instruction that describes the task: ### Input: Method to set Abort state if something goes wrong during provisioning Method also used to finish provisioning process when all is completed Method: POST ### Response: def set_abort_pending(self, newstate): """ Method t...
def recordings(self): """ Access the recordings :returns: twilio.rest.api.v2010.account.conference.recording.RecordingList :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList """ if self._recordings is None: self._recordings = RecordingLi...
Access the recordings :returns: twilio.rest.api.v2010.account.conference.recording.RecordingList :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList
Below is the the instruction that describes the task: ### Input: Access the recordings :returns: twilio.rest.api.v2010.account.conference.recording.RecordingList :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList ### Response: def recordings(self): """ Access ...
def field_type(field): """ Template filter that returns field class name (in lower case). E.g. if field is CharField then {{ field|field_type }} will return 'charfield'. """ if hasattr(field, 'field') and field.field: return field.field.__class__.__name__.lower() return ''
Template filter that returns field class name (in lower case). E.g. if field is CharField then {{ field|field_type }} will return 'charfield'.
Below is the the instruction that describes the task: ### Input: Template filter that returns field class name (in lower case). E.g. if field is CharField then {{ field|field_type }} will return 'charfield'. ### Response: def field_type(field): """ Template filter that returns field class name (in ...
def remove(self): """ remove this object from Ariane server :return: """ LOGGER.debug("Environment.remove") if self.id is None: return None else: params = { 'id': self.id } args = {'http_operation': '...
remove this object from Ariane server :return:
Below is the the instruction that describes the task: ### Input: remove this object from Ariane server :return: ### Response: def remove(self): """ remove this object from Ariane server :return: """ LOGGER.debug("Environment.remove") if self.id is None: ...
def create_intent(self, workspace_id, intent, description=None, examples=None, **kwargs): """ Create intent. Create a new intent. This operation is limited to 2000 requests per ...
Create intent. Create a new intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The name of the intent. This string must conform to the ...
Below is the the instruction that describes the task: ### Input: Create intent. Create a new intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param s...
def dms2dd(degrees, minutes, seconds, direction): """convert degrees, minutes, seconds to dd :param string direction: one of N S W E """ dd = (degrees + minutes/60.0) + (seconds/3600.0) # 60.0 fraction for python 2+ compatibility return dd * -1 if direction == 'S' or direction == 'W' else ...
convert degrees, minutes, seconds to dd :param string direction: one of N S W E
Below is the the instruction that describes the task: ### Input: convert degrees, minutes, seconds to dd :param string direction: one of N S W E ### Response: def dms2dd(degrees, minutes, seconds, direction): """convert degrees, minutes, seconds to dd :param string direction: one of N S W E """ ...
def add_team(self, team, sync=True): """ add a team to this OS instance. :param team: the team to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the team object on list to be added on next save(). :return: ...
add a team to this OS instance. :param team: the team to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the team object on list to be added on next save(). :return:
Below is the the instruction that describes the task: ### Input: add a team to this OS instance. :param team: the team to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the team object on list to be added on next save(). ...
def tree(obj): """ Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON. """ from .objects import Object if isinstance(obj, (bool, int, float, str, bytes)): return obj elif isinstance(obj, (datetime.date, datetime.time)): return obj...
Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON.
Below is the the instruction that describes the task: ### Input: Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON. ### Response: def tree(obj): """ Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON. "...
def validate_redirect_url(next_url): """ Returns the next_url path if next_url matches allowed hosts. """ if not next_url: return None parts = urlparse(next_url) if parts.netloc: domain, _ = split_domain_port(parts.netloc) allowed_hosts...
Returns the next_url path if next_url matches allowed hosts.
Below is the the instruction that describes the task: ### Input: Returns the next_url path if next_url matches allowed hosts. ### Response: def validate_redirect_url(next_url): """ Returns the next_url path if next_url matches allowed hosts. """ if not next_url: return N...
def _wait_for_new_tasks(self, timeout=0, batch_timeout=0): """ Check activity channel and wait as necessary. This method is also used to slow down the main processing loop to reduce the effects of rapidly sending Redis commands. This method will exit for any of these conditions...
Check activity channel and wait as necessary. This method is also used to slow down the main processing loop to reduce the effects of rapidly sending Redis commands. This method will exit for any of these conditions: 1. _did_work is True, suggests there could be more work pending ...
Below is the the instruction that describes the task: ### Input: Check activity channel and wait as necessary. This method is also used to slow down the main processing loop to reduce the effects of rapidly sending Redis commands. This method will exit for any of these conditions: ...
def spawn_isolated_child(self): """ Fork or launch a new child off the target context. :returns: mitogen.core.Context of the new child. """ return self.get_chain(use_fork=True).call( ansible_mitogen.target.spawn_isolated_child )
Fork or launch a new child off the target context. :returns: mitogen.core.Context of the new child.
Below is the the instruction that describes the task: ### Input: Fork or launch a new child off the target context. :returns: mitogen.core.Context of the new child. ### Response: def spawn_isolated_child(self): """ Fork or launch a new child off the target context. :re...
def mode_computations(self, f_hat, Ki_f, K, Y, likelihood, kern, Y_metadata): """ At the mode, compute the hessian and effective covariance matrix. returns: logZ : approximation to the marginal likelihood woodbury_inv : variable required for calculating the approximation to the...
At the mode, compute the hessian and effective covariance matrix. returns: logZ : approximation to the marginal likelihood woodbury_inv : variable required for calculating the approximation to the covariance matrix dL_dthetaL : array of derivatives (1 x num_kernel_params) ...
Below is the the instruction that describes the task: ### Input: At the mode, compute the hessian and effective covariance matrix. returns: logZ : approximation to the marginal likelihood woodbury_inv : variable required for calculating the approximation to the covariance matrix ...
def lisFichierLexique(self, filepath): """ Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str """ orig = int(filepath.endswith("ext.la")) lignes = lignesFichier(filepath) for ligne in lignes: ...
Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str
Below is the the instruction that describes the task: ### Input: Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str ### Response: def lisFichierLexique(self, filepath): """ Lecture des lemmes, et enregistrement de leurs ...
def register_encoder(self, lookup: Lookup, encoder: Encoder, label: str=None) -> None: """ Registers the given ``encoder`` under the given ``lookup``. A unique string label may be optionally provided that can be used to refer to the registration by name. For more information about argu...
Registers the given ``encoder`` under the given ``lookup``. A unique string label may be optionally provided that can be used to refer to the registration by name. For more information about arguments, refer to :any:`register`.
Below is the the instruction that describes the task: ### Input: Registers the given ``encoder`` under the given ``lookup``. A unique string label may be optionally provided that can be used to refer to the registration by name. For more information about arguments, refer to :any:`register...
def value_error(self, key, bad_value): """Reports a value error using ERROR_MESSAGES dict. key - key to use for ERROR_MESSAGES. bad_value - is passed to format which is called on what key maps to in ERROR_MESSAGES. """ msg = ERROR_MESSAGES[key].format(bad_value) s...
Reports a value error using ERROR_MESSAGES dict. key - key to use for ERROR_MESSAGES. bad_value - is passed to format which is called on what key maps to in ERROR_MESSAGES.
Below is the the instruction that describes the task: ### Input: Reports a value error using ERROR_MESSAGES dict. key - key to use for ERROR_MESSAGES. bad_value - is passed to format which is called on what key maps to in ERROR_MESSAGES. ### Response: def value_error(self, key, bad_value): ...
def _mass(self,R,z=0.,t=0.): """ NAME: _mass PURPOSE: evaluate the mass within R for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height t - time OUTPUT: the mass enclosed HISTOR...
NAME: _mass PURPOSE: evaluate the mass within R for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height t - time OUTPUT: the mass enclosed HISTORY: 2014-04-01 - Written - Erkal (IoA)
Below is the the instruction that describes the task: ### Input: NAME: _mass PURPOSE: evaluate the mass within R for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height t - time OUTPUT: the mass enc...
def remove_user_from_group(self, username, groupname): """Remove a user from a group. :param username: The user to remove from the group. :param groupname: The group that the user will be removed from. """ url = self._options['server'] + '/rest/api/latest/group/user' x =...
Remove a user from a group. :param username: The user to remove from the group. :param groupname: The group that the user will be removed from.
Below is the the instruction that describes the task: ### Input: Remove a user from a group. :param username: The user to remove from the group. :param groupname: The group that the user will be removed from. ### Response: def remove_user_from_group(self, username, groupname): """Remove a ...
def schedule_servicegroup_host_downtime(self, servicegroup, start_time, end_time, fixed, trigger_id, duration, author, comment): """Schedule a host downtime for each host of services in a servicegroup Format of the line that triggers function call:: S...
Schedule a host downtime for each host of services in a servicegroup Format of the line that triggers function call:: SCHEDULE_SERVICEGROUP_HOST_DOWNTIME;<servicegroup_name>;<start_time>;<end_time>;<fixed>; <trigger_id>;<duration>;<author>;<comment> :param servicegroup: servicegroup to...
Below is the the instruction that describes the task: ### Input: Schedule a host downtime for each host of services in a servicegroup Format of the line that triggers function call:: SCHEDULE_SERVICEGROUP_HOST_DOWNTIME;<servicegroup_name>;<start_time>;<end_time>;<fixed>; <trigger_id>;<durat...
def mark_done(task_id): """Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist. """ task = Task.get_by_id(task_id) if task is None: raise ValueError('Task with id %d does not exist' % task_id) task.done = True t...
Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist.
Below is the the instruction that describes the task: ### Input: Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist. ### Response: def mark_done(task_id): """Marks a task as done. Args: task_id: The integer id of...
def _time_shift(self, periods, freq=None): """ Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int ...
Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int Number of periods to shift by. freq : pandas.DateOf...
Below is the the instruction that describes the task: ### Input: Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int ...
def list_role_binding_for_all_namespaces(self, **kwargs): """ list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_role_binding_for_all_namespaces(...
list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_role_binding_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bo...
Below is the the instruction that describes the task: ### Input: list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_role_binding_for_all_namespaces(async_req...
def resolve_incident(self, incident_key, description=None, details=None): """ Causes the referenced incident to enter resolved state. Send a resolve event when the problem that caused the initial trigger has been fixed. """ return self.create_event(descr...
Causes the referenced incident to enter resolved state. Send a resolve event when the problem that caused the initial trigger has been fixed.
Below is the the instruction that describes the task: ### Input: Causes the referenced incident to enter resolved state. Send a resolve event when the problem that caused the initial trigger has been fixed. ### Response: def resolve_incident(self, incident_key, description=...
def _assert_type_bounds_are_not_conflicting(current_type_bound, previous_type_bound, location, match_query): """Ensure that the two bounds either are an exact match, or one of them is None.""" if all((current_type_bound is not None, previous_type_bound is ...
Ensure that the two bounds either are an exact match, or one of them is None.
Below is the the instruction that describes the task: ### Input: Ensure that the two bounds either are an exact match, or one of them is None. ### Response: def _assert_type_bounds_are_not_conflicting(current_type_bound, previous_type_bound, location, match_query): "...
def is_group(self): """True if the message was sent on a group or megagroup.""" if self._broadcast is None and self.chat: self._broadcast = getattr(self.chat, 'broadcast', None) return ( isinstance(self._chat_peer, (types.PeerChat, types.PeerChannel)) and not...
True if the message was sent on a group or megagroup.
Below is the the instruction that describes the task: ### Input: True if the message was sent on a group or megagroup. ### Response: def is_group(self): """True if the message was sent on a group or megagroup.""" if self._broadcast is None and self.chat: self._broadcast = getattr(self.c...
def item_move(self, request, tree_id, item_id, direction): """Moves item up or down by swapping 'sort_order' field values of neighboring items.""" current_item = MODEL_TREE_ITEM_CLASS._default_manager.get(pk=item_id) if direction == 'up': sort_order = 'sort_order' else: ...
Moves item up or down by swapping 'sort_order' field values of neighboring items.
Below is the the instruction that describes the task: ### Input: Moves item up or down by swapping 'sort_order' field values of neighboring items. ### Response: def item_move(self, request, tree_id, item_id, direction): """Moves item up or down by swapping 'sort_order' field values of neighboring items."""...
def DiffDoArrays(self, oldObj, newObj, isElementLinks): """Diff two DataObject arrays""" if len(oldObj) != len(newObj): __Log__.debug('DiffDoArrays: Array lengths do not match %d != %d' % (len(oldObj), len(newObj))) return False for i, j in zip(oldObj, newObj): i...
Diff two DataObject arrays
Below is the the instruction that describes the task: ### Input: Diff two DataObject arrays ### Response: def DiffDoArrays(self, oldObj, newObj, isElementLinks): """Diff two DataObject arrays""" if len(oldObj) != len(newObj): __Log__.debug('DiffDoArrays: Array lengths do not match %d != %d' ...
def search_issues(self, query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None): """Find issues by state and keyword The query can contain any combination of the following supported qualifers: - ``type`` With this qualifier you can res...
Find issues by state and keyword The query can contain any combination of the following supported qualifers: - ``type`` With this qualifier you can restrict the search to issues or pull request only. - ``in`` Qualifies which fields are searched. With this qualifier you ...
Below is the the instruction that describes the task: ### Input: Find issues by state and keyword The query can contain any combination of the following supported qualifers: - ``type`` With this qualifier you can restrict the search to issues or pull request only. - ``in`...
def get_probes_results(self): """Return the results of the RPM probes.""" probes_results = {} probes_results_table = junos_views.junos_rpm_probes_results_table(self.device) probes_results_table.get() probes_results_items = probes_results_table.items() for probe_result i...
Return the results of the RPM probes.
Below is the the instruction that describes the task: ### Input: Return the results of the RPM probes. ### Response: def get_probes_results(self): """Return the results of the RPM probes.""" probes_results = {} probes_results_table = junos_views.junos_rpm_probes_results_table(self.device) ...
def compute_depth(self): """ Recursively computes true depth of the subtree. Should only be needed for debugging. Unless something is wrong, the depth field should reflect the correct depth of the subtree. """ left_depth = self.left_node.compute_depth() if self.left_node ...
Recursively computes true depth of the subtree. Should only be needed for debugging. Unless something is wrong, the depth field should reflect the correct depth of the subtree.
Below is the the instruction that describes the task: ### Input: Recursively computes true depth of the subtree. Should only be needed for debugging. Unless something is wrong, the depth field should reflect the correct depth of the subtree. ### Response: def compute_depth(self): """ ...
def parallel_beam_geometry(space, num_angles=None, det_shape=None): r"""Create default parallel beam geometry from ``space``. This is intended for simple test cases where users do not need the full flexibility of the geometries, but simply want a geometry that works. This default geometry gives a full...
r"""Create default parallel beam geometry from ``space``. This is intended for simple test cases where users do not need the full flexibility of the geometries, but simply want a geometry that works. This default geometry gives a fully sampled sinogram according to the Nyquist criterion, which in gene...
Below is the the instruction that describes the task: ### Input: r"""Create default parallel beam geometry from ``space``. This is intended for simple test cases where users do not need the full flexibility of the geometries, but simply want a geometry that works. This default geometry gives a fully s...
def info(cabdir, header=False): """ prints out help information about a cab """ # First check if cab exists pfile = "{}/parameters.json".format(cabdir) if not os.path.exists(pfile): raise RuntimeError("Cab could not be found at : {}".format(cabdir)) # Get cab info cab_definition = cab.C...
prints out help information about a cab
Below is the the instruction that describes the task: ### Input: prints out help information about a cab ### Response: def info(cabdir, header=False): """ prints out help information about a cab """ # First check if cab exists pfile = "{}/parameters.json".format(cabdir) if not os.path.exists(pfile...
def processEnded(self, status): """ :api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API """ self.cleanup() if status.value.exitCode is None: if self._did_timeout: err = RuntimeError("Timeout waiting for Tor launch.") els...
:api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API
Below is the the instruction that describes the task: ### Input: :api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API ### Response: def processEnded(self, status): """ :api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API """ self.cleanup() ...
def DomainsGet(self, parameters = None, domain_id = -1): """ This method returns the domains of the current user. The list also contains the domains to which the users has not yet been accepted. @param parameters (dictonary) - Dictionary containing the para...
This method returns the domains of the current user. The list also contains the domains to which the users has not yet been accepted. @param parameters (dictonary) - Dictionary containing the parameters of the request. @return (...
Below is the the instruction that describes the task: ### Input: This method returns the domains of the current user. The list also contains the domains to which the users has not yet been accepted. @param parameters (dictonary) - Dictionary containing the parameters of the ...
def contains(self, key): '''Returns whether the object named by `key` exists. First checks ``cache_datastore``. ''' return self.cache_datastore.contains(key) \ or self.child_datastore.contains(key)
Returns whether the object named by `key` exists. First checks ``cache_datastore``.
Below is the the instruction that describes the task: ### Input: Returns whether the object named by `key` exists. First checks ``cache_datastore``. ### Response: def contains(self, key): '''Returns whether the object named by `key` exists. First checks ``cache_datastore``. ''' return sel...
def experiment_list(args): '''get the information of all experiments''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: print('There is no experiment running...') exit(1) update_experiment() experiment_id_list = ...
get the information of all experiments
Below is the the instruction that describes the task: ### Input: get the information of all experiments ### Response: def experiment_list(args): '''get the information of all experiments''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment...
def keywords_special_characters(keywords): """ Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError """ invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n' if any(char in invalid_chars for char in keywords...
Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError
Below is the the instruction that describes the task: ### Input: Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError ### Response: def keywords_special_characters(keywords): """ Confirms that the keywords don't cont...
def team(self): """Team to which the scope is assigned.""" team_dict = self._json_data.get('team') if team_dict and team_dict.get('id'): return self._client.team(id=team_dict.get('id')) else: return None
Team to which the scope is assigned.
Below is the the instruction that describes the task: ### Input: Team to which the scope is assigned. ### Response: def team(self): """Team to which the scope is assigned.""" team_dict = self._json_data.get('team') if team_dict and team_dict.get('id'): return self._client.team(i...
def salt_run(): ''' Execute a salt convenience routine. ''' import salt.cli.run if '' in sys.path: sys.path.remove('') client = salt.cli.run.SaltRun() _install_signal_handlers(client) client.run()
Execute a salt convenience routine.
Below is the the instruction that describes the task: ### Input: Execute a salt convenience routine. ### Response: def salt_run(): ''' Execute a salt convenience routine. ''' import salt.cli.run if '' in sys.path: sys.path.remove('') client = salt.cli.run.SaltRun() _install_sign...
def process(filename=None, url=None, key=None): """ Yeilds DOE CODE records based on provided input sources param: filename (str): Path to a DOE CODE .json file url (str): URL for a DOE CODE server json file key (str): API Key for connecting to DOE CODE server """ if filena...
Yeilds DOE CODE records based on provided input sources param: filename (str): Path to a DOE CODE .json file url (str): URL for a DOE CODE server json file key (str): API Key for connecting to DOE CODE server
Below is the the instruction that describes the task: ### Input: Yeilds DOE CODE records based on provided input sources param: filename (str): Path to a DOE CODE .json file url (str): URL for a DOE CODE server json file key (str): API Key for connecting to DOE CODE server ### Response:...
def play_NoteContainer(self, notecontainer): """Convert a mingus.containers.NoteContainer to the equivalent MIDI events and add it to the track_data. Note.channel and Note.velocity can be set as well. """ if len(notecontainer) <= 1: [self.play_Note(x) for x in noteco...
Convert a mingus.containers.NoteContainer to the equivalent MIDI events and add it to the track_data. Note.channel and Note.velocity can be set as well.
Below is the the instruction that describes the task: ### Input: Convert a mingus.containers.NoteContainer to the equivalent MIDI events and add it to the track_data. Note.channel and Note.velocity can be set as well. ### Response: def play_NoteContainer(self, notecontainer): """Convert a ...
def query_instance(vm_=None, call=None): ''' Query an instance upon creation from the EC2 API ''' if call == 'function': # Technically this function may be called other ways too, but it # definitely cannot be called with --function. raise SaltCloudSystemExit( 'The que...
Query an instance upon creation from the EC2 API
Below is the the instruction that describes the task: ### Input: Query an instance upon creation from the EC2 API ### Response: def query_instance(vm_=None, call=None): ''' Query an instance upon creation from the EC2 API ''' if call == 'function': # Technically this function may be called ...
def generate(env): """Add Builders and construction variables for compaq visual fortran to an Environment.""" fortran.generate(env) env['FORTRAN'] = 'f90' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows...
Add Builders and construction variables for compaq visual fortran to an Environment.
Below is the the instruction that describes the task: ### Input: Add Builders and construction variables for compaq visual fortran to an Environment. ### Response: def generate(env): """Add Builders and construction variables for compaq visual fortran to an Environment.""" fortran.generate(env) env['...
def _should_rotate_log(self, handler): ''' Determine if a log file rotation is necessary ''' if handler['rotate_log']: rotate_time_index = handler.get('rotate_log_index', 'day') try: rotate_time_index = self._decode_time_rotation_index(rotate_time_index) ...
Determine if a log file rotation is necessary
Below is the the instruction that describes the task: ### Input: Determine if a log file rotation is necessary ### Response: def _should_rotate_log(self, handler): ''' Determine if a log file rotation is necessary ''' if handler['rotate_log']: rotate_time_index = handler.get('rotate_log...
def validate(value): """ checks if given value is a valid country codes @param string value @return bool """ if not helpers.has_len(value): return False return COUNTRIES.has_key(str(value).lower())
checks if given value is a valid country codes @param string value @return bool
Below is the the instruction that describes the task: ### Input: checks if given value is a valid country codes @param string value @return bool ### Response: def validate(value): """ checks if given value is a valid country codes @param string value @return bool ...
def pfull_from_ps(bk, pk, ps, pfull_coord): """Compute pressure at full levels from surface pressure.""" return to_pfull_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
Compute pressure at full levels from surface pressure.
Below is the the instruction that describes the task: ### Input: Compute pressure at full levels from surface pressure. ### Response: def pfull_from_ps(bk, pk, ps, pfull_coord): """Compute pressure at full levels from surface pressure.""" return to_pfull_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
def validate(cls, cpf): u""" Válida o CPF. >>> CPF.validate(58119443659) True >>> CPF.validate(58119443650) False >>> CPF.validate('58119443659') True >>> CPF.validate('581.194.436-59') True """ if cpf is None: ...
u""" Válida o CPF. >>> CPF.validate(58119443659) True >>> CPF.validate(58119443650) False >>> CPF.validate('58119443659') True >>> CPF.validate('581.194.436-59') True
Below is the the instruction that describes the task: ### Input: u""" Válida o CPF. >>> CPF.validate(58119443659) True >>> CPF.validate(58119443650) False >>> CPF.validate('58119443659') True >>> CPF.validate('581.194.436-59') True ### Respons...
def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode): """Simple discretization through tanh, flip bottleneck_noise many bits.""" x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck") d0 = tf.stop_gradient(2.0 * tf.to_floa...
Simple discretization through tanh, flip bottleneck_noise many bits.
Below is the the instruction that describes the task: ### Input: Simple discretization through tanh, flip bottleneck_noise many bits. ### Response: def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode): """Simple discretization through tanh...
def unregister(self, entry_point): """Unregister a provider :param str entry_point: provider to unregister (entry point syntax). """ if entry_point not in self.registered_extensions: raise ValueError('Extension not registered') ep = EntryPoint.parse(entry_point) ...
Unregister a provider :param str entry_point: provider to unregister (entry point syntax).
Below is the the instruction that describes the task: ### Input: Unregister a provider :param str entry_point: provider to unregister (entry point syntax). ### Response: def unregister(self, entry_point): """Unregister a provider :param str entry_point: provider to unregister (entry point...
def match_file(patterns, file): """ Matches the file to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns :data:`True` if *file* matched; ...
Matches the file to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns :data:`True` if *file* matched; otherwise, :data:`False`.
Below is the the instruction that describes the task: ### Input: Matches the file to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns :...
def average(): """ generator that holds a rolling average """ count = 0 total = total() i=0 while 1: i = yield ((total.send(i)*1.0)/count if count else 0) count += 1
generator that holds a rolling average
Below is the the instruction that describes the task: ### Input: generator that holds a rolling average ### Response: def average(): """ generator that holds a rolling average """ count = 0 total = total() i=0 while 1: i = yield ((total.send(i)*1.0)/count if count else 0) count ...
def visit_keyword(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of `node` as keyword arg.""" arg = node.arg if arg is None: return f"**{self.visit(node.value)}" else: return f"{arg}={self.visit(node.value)}"
Return representation of `node` as keyword arg.
Below is the the instruction that describes the task: ### Input: Return representation of `node` as keyword arg. ### Response: def visit_keyword(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of `node` as keyword arg.""" arg = node.arg if arg is None: ...
def response_as_single(self, copy=0): """ convert the response map to a single data frame with Multi-Index columns """ arr = [] for sid, frame in self.response.iteritems(): if copy: frame = frame.copy() 'security' not in frame and frame.insert(0, 'security...
convert the response map to a single data frame with Multi-Index columns
Below is the the instruction that describes the task: ### Input: convert the response map to a single data frame with Multi-Index columns ### Response: def response_as_single(self, copy=0): """ convert the response map to a single data frame with Multi-Index columns """ arr = [] for sid, fr...
def relabeled_clone(self, relabels): """Gets a re-labeled clone of this expression.""" return self.__class__( relabels.get(self.alias, self.alias), self.target, self.hstore_key, self.output_field )
Gets a re-labeled clone of this expression.
Below is the the instruction that describes the task: ### Input: Gets a re-labeled clone of this expression. ### Response: def relabeled_clone(self, relabels): """Gets a re-labeled clone of this expression.""" return self.__class__( relabels.get(self.alias, self.alias), sel...
def add_interrupt_callback(self, gpio_id, callback, edge='both', pull_up_down=_GPIO.PUD_OFF, threaded_callback=False, debounce_timeout_ms=None): """ Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='...
Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and `RPIO.PUD_OFF`. If `threaded_callback` is True, the callback will be started insid...
Below is the the instruction that describes the task: ### Input: Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and `RPIO.PUD_OFF`. If `t...
def parseAndSave(option, urlOrPaths, outDir=None, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar, responseMimeType='application/json', metaExtension='_meta.json', services={'meta': '/meta', 'text': '/tika', 'all': '/rmeta'}): ''' Parse the objects a...
Parse the objects and write extracted metadata and/or text in JSON format to matching filename with an extension of '_meta.json'. :param option: :param urlOrPaths: :param outDir: :param serverEndpoint: :param verbose: :param tikaServerJar: :param responseMimeType: :param metaExtensio...
Below is the the instruction that describes the task: ### Input: Parse the objects and write extracted metadata and/or text in JSON format to matching filename with an extension of '_meta.json'. :param option: :param urlOrPaths: :param outDir: :param serverEndpoint: :param verbose: :para...
def comma_replacement(random, population, parents, offspring, args): """Performs "comma" replacement. This function performs "comma" replacement, which means that the entire existing population is replaced by the best population-many elements from the offspring. This function makes the assumpti...
Performs "comma" replacement. This function performs "comma" replacement, which means that the entire existing population is replaced by the best population-many elements from the offspring. This function makes the assumption that the size of the offspring is at least as large as the original ...
Below is the the instruction that describes the task: ### Input: Performs "comma" replacement. This function performs "comma" replacement, which means that the entire existing population is replaced by the best population-many elements from the offspring. This function makes the assumption that...
def show(self): """ Prints the content of this method to stdout. This will print the method signature and the decompiled code. """ args, ret = self.method.get_descriptor()[1:].split(")") if self.code: # We patch the descriptor here and add the registers, if c...
Prints the content of this method to stdout. This will print the method signature and the decompiled code.
Below is the the instruction that describes the task: ### Input: Prints the content of this method to stdout. This will print the method signature and the decompiled code. ### Response: def show(self): """ Prints the content of this method to stdout. This will print the method sig...
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0): ''' Assign a certificate to an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: The web binding that the certificate is being assigned to must already exist. Arg...
Assign a certificate to an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: The web binding that the certificate is being assigned to must already exist. Args: name (str): The thumbprint of the certificate. site (str): The IIS site name. hostheader (str): Th...
Below is the the instruction that describes the task: ### Input: Assign a certificate to an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: The web binding that the certificate is being assigned to must already exist. Args: name (str): The thumbprint of the certificate...
def _detect_notebook() -> bool: """Detect if code is running in a Jupyter Notebook. This isn't 100% correct but seems good enough Returns ------- bool True if it detects this is a notebook, otherwise False. """ try: from IPython import get_ipython from ipykernel im...
Detect if code is running in a Jupyter Notebook. This isn't 100% correct but seems good enough Returns ------- bool True if it detects this is a notebook, otherwise False.
Below is the the instruction that describes the task: ### Input: Detect if code is running in a Jupyter Notebook. This isn't 100% correct but seems good enough Returns ------- bool True if it detects this is a notebook, otherwise False. ### Response: def _detect_notebook() -> bool: ""...
def from_key_bytes(cls, algorithm, key_bytes): """Builds a `Signer` from an algorithm suite and a raw signing key. :param algorithm: Algorithm on which to base signer :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param bytes key_bytes: Raw signing key :rtype: aws_en...
Builds a `Signer` from an algorithm suite and a raw signing key. :param algorithm: Algorithm on which to base signer :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param bytes key_bytes: Raw signing key :rtype: aws_encryption_sdk.internal.crypto.Signer
Below is the the instruction that describes the task: ### Input: Builds a `Signer` from an algorithm suite and a raw signing key. :param algorithm: Algorithm on which to base signer :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param bytes key_bytes: Raw signing key :rt...
def error(self, text): """ Posts an error message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their ...
Posts an error message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right tim...
Below is the the instruction that describes the task: ### Input: Posts an error message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they a...
def save_model(self, model, meta_data=None, index_fields=None): """ model (instance): Model instance. meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for indexing keys in ri...
model (instance): Model instance. meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for indexing keys in riak (with 'bin' or 'int'). [('lorem','bin'),('dolar','int')] :ret...
Below is the the instruction that describes the task: ### Input: model (instance): Model instance. meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for indexing keys in riak (with 'bin' or '...
def update(self, data=None, timeout=-1, force=''): """Updates server profile template. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops wa...
Updates server profile template. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. force: Force the update ...
Below is the the instruction that describes the task: ### Input: Updates server profile template. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just s...
def split_code_at_show(text): """ Split code at plt.show() """ parts = [] is_doctest = contains_doctest(text) part = [] for line in text.split("\n"): if (not is_doctest and line.strip() == 'plt.show()') or \ (is_doctest and line.strip() == '>>> plt.show()'): ...
Split code at plt.show()
Below is the the instruction that describes the task: ### Input: Split code at plt.show() ### Response: def split_code_at_show(text): """ Split code at plt.show() """ parts = [] is_doctest = contains_doctest(text) part = [] for line in text.split("\n"): if (not is_doctest and...
def update_many(cls, filter, update, upsert=False): """ Updates all documents that pass the filter with the update value Will upsert a new document if upsert=True and no document is filtered """ return cls.collection.update_many(filter, update, upsert).raw_result
Updates all documents that pass the filter with the update value Will upsert a new document if upsert=True and no document is filtered
Below is the the instruction that describes the task: ### Input: Updates all documents that pass the filter with the update value Will upsert a new document if upsert=True and no document is filtered ### Response: def update_many(cls, filter, update, upsert=False): """ Updates all documents...
def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for static methods. """ @utility.disk_cache(basename, cls.directory(), method=method) def wrapper(*args, **kwargs): ...
Cache the return value in the correct cache directory. Set 'method' to false for static methods.
Below is the the instruction that describes the task: ### Input: Cache the return value in the correct cache directory. Set 'method' to false for static methods. ### Response: def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct ca...
def get_schema_dir(self, path): """Retrieve the directory containing the given schema. :param path: Schema path, relative to the directory where it was registered. :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema was found in the specified path. ...
Retrieve the directory containing the given schema. :param path: Schema path, relative to the directory where it was registered. :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema was found in the specified path. :returns: The schema directory.
Below is the the instruction that describes the task: ### Input: Retrieve the directory containing the given schema. :param path: Schema path, relative to the directory where it was registered. :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema was found in ...
def center_of_mass(self): """ Calculates the center of mass of the slab """ weights = [s.species.weight for s in self] center_of_mass = np.average(self.frac_coords, weights=weights, axis=0) return center_of_mass
Calculates the center of mass of the slab
Below is the the instruction that describes the task: ### Input: Calculates the center of mass of the slab ### Response: def center_of_mass(self): """ Calculates the center of mass of the slab """ weights = [s.species.weight for s in self] center_of_mass = np.average(self.fr...
def do_speed(self, speed): """ rewind """ if speed: try: self.bot._speed = float(speed) except Exception as e: self.print_response('%s is not a valid framerate' % speed) return self.print_response('Speed: %s ...
rewind
Below is the the instruction that describes the task: ### Input: rewind ### Response: def do_speed(self, speed): """ rewind """ if speed: try: self.bot._speed = float(speed) except Exception as e: self.print_response('%s is not...