code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def views_preview_count(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/views#preview-count" api_path = "/api/v2/views/preview/count.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/views#preview-count
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/views#preview-count ### Response: def views_preview_count(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/views#preview-count" api_path = "/api/v2/views/preview...
async def _on_state_update(self, state_update): """Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance """ # The state update will include some type of notification: notification_type = state_update.WhichOneof('st...
Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance
Below is the the instruction that describes the task: ### Input: Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance ### Response: async def _on_state_update(self, state_update): """Receive a StateUpdate and fan out to Conversations...
def getPlugItObject(hproPk): """Return the plugit object and the baseURI to use if not in standalone mode""" from hprojects.models import HostedProject try: hproject = HostedProject.objects.get(pk=hproPk) except (HostedProject.DoesNotExist, ValueError): try: hproject = Host...
Return the plugit object and the baseURI to use if not in standalone mode
Below is the the instruction that describes the task: ### Input: Return the plugit object and the baseURI to use if not in standalone mode ### Response: def getPlugItObject(hproPk): """Return the plugit object and the baseURI to use if not in standalone mode""" from hprojects.models import HostedProject ...
def attach_usage_plan_to_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None): ''' Attaches given usage plan to each of the apis provided in a list of apiId and stage values .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: ...
Attaches given usage plan to each of the apis provided in a list of apiId and stage values .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage ...
Below is the the instruction that describes the task: ### Input: Attaches given usage plan to each of the apis provided in a list of apiId and stage values .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, whi...
def load_config_json(conf_file): """Banana?""" try: with open(conf_file) as _: try: json_conf = json.load(_) except ValueError as ze_error: error('invalid-config', 'The provided configuration file %s is not valid json.\n' ...
Banana?
Below is the the instruction that describes the task: ### Input: Banana? ### Response: def load_config_json(conf_file): """Banana?""" try: with open(conf_file) as _: try: json_conf = json.load(_) except ValueError as ze_error: error('invalid-c...
def _get_vispy_app_dir(): """Helper to get the default directory for storing vispy data""" # Define default user directory user_dir = os.path.expanduser('~') # Get system app data dir path = None if sys.platform.startswith('win'): path1, path2 = os.getenv('LOCALAPPDATA'), os.getenv('APP...
Helper to get the default directory for storing vispy data
Below is the the instruction that describes the task: ### Input: Helper to get the default directory for storing vispy data ### Response: def _get_vispy_app_dir(): """Helper to get the default directory for storing vispy data""" # Define default user directory user_dir = os.path.expanduser('~') # ...
def init(force): """Initialize registered aliases and mappings.""" click.secho('Creating indexes...', fg='green', bold=True, file=sys.stderr) with click.progressbar( current_search.create(ignore=[400] if force else None), length=current_search.number_of_indexes) as bar: for n...
Initialize registered aliases and mappings.
Below is the the instruction that describes the task: ### Input: Initialize registered aliases and mappings. ### Response: def init(force): """Initialize registered aliases and mappings.""" click.secho('Creating indexes...', fg='green', bold=True, file=sys.stderr) with click.progressbar( cu...
def delete(cls, uuid): """Delete a workflow.""" to_delete = Workflow.query.get(uuid) db.session.delete(to_delete)
Delete a workflow.
Below is the the instruction that describes the task: ### Input: Delete a workflow. ### Response: def delete(cls, uuid): """Delete a workflow.""" to_delete = Workflow.query.get(uuid) db.session.delete(to_delete)
def disasters_sim(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): """Coal mining disasters sampled from the posterior predictive distribution""" return concatenate((pm.rpoisson(early_mean, size=switchpoint), pm.rpoisson( late_mean, size=n - switc...
Coal mining disasters sampled from the posterior predictive distribution
Below is the the instruction that describes the task: ### Input: Coal mining disasters sampled from the posterior predictive distribution ### Response: def disasters_sim(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): """Coal mining disasters sampled fr...
def set_pin(self, newPin: str, oldPin: str = None) -> dict: """ sets a new pin for the home Args: newPin(str): the new pin oldPin(str): optional, if there is currently a pin active it must be given here. Otherwise it will not be possible to set the ...
sets a new pin for the home Args: newPin(str): the new pin oldPin(str): optional, if there is currently a pin active it must be given here. Otherwise it will not be possible to set the new pin Returns: the result of the call
Below is the the instruction that describes the task: ### Input: sets a new pin for the home Args: newPin(str): the new pin oldPin(str): optional, if there is currently a pin active it must be given here. Otherwise it will not be possible to set the new ...
def evaluate(self, x, y, flux, x_0, y_0): """ Evaluate the `GriddedPSFModel` for the input parameters. """ # NOTE: this is needed because the PSF photometry routines input # length-1 values instead of scalars. TODO: fix the photometry # routines. if not np.issca...
Evaluate the `GriddedPSFModel` for the input parameters.
Below is the the instruction that describes the task: ### Input: Evaluate the `GriddedPSFModel` for the input parameters. ### Response: def evaluate(self, x, y, flux, x_0, y_0): """ Evaluate the `GriddedPSFModel` for the input parameters. """ # NOTE: this is needed because the PSF ...
def get_sql_select_all_fields_by_key( table: str, fieldlist: Sequence[str], keyname: str, delims: Tuple[str, str] = ("", "")) -> str: """Returns SQL: SELECT [all fields in the fieldlist] WHERE [keyname] = ? """ return ( "SELECT " + ",".join([delimit(x,...
Returns SQL: SELECT [all fields in the fieldlist] WHERE [keyname] = ?
Below is the the instruction that describes the task: ### Input: Returns SQL: SELECT [all fields in the fieldlist] WHERE [keyname] = ? ### Response: def get_sql_select_all_fields_by_key( table: str, fieldlist: Sequence[str], keyname: str, delims: Tuple[str, str] = ("", "")) ...
def normalise(v, dimN=2): r"""Normalise vectors, corresponding to slices along specified number of initial spatial dimensions of an array, to have unit :math:`\ell_2` norm. The remaining axes enumerate the distinct vectors to be normalised. Parameters ---------- v : array_like Array w...
r"""Normalise vectors, corresponding to slices along specified number of initial spatial dimensions of an array, to have unit :math:`\ell_2` norm. The remaining axes enumerate the distinct vectors to be normalised. Parameters ---------- v : array_like Array with components to be normalise...
Below is the the instruction that describes the task: ### Input: r"""Normalise vectors, corresponding to slices along specified number of initial spatial dimensions of an array, to have unit :math:`\ell_2` norm. The remaining axes enumerate the distinct vectors to be normalised. Parameters ----...
def simhash(self, content): """ Select policies for simhash on the different types of content. """ if content is None: self.hash = -1 return if isinstance(content, str): features = self.tokenizer_func(content, self.keyword_weight_pari) ...
Select policies for simhash on the different types of content.
Below is the the instruction that describes the task: ### Input: Select policies for simhash on the different types of content. ### Response: def simhash(self, content): """ Select policies for simhash on the different types of content. """ if content is None: self.hash ...
def Crowl_Louvar_UFL(atoms): r'''Calculates upper flammability limit, using the Crowl-Louvar [1]_ correlation. Uses molecular formula only. The upper flammability limit of a gas is air is: .. math:: C_mH_xO_y + zO_2 \to mCO_2 + \frac{x}{2}H_2O \text{UFL} = \frac{3.5}{4.76m + 1.19x - 2...
r'''Calculates upper flammability limit, using the Crowl-Louvar [1]_ correlation. Uses molecular formula only. The upper flammability limit of a gas is air is: .. math:: C_mH_xO_y + zO_2 \to mCO_2 + \frac{x}{2}H_2O \text{UFL} = \frac{3.5}{4.76m + 1.19x - 2.38y + 1} Parameters ---...
Below is the the instruction that describes the task: ### Input: r'''Calculates upper flammability limit, using the Crowl-Louvar [1]_ correlation. Uses molecular formula only. The upper flammability limit of a gas is air is: .. math:: C_mH_xO_y + zO_2 \to mCO_2 + \frac{x}{2}H_2O \text...
def update_graderoster(graderoster, requestor): """ Updates the graderoster resource for the passed restclients.GradeRoster model. A new restclients.GradeRoster is returned, representing the document returned from the update request. """ label = graderoster.graderoster_label() url = "{}/{}"....
Updates the graderoster resource for the passed restclients.GradeRoster model. A new restclients.GradeRoster is returned, representing the document returned from the update request.
Below is the the instruction that describes the task: ### Input: Updates the graderoster resource for the passed restclients.GradeRoster model. A new restclients.GradeRoster is returned, representing the document returned from the update request. ### Response: def update_graderoster(graderoster, requestor)...
def _group_chunks_by_entities(self, chunks, entities): """Groups chunks by entities retrieved from NL API Entity Analysis. Args: chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed. entities (:obj:`list` of :obj:`dict`): List of entities. Returns: A chunk list. (:obj:`b...
Groups chunks by entities retrieved from NL API Entity Analysis. Args: chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed. entities (:obj:`list` of :obj:`dict`): List of entities. Returns: A chunk list. (:obj:`budou.chunk.ChunkList`)
Below is the the instruction that describes the task: ### Input: Groups chunks by entities retrieved from NL API Entity Analysis. Args: chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed. entities (:obj:`list` of :obj:`dict`): List of entities. Returns: A chunk list. (...
def points_are_in_a_straight_line( points, tolerance=1e-7 ): """ Check whether a set of points fall on a straight line. Calculates the areas of triangles formed by triplets of the points. Returns False is any of these areas are larger than the tolerance. Args: points (list(np.array)): list ...
Check whether a set of points fall on a straight line. Calculates the areas of triangles formed by triplets of the points. Returns False is any of these areas are larger than the tolerance. Args: points (list(np.array)): list of Cartesian coordinates for each point. tolerance (optional:floa...
Below is the the instruction that describes the task: ### Input: Check whether a set of points fall on a straight line. Calculates the areas of triangles formed by triplets of the points. Returns False is any of these areas are larger than the tolerance. Args: points (list(np.array)): list of C...
def sum_num_dicts(dicts, normalize=False): """Sums the given dicts into a single dict mapping each key to the sum of its mappings in all given dicts. Parameters ---------- dicts : list A list of dict objects mapping each key to an numeric value. normalize : bool, default False I...
Sums the given dicts into a single dict mapping each key to the sum of its mappings in all given dicts. Parameters ---------- dicts : list A list of dict objects mapping each key to an numeric value. normalize : bool, default False Indicated whether to normalize all values by value ...
Below is the the instruction that describes the task: ### Input: Sums the given dicts into a single dict mapping each key to the sum of its mappings in all given dicts. Parameters ---------- dicts : list A list of dict objects mapping each key to an numeric value. normalize : bool, defa...
def _lastWord(self, text): """Move backward to the start of the word at the end of a string. Return the word """ for index, char in enumerate(text[::-1]): if char.isspace() or \ char in ('(', ')'): return text[len(text) - index :] else: ...
Move backward to the start of the word at the end of a string. Return the word
Below is the the instruction that describes the task: ### Input: Move backward to the start of the word at the end of a string. Return the word ### Response: def _lastWord(self, text): """Move backward to the start of the word at the end of a string. Return the word """ for ...
def url_join(base, *args): """ Helper function to join an arbitrary number of url segments together. """ scheme, netloc, path, query, fragment = urlsplit(base) path = path if len(path) else "/" path = posixpath.join(path, *[('%s' % x) for x in args]) return urlunsplit([scheme, netloc, path, ...
Helper function to join an arbitrary number of url segments together.
Below is the the instruction that describes the task: ### Input: Helper function to join an arbitrary number of url segments together. ### Response: def url_join(base, *args): """ Helper function to join an arbitrary number of url segments together. """ scheme, netloc, path, query, fragment = urlsp...
def select_page(self, limit, offset=0, **kwargs): """ :type limit: int :param limit: The max row number for each page :type offset: int :param offset: The starting position of the page :return: """ start = offset while True: result = se...
:type limit: int :param limit: The max row number for each page :type offset: int :param offset: The starting position of the page :return:
Below is the the instruction that describes the task: ### Input: :type limit: int :param limit: The max row number for each page :type offset: int :param offset: The starting position of the page :return: ### Response: def select_page(self, limit, offset=0, **kwargs): """ ...
def _create_page(cls, page, lang, auto_title, cms_app=None, parent=None, namespace=None, site=None, set_home=False): """ Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created ...
Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created title :param cms_app: Apphook Class to be attached to the page :param parent: parent page (None when creating the home page) :param na...
Below is the the instruction that describes the task: ### Input: Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created title :param cms_app: Apphook Class to be attached to the page :param par...
def _ExtractContentSettingsExceptions(self, exceptions_dict, parser_mediator): """Extracts site specific events. Args: exceptions_dict (dict): Permission exceptions data from Preferences file. parser_mediator (ParserMediator): mediates interactions between parsers and other components, su...
Extracts site specific events. Args: exceptions_dict (dict): Permission exceptions data from Preferences file. parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs.
Below is the the instruction that describes the task: ### Input: Extracts site specific events. Args: exceptions_dict (dict): Permission exceptions data from Preferences file. parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and...
def WhatMustIUnderstand(self): '''Return a list of (uri,localname) tuples for all elements in the header that have mustUnderstand set. ''' return [ ( E.namespaceURI, E.localName ) for E in self.header_elements if _find_mu(E) == "1" ]
Return a list of (uri,localname) tuples for all elements in the header that have mustUnderstand set.
Below is the the instruction that describes the task: ### Input: Return a list of (uri,localname) tuples for all elements in the header that have mustUnderstand set. ### Response: def WhatMustIUnderstand(self): '''Return a list of (uri,localname) tuples for all elements in the header that h...
def get_convert_dict(fmt): """Retrieve parse definition from the format string `fmt`.""" convdef = {} for literal_text, field_name, format_spec, conversion in formatter.parse(fmt): if field_name is None: continue # XXX: Do I need to include 'conversion'? convdef[field_nam...
Retrieve parse definition from the format string `fmt`.
Below is the the instruction that describes the task: ### Input: Retrieve parse definition from the format string `fmt`. ### Response: def get_convert_dict(fmt): """Retrieve parse definition from the format string `fmt`.""" convdef = {} for literal_text, field_name, format_spec, conversion in formatter...
def value(self): """ Take last known value as the value """ try: value = self.lastValue except IndexError: value = "NaN" except ValueError: value = "NaN" return value
Take last known value as the value
Below is the the instruction that describes the task: ### Input: Take last known value as the value ### Response: def value(self): """ Take last known value as the value """ try: value = self.lastValue except IndexError: value = "NaN" except V...
def is_correlated(self, threshold=0): """ Compare with a threshold to determine whether two timeseries correlate to each other. :return: a CorrelationResult object if two time series correlate otherwise false. """ return self.correlation_result if self.correlation_result.coeffici...
Compare with a threshold to determine whether two timeseries correlate to each other. :return: a CorrelationResult object if two time series correlate otherwise false.
Below is the the instruction that describes the task: ### Input: Compare with a threshold to determine whether two timeseries correlate to each other. :return: a CorrelationResult object if two time series correlate otherwise false. ### Response: def is_correlated(self, threshold=0): """ Co...
def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG): """Print the message as a banner with a fixed width. Also logs the message (un-bannered) to the given logger at the debug level. Args: msg: The message to print. color: Optional colorama color string to be applied to the message. Y...
Print the message as a banner with a fixed width. Also logs the message (un-bannered) to the given logger at the debug level. Args: msg: The message to print. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any...
Below is the the instruction that describes the task: ### Input: Print the message as a banner with a fixed width. Also logs the message (un-bannered) to the given logger at the debug level. Args: msg: The message to print. color: Optional colorama color string to be applied to the message. You can ...
def _on_axes_updated(self): """Method to run when axes are changed in any way. Propagates updated axes properly. """ # update attrs self.attrs["axes"] = [a.identity.encode() for a in self._axes] # remove old attributes while len(self._current_axis_identities_in_n...
Method to run when axes are changed in any way. Propagates updated axes properly.
Below is the the instruction that describes the task: ### Input: Method to run when axes are changed in any way. Propagates updated axes properly. ### Response: def _on_axes_updated(self): """Method to run when axes are changed in any way. Propagates updated axes properly. """ ...
def domain(domain_name): """ Allow to apply a function f(df: DataFrame) -> DataFrame) on dfs by specifying the key E.g instead of writing: def process_domain1(dfs): df = dfs['domain1'] # actual process dfs['domain1'] = df return dfs You can write:...
Allow to apply a function f(df: DataFrame) -> DataFrame) on dfs by specifying the key E.g instead of writing: def process_domain1(dfs): df = dfs['domain1'] # actual process dfs['domain1'] = df return dfs You can write: @domain('domain1') d...
Below is the the instruction that describes the task: ### Input: Allow to apply a function f(df: DataFrame) -> DataFrame) on dfs by specifying the key E.g instead of writing: def process_domain1(dfs): df = dfs['domain1'] # actual process dfs['domain1'] = df ...
def unwrap(self, value, session=None): ''' Unwrap value using the unwrap function from ``EnumField.item_type``. Since unwrap validation could not happen in is_valid_wrap, it happens in this function.''' self.validate_unwrap(value) value = self.item_type.unwrap(value, sess...
Unwrap value using the unwrap function from ``EnumField.item_type``. Since unwrap validation could not happen in is_valid_wrap, it happens in this function.
Below is the the instruction that describes the task: ### Input: Unwrap value using the unwrap function from ``EnumField.item_type``. Since unwrap validation could not happen in is_valid_wrap, it happens in this function. ### Response: def unwrap(self, value, session=None): ''' Unwr...
def tryAcquire(self, lockID, callback=None, sync=False, timeout=None): """Attempt to acquire lock. :param lockID: unique lock identifier. :type lockID: str :param sync: True - to wait until lock is acquired or failed to acquire. :type sync: bool :param callback: if sync ...
Attempt to acquire lock. :param lockID: unique lock identifier. :type lockID: str :param sync: True - to wait until lock is acquired or failed to acquire. :type sync: bool :param callback: if sync is False - callback will be called with operation result. :type callback: ...
Below is the the instruction that describes the task: ### Input: Attempt to acquire lock. :param lockID: unique lock identifier. :type lockID: str :param sync: True - to wait until lock is acquired or failed to acquire. :type sync: bool :param callback: if sync is False - ca...
def parse_python_assigns(assign_str): """ Parses a string, containing assign statements into a dictionary. .. code-block:: python h5 = katdal.open('123456789.h5') kwargs = parse_python_assigns("spw=3; scans=[1,2];" "targets='bpcal,radec';" ...
Parses a string, containing assign statements into a dictionary. .. code-block:: python h5 = katdal.open('123456789.h5') kwargs = parse_python_assigns("spw=3; scans=[1,2];" "targets='bpcal,radec';" "channels=slice(0,20...
Below is the the instruction that describes the task: ### Input: Parses a string, containing assign statements into a dictionary. .. code-block:: python h5 = katdal.open('123456789.h5') kwargs = parse_python_assigns("spw=3; scans=[1,2];" "targets='bpca...
def stem(self, word): """Perform stemming on an input word.""" if self.stemmer: return unicode_to_ascii(self._stemmer.stem(word)) else: return word
Perform stemming on an input word.
Below is the the instruction that describes the task: ### Input: Perform stemming on an input word. ### Response: def stem(self, word): """Perform stemming on an input word.""" if self.stemmer: return unicode_to_ascii(self._stemmer.stem(word)) else: return word
def update(self, name=None, email=None, blog=None, company=None, location=None, hireable=False, bio=None): """If authenticated as this user, update the information with the information provided in the parameters. :param str name: e.g., 'John Smith', not login name :param ...
If authenticated as this user, update the information with the information provided in the parameters. :param str name: e.g., 'John Smith', not login name :param str email: e.g., 'john.smith@example.com' :param str blog: e.g., 'http://www.example.com/jsmith/blog' :param str comp...
Below is the the instruction that describes the task: ### Input: If authenticated as this user, update the information with the information provided in the parameters. :param str name: e.g., 'John Smith', not login name :param str email: e.g., 'john.smith@example.com' :param str blo...
def deviation(self, series, start, limit, mean): ''' :type start: int :type limit: int :type mean: int :rtype: list() ''' d = [] for x in range(start, limit): d.append(float(series[x] - mean)) return d
:type start: int :type limit: int :type mean: int :rtype: list()
Below is the the instruction that describes the task: ### Input: :type start: int :type limit: int :type mean: int :rtype: list() ### Response: def deviation(self, series, start, limit, mean): ''' :type start: int :type limit: int :type mean: int :rty...
def first_image(self): """Ready-only attribute that provides the value of the first non-none image that's not the thumbnail override field. """ # loop through image fields and grab the first non-none one for model_field in self._meta.fields: if isinstance(model_field,...
Ready-only attribute that provides the value of the first non-none image that's not the thumbnail override field.
Below is the the instruction that describes the task: ### Input: Ready-only attribute that provides the value of the first non-none image that's not the thumbnail override field. ### Response: def first_image(self): """Ready-only attribute that provides the value of the first non-none image that's ...
def results(self): "An iterable of all `(job-id, WorkResult)`s." cur = self._conn.cursor() rows = cur.execute("SELECT * FROM results") for row in rows: yield (row['job_id'], _row_to_work_result(row))
An iterable of all `(job-id, WorkResult)`s.
Below is the the instruction that describes the task: ### Input: An iterable of all `(job-id, WorkResult)`s. ### Response: def results(self): "An iterable of all `(job-id, WorkResult)`s." cur = self._conn.cursor() rows = cur.execute("SELECT * FROM results") for row in rows: ...
def render_POST(self, request): """ Read remoting request from the client. @type request: The HTTP Request. @param request: C{twisted.web.http.Request} """ def handleDecodeError(failure): """ Return HTTP 400 Bad Request. """ ...
Read remoting request from the client. @type request: The HTTP Request. @param request: C{twisted.web.http.Request}
Below is the the instruction that describes the task: ### Input: Read remoting request from the client. @type request: The HTTP Request. @param request: C{twisted.web.http.Request} ### Response: def render_POST(self, request): """ Read remoting request from the client. @ty...
def _fallback_cleanups(self): ''' Fallback cleanup routines, attempting to fix leaked processes, threads, etc. ''' # Add an extra fallback in case a forked process leaks through multiprocessing.active_children() # Cleanup Windows threads if not salt.utils.platfor...
Fallback cleanup routines, attempting to fix leaked processes, threads, etc.
Below is the the instruction that describes the task: ### Input: Fallback cleanup routines, attempting to fix leaked processes, threads, etc. ### Response: def _fallback_cleanups(self): ''' Fallback cleanup routines, attempting to fix leaked processes, threads, etc. ''' # Add an ext...
def unselect(self, rows, status=True, progress=True): "Unselect given rows. Don't show progress if progress=False; don't show status if status=False." before = len(self._selectedRows) for r in (Progress(rows, 'unselecting') if progress else rows): self.unselectRow(r) if statu...
Unselect given rows. Don't show progress if progress=False; don't show status if status=False.
Below is the the instruction that describes the task: ### Input: Unselect given rows. Don't show progress if progress=False; don't show status if status=False. ### Response: def unselect(self, rows, status=True, progress=True): "Unselect given rows. Don't show progress if progress=False; don't show status ...
def handler(self, signum, frame): # pragma: no cover '''Signal handler for this process''' if signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT): self.stop(signum) os._exit(0)
Signal handler for this process
Below is the the instruction that describes the task: ### Input: Signal handler for this process ### Response: def handler(self, signum, frame): # pragma: no cover '''Signal handler for this process''' if signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT): self.stop(signum) ...
def relaxation_operators(p): """ Return the amplitude damping Kraus operators """ k0 = np.array([[1.0, 0.0], [0.0, np.sqrt(1 - p)]]) k1 = np.array([[0.0, np.sqrt(p)], [0.0, 0.0]]) return k0, k1
Return the amplitude damping Kraus operators
Below is the the instruction that describes the task: ### Input: Return the amplitude damping Kraus operators ### Response: def relaxation_operators(p): """ Return the amplitude damping Kraus operators """ k0 = np.array([[1.0, 0.0], [0.0, np.sqrt(1 - p)]]) k1 = np.array([[0.0, np.sqrt(p)], [0.0...
def display_popup(self, message, size_x=None, size_y=None, duration=3, is_input=False, input_size=30, input_value=None): """ Display a centered popup. If is_input is False: Dis...
Display a centered popup. If is_input is False: Display a centered popup with the given message during duration seconds If size_x and size_y: set the popup size else set it automatically Return True if the popup could be displayed If is_input is True: Displ...
Below is the the instruction that describes the task: ### Input: Display a centered popup. If is_input is False: Display a centered popup with the given message during duration seconds If size_x and size_y: set the popup size else set it automatically Return True if the ...
def http_log_graph(self, stream): ''' Build up a graph (nodes and edges from a Bro http.log) ''' print 'Entering http_log_graph...' for row in list(stream): # Skip '-' hosts if (row['id.orig_h'] == '-'): continue # Add the originating host ...
Build up a graph (nodes and edges from a Bro http.log)
Below is the the instruction that describes the task: ### Input: Build up a graph (nodes and edges from a Bro http.log) ### Response: def http_log_graph(self, stream): ''' Build up a graph (nodes and edges from a Bro http.log) ''' print 'Entering http_log_graph...' for row in list(stream): ...
def update(self,o): """Update from another index or index dict""" self.open() try: self._db.update(o._db) except AttributeError: self._db.update(o)
Update from another index or index dict
Below is the the instruction that describes the task: ### Input: Update from another index or index dict ### Response: def update(self,o): """Update from another index or index dict""" self.open() try: self._db.update(o._db) except AttributeError: self._db....
def fsliceafter(astr, sub): """Return the slice after at sub in string astr""" findex = astr.find(sub) return astr[findex + len(sub):]
Return the slice after at sub in string astr
Below is the the instruction that describes the task: ### Input: Return the slice after at sub in string astr ### Response: def fsliceafter(astr, sub): """Return the slice after at sub in string astr""" findex = astr.find(sub) return astr[findex + len(sub):]
def dependency_check(self, task_cls, skip_unresolved=False): """ Check dependency of task for irresolvable conflicts (like task to task mutual dependency) :param task_cls: task to check :param skip_unresolved: flag controls this method behaviour for tasks that could not be found. \ When False, method will rais...
Check dependency of task for irresolvable conflicts (like task to task mutual dependency) :param task_cls: task to check :param skip_unresolved: flag controls this method behaviour for tasks that could not be found. \ When False, method will raise an exception if task tag was set in dependency and the related ta...
Below is the the instruction that describes the task: ### Input: Check dependency of task for irresolvable conflicts (like task to task mutual dependency) :param task_cls: task to check :param skip_unresolved: flag controls this method behaviour for tasks that could not be found. \ When False, method will ra...
def map_or_apply(function, param): """ Map the function on ``param``, or apply it, depending whether ``param`` \ is a list or an item. :param function: The function to apply. :param param: The parameter to feed the function with (list or item). :returns: The computed value or ``None``. ...
Map the function on ``param``, or apply it, depending whether ``param`` \ is a list or an item. :param function: The function to apply. :param param: The parameter to feed the function with (list or item). :returns: The computed value or ``None``.
Below is the the instruction that describes the task: ### Input: Map the function on ``param``, or apply it, depending whether ``param`` \ is a list or an item. :param function: The function to apply. :param param: The parameter to feed the function with (list or item). :returns: The comput...
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.storage.v2015_06_15.models>` * 2016-01-01: :mod:`v2016_01_01.models<azure.mgmt.storage.v2016_01_01.models>` * 2016-12-01: :mod:`v2016_12_01....
Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.storage.v2015_06_15.models>` * 2016-01-01: :mod:`v2016_01_01.models<azure.mgmt.storage.v2016_01_01.models>` * 2016-12-01: :mod:`v2016_12_01.models<azure.mgmt.storage.v2016_12_01.models>` * 2...
Below is the the instruction that describes the task: ### Input: Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.storage.v2015_06_15.models>` * 2016-01-01: :mod:`v2016_01_01.models<azure.mgmt.storage.v2016_01_01.models>` * 2016-12-01: :mod:`v201...
def insert_many(cls, documents): """Insert a list of documents""" from mongoframes.queries import to_refs # Ensure all documents have been converted to frames frames = cls._ensure_frames(documents) # Send insert signal signal('insert').send(cls, frames=frames) ...
Insert a list of documents
Below is the the instruction that describes the task: ### Input: Insert a list of documents ### Response: def insert_many(cls, documents): """Insert a list of documents""" from mongoframes.queries import to_refs # Ensure all documents have been converted to frames frames = cls._ens...
def variants(context, case_id, institute, force, cancer, cancer_research, sv, sv_research, snv, snv_research, str_clinical, chrom, start, end, hgnc_id, hgnc_symbol, rank_treshold): """Upload variants to a case Note that the files has to be linked with the case, if they ...
Upload variants to a case Note that the files has to be linked with the case, if they are not use 'scout update case'.
Below is the the instruction that describes the task: ### Input: Upload variants to a case Note that the files has to be linked with the case, if they are not use 'scout update case'. ### Response: def variants(context, case_id, institute, force, cancer, cancer_research, sv, sv_rese...
def register(self, mimetype, processor): """Register passed `processor` for passed `mimetype`.""" if mimetype not in self or processor not in self[mimetype]: self.setdefault(mimetype, []).append(processor)
Register passed `processor` for passed `mimetype`.
Below is the the instruction that describes the task: ### Input: Register passed `processor` for passed `mimetype`. ### Response: def register(self, mimetype, processor): """Register passed `processor` for passed `mimetype`.""" if mimetype not in self or processor not in self[mimetype]: ...
def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. ...
Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF].
Below is the the instruction that describes the task: ### Input: Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex num...
def cmd(send, msg, args): """Gives help. Syntax: {command} [command] """ cmdchar = args['config']['core']['cmdchar'] if msg: if msg.startswith(cmdchar): msg = msg[len(cmdchar):] if len(msg.split()) > 1: send("One argument only") elif not command_regi...
Gives help. Syntax: {command} [command]
Below is the the instruction that describes the task: ### Input: Gives help. Syntax: {command} [command] ### Response: def cmd(send, msg, args): """Gives help. Syntax: {command} [command] """ cmdchar = args['config']['core']['cmdchar'] if msg: if msg.startswith(cmdchar): ...
def add_or_update(user_id, app_id, value): ''' Editing evaluation. ''' rec = MEvaluation.get_by_signature(user_id, app_id) if rec: entry = TabEvaluation.update( value=value, ).where(TabEvaluation.uid == rec.uid) entry.execute() ...
Editing evaluation.
Below is the the instruction that describes the task: ### Input: Editing evaluation. ### Response: def add_or_update(user_id, app_id, value): ''' Editing evaluation. ''' rec = MEvaluation.get_by_signature(user_id, app_id) if rec: entry = TabEvaluation.update( ...
def to_str(self, delimiter='|', null='NULL'): """ Sets the current encoder output to Python `str` and returns a row iterator. :param str null: The string representation of null values :param str delimiter: The string delimiting values in the output string :r...
Sets the current encoder output to Python `str` and returns a row iterator. :param str null: The string representation of null values :param str delimiter: The string delimiting values in the output string :rtype: iterator (yields ``str``)
Below is the the instruction that describes the task: ### Input: Sets the current encoder output to Python `str` and returns a row iterator. :param str null: The string representation of null values :param str delimiter: The string delimiting values in the output string ...
def add_elasticache_node(self, node, cluster, region): ''' Adds an ElastiCache node to the inventory and index, as long as it is addressable ''' # Only want available nodes unless all_elasticache_nodes is True if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available':...
Adds an ElastiCache node to the inventory and index, as long as it is addressable
Below is the the instruction that describes the task: ### Input: Adds an ElastiCache node to the inventory and index, as long as it is addressable ### Response: def add_elasticache_node(self, node, cluster, region): ''' Adds an ElastiCache node to the inventory and index, as long as it is a...
def get_area_dates(bbox, date_interval, maxcc=None): """ Get list of times of existing images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(str) :...
Get list of times of existing images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(str) :param maxcc: filter images by maximum percentage of cloud cov...
Below is the the instruction that describes the task: ### Input: Get list of times of existing images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(st...
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10): """This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are ...
This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets{?asset_code,asset_issuer,cursor,limit,order} <https://www.st...
Below is the the instruction that describes the task: ### Input: This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets...
def message_handler(stream, type_, from_, cb): """ Context manager to temporarily register a callback to handle messages on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Message type to listen for, or :data:`...
Context manager to temporarily register a callback to handle messages on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Message type to listen for, or :data:`None` for a wildcard match. :type typ...
Below is the the instruction that describes the task: ### Input: Context manager to temporarily register a callback to handle messages on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Message type to listen for, ...
def initial_key_to_master_key(initial_key): """ initial_key: a hex string of length 32 """ b = initial_key.encode("utf8") orig_input = b for i in range(100000): b = hashlib.sha256(b + orig_input).digest() return from_bytes_32(b)
initial_key: a hex string of length 32
Below is the the instruction that describes the task: ### Input: initial_key: a hex string of length 32 ### Response: def initial_key_to_master_key(initial_key): """ initial_key: a hex string of length 32 """ b = initial_key.encode("utf8") orig_input = b for i in range(10000...
def t_string_NGRAPH(t): r"\\[ '.:][ '.:]" global __STRING P = {' ': 0, "'": 2, '.': 8, ':': 10} N = {' ': 0, "'": 1, '.': 4, ':': 5} __STRING += chr(128 + P[t.value[1]] + N[t.value[2]])
r"\\[ '.:][ '.:]
Below is the the instruction that describes the task: ### Input: r"\\[ '.:][ '.:] ### Response: def t_string_NGRAPH(t): r"\\[ '.:][ '.:]" global __STRING P = {' ': 0, "'": 2, '.': 8, ':': 10} N = {' ': 0, "'": 1, '.': 4, ':': 5} __STRING += chr(128 + P[t.value[1]] + N[t.value[2]])
def create_index(self, cardinality): """ Create an index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality to create a index for. """ DatabaseConnector.create_index(self, cardinality) query = "C...
Create an index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality to create a index for.
Below is the the instruction that describes the task: ### Input: Create an index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality to create a index for. ### Response: def create_index(self, cardinality): """ Creat...
def aggregate_daily(image_coll, start_date=None, end_date=None, agg_type='mean'): """Aggregate images by day without using joins The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- image...
Aggregate images by day without using joins The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- image_coll : ee.ImageCollection Input image collection. start_date : date, number, string, optional ...
Below is the the instruction that describes the task: ### Input: Aggregate images by day without using joins The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- image_coll : ee.ImageCollection Input...
def _get_best_subset(self, ritz): '''Return candidate set with smallest goal functional.''' # (c,\omega(c)) for all considered subsets c overall_evaluations = {} def evaluate(_subset, _evaluations): try: _evaluations[_subset] = \ self.sub...
Return candidate set with smallest goal functional.
Below is the the instruction that describes the task: ### Input: Return candidate set with smallest goal functional. ### Response: def _get_best_subset(self, ritz): '''Return candidate set with smallest goal functional.''' # (c,\omega(c)) for all considered subsets c overall_evaluations = ...
def dump(self, zone, output_dir, lenient, split, source, *sources): ''' Dump zone data from the specified source ''' self.log.info('dump: zone=%s, sources=%s', zone, sources) # We broke out source to force at least one to be passed, add it to any # others we got. ...
Dump zone data from the specified source
Below is the the instruction that describes the task: ### Input: Dump zone data from the specified source ### Response: def dump(self, zone, output_dir, lenient, split, source, *sources): ''' Dump zone data from the specified source ''' self.log.info('dump: zone=%s, sources=%s', zon...
def JR(self,**kwargs): """ NAME: JR PURPOSE: Calculate the radial action INPUT: fixed_quad= (False) if True, use n=10 fixed_quad +scipy.integrate.quad keywords OUTPUT: J_R(R,vT,vT)/ro/vc + estimate of the error (nan for fixed...
NAME: JR PURPOSE: Calculate the radial action INPUT: fixed_quad= (False) if True, use n=10 fixed_quad +scipy.integrate.quad keywords OUTPUT: J_R(R,vT,vT)/ro/vc + estimate of the error (nan for fixed_quad) HISTORY: 2012-11-...
Below is the the instruction that describes the task: ### Input: NAME: JR PURPOSE: Calculate the radial action INPUT: fixed_quad= (False) if True, use n=10 fixed_quad +scipy.integrate.quad keywords OUTPUT: J_R(R,vT,vT)/ro/vc + estimate o...
def process(self): """Construct and start a new File hunt. Returns: The newly created GRR hunt object. Raises: RuntimeError: if no items specified for collection. """ print('Hunt to collect {0:d} items'.format(len(self.file_path_list))) print('Files to be collected: {0!s}'.format(s...
Construct and start a new File hunt. Returns: The newly created GRR hunt object. Raises: RuntimeError: if no items specified for collection.
Below is the the instruction that describes the task: ### Input: Construct and start a new File hunt. Returns: The newly created GRR hunt object. Raises: RuntimeError: if no items specified for collection. ### Response: def process(self): """Construct and start a new File hunt. Retur...
def _get_individual_image(self, run, tag, index, sample): """ Returns the actual image bytes for a given image. Args: run: The name of the run the image belongs to. tag: The name of the tag the images belongs to. index: The index of the image in the current reservoir. sample: The ze...
Returns the actual image bytes for a given image. Args: run: The name of the run the image belongs to. tag: The name of the tag the images belongs to. index: The index of the image in the current reservoir. sample: The zero-indexed sample of the image to retrieve (for example, setti...
Below is the the instruction that describes the task: ### Input: Returns the actual image bytes for a given image. Args: run: The name of the run the image belongs to. tag: The name of the tag the images belongs to. index: The index of the image in the current reservoir. sample: The zer...
def trimmed(self, pred=trimmed_pred_default): """Trim a ParseTree. A node is trimmed if pred(node) returns True. """ new_children = [] for child in self.children: if isinstance(child, ParseNode): new_child = child.trimmed(pred) else: new_child = child if not pred...
Trim a ParseTree. A node is trimmed if pred(node) returns True.
Below is the the instruction that describes the task: ### Input: Trim a ParseTree. A node is trimmed if pred(node) returns True. ### Response: def trimmed(self, pred=trimmed_pred_default): """Trim a ParseTree. A node is trimmed if pred(node) returns True. """ new_children = [] for child ...
def StartingKey(self, evt): """ If the editor is enabled by pressing keys on the grid, this will be called to let the editor do something about that first key if desired. """ key = evt.GetKeyCode() ch = None if key in [ wx.WXK_NUMPAD0, wx.WXK_NUMP...
If the editor is enabled by pressing keys on the grid, this will be called to let the editor do something about that first key if desired.
Below is the the instruction that describes the task: ### Input: If the editor is enabled by pressing keys on the grid, this will be called to let the editor do something about that first key if desired. ### Response: def StartingKey(self, evt): """ If the editor is enabled by pressing keys...
def p_iteration_statement_6(self, p): """ iteration_statement \ : FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement """ vardecl = self.asttypes.VarDeclNoIn( identifier=p[4], initializer=p[5]) vardecl.setpos(p, 3) p[0] = self.asttype...
iteration_statement \ : FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement
Below is the the instruction that describes the task: ### Input: iteration_statement \ : FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement ### Response: def p_iteration_statement_6(self, p): """ iteration_statement \ : FOR LPAREN VAR identifier initializer_noin...
def asd(result, reference, voxelspacing=None, connectivity=1): """ Average surface distance metric. Computes the average surface distance (ASD) between the binary objects in two images. Parameters ---------- result : array_like Input data containing objects. Can be any type but...
Average surface distance metric. Computes the average surface distance (ASD) between the binary objects in two images. Parameters ---------- result : array_like Input data containing objects. Can be any type but will be converted into binary: background where 0, object everywhe...
Below is the the instruction that describes the task: ### Input: Average surface distance metric. Computes the average surface distance (ASD) between the binary objects in two images. Parameters ---------- result : array_like Input data containing objects. Can be any type but will ...
def write(self, pack_uri, blob): """ Write *blob* to this zip package with the membername corresponding to *pack_uri*. """ self._zipf.writestr(pack_uri.membername, blob)
Write *blob* to this zip package with the membername corresponding to *pack_uri*.
Below is the the instruction that describes the task: ### Input: Write *blob* to this zip package with the membername corresponding to *pack_uri*. ### Response: def write(self, pack_uri, blob): """ Write *blob* to this zip package with the membername corresponding to *pack_uri*. ...
def place_project_bid(session, project_id, bidder_id, description, amount, period, milestone_percentage): """ Place a bid on a project """ bid_data = { 'project_id': project_id, 'bidder_id': bidder_id, 'description': description, 'amount': amount, ...
Place a bid on a project
Below is the the instruction that describes the task: ### Input: Place a bid on a project ### Response: def place_project_bid(session, project_id, bidder_id, description, amount, period, milestone_percentage): """ Place a bid on a project """ bid_data = { 'project_id':...
def transfer(self, new_region_slug): """ Transfer the image """ return self.get_data( "images/%s/actions/" % self.id, type=POST, params={"type": "transfer", "region": new_region_slug} )
Transfer the image
Below is the the instruction that describes the task: ### Input: Transfer the image ### Response: def transfer(self, new_region_slug): """ Transfer the image """ return self.get_data( "images/%s/actions/" % self.id, type=POST, params={"type": ...
def project_variant_forward(self, c_variant): """ project c_variant on the source transcript onto the destination transcript :param c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the source transcript :returns: c_variant: an :class:`hgvs.sequencevariant.SequenceVa...
project c_variant on the source transcript onto the destination transcript :param c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the source transcript :returns: c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the destination transcript
Below is the the instruction that describes the task: ### Input: project c_variant on the source transcript onto the destination transcript :param c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the source transcript :returns: c_variant: an :class:`hgvs.sequencevariant.Sequenc...
def save_data(self, trigger_id, **data): """ used to save data to the service but first of all make some work about the data to find and the data to convert :param trigger_id: trigger ID from which to save data :param data: the data to chec...
used to save data to the service but first of all make some work about the data to find and the data to convert :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int ...
Below is the the instruction that describes the task: ### Input: used to save data to the service but first of all make some work about the data to find and the data to convert :param trigger_id: trigger ID from which to save data :param data: the data to ...
def create_analysis(self, config): """ Create Analysis and save in Naarad from config :param config: :return: """ self._default_test_id += 1 self._analyses[self._default_test_id] = _Analysis(ts_start=None, config=config, test_id=self._default_test_id)
Create Analysis and save in Naarad from config :param config: :return:
Below is the the instruction that describes the task: ### Input: Create Analysis and save in Naarad from config :param config: :return: ### Response: def create_analysis(self, config): """ Create Analysis and save in Naarad from config :param config: :return: """ self._default_test_...
def acquire(self, **kwargs): """ Download the file and return its path Returns ------- str or None The path of the file in BatchUp's temporary directory or None if the download failed. """ return config.download_data(self.temp_filename, se...
Download the file and return its path Returns ------- str or None The path of the file in BatchUp's temporary directory or None if the download failed.
Below is the the instruction that describes the task: ### Input: Download the file and return its path Returns ------- str or None The path of the file in BatchUp's temporary directory or None if the download failed. ### Response: def acquire(self, **kwargs): ...
def get_cohesive_energy(self, material_id, per_atom=False): """ Gets the cohesive for a material (eV per formula unit). Cohesive energy is defined as the difference between the bulk energy and the sum of total DFT energy of isolated atoms for atom elements in the bulk. Ar...
Gets the cohesive for a material (eV per formula unit). Cohesive energy is defined as the difference between the bulk energy and the sum of total DFT energy of isolated atoms for atom elements in the bulk. Args: material_id (str): Materials Project material_id, e.g. 'mp-123'....
Below is the the instruction that describes the task: ### Input: Gets the cohesive for a material (eV per formula unit). Cohesive energy is defined as the difference between the bulk energy and the sum of total DFT energy of isolated atoms for atom elements in the bulk. Args: ...
def define_attribute(self, name, atype, data=None): """ Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data. """ ...
Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data.
Below is the the instruction that describes the task: ### Input: Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data. ### Response: def defi...
def get_default_net_device(): """ Find the device where the default route is. """ with open('/proc/net/route') as fh: for line in fh: iface, dest, _ = line.split(None, 2) if dest == '00000000': return iface return None
Find the device where the default route is.
Below is the the instruction that describes the task: ### Input: Find the device where the default route is. ### Response: def get_default_net_device(): """ Find the device where the default route is. """ with open('/proc/net/route') as fh: for line in fh: iface, dest, _ = line.split(No...
def threads_bt(self): """Display thread backtraces.""" import threading import traceback threads = {} for thread in threading.enumerate(): frames = sys._current_frames().get(thread.ident) if frames: stack = traceback.format_stack(frames) ...
Display thread backtraces.
Below is the the instruction that describes the task: ### Input: Display thread backtraces. ### Response: def threads_bt(self): """Display thread backtraces.""" import threading import traceback threads = {} for thread in threading.enumerate(): frames = sys._cur...
def create_user(app, appbuilder, role, username, firstname, lastname, email, password): """ Create a user """ _appbuilder = import_application(app, appbuilder) role_object = _appbuilder.sm.find_role(role) user = _appbuilder.sm.add_user( username, firstname, lastname, email, role_obje...
Create a user
Below is the the instruction that describes the task: ### Input: Create a user ### Response: def create_user(app, appbuilder, role, username, firstname, lastname, email, password): """ Create a user """ _appbuilder = import_application(app, appbuilder) role_object = _appbuilder.sm.find_role...
def insert_entity(self, table_name, entity, timeout=None): ''' Inserts a new entity into the table. Throws if an entity with the same PartitionKey and RowKey already exists. When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system p...
Inserts a new entity into the table. Throws if an entity with the same PartitionKey and RowKey already exists. When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. Together, these properties form the primary key and must be...
Below is the the instruction that describes the task: ### Input: Inserts a new entity into the table. Throws if an entity with the same PartitionKey and RowKey already exists. When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties....
def _insert_data(self, connection, name, value, timestamp, interval, config): '''Helper to insert data into cql.''' cursor = connection.cursor() try: stmt = self._insert_stmt(name, value, timestamp, interval, config) if stmt: cursor.execute(stmt) finally: cursor.close()
Helper to insert data into cql.
Below is the the instruction that describes the task: ### Input: Helper to insert data into cql. ### Response: def _insert_data(self, connection, name, value, timestamp, interval, config): '''Helper to insert data into cql.''' cursor = connection.cursor() try: stmt = self._insert_stmt(name, value...
def translate(self, tx, ty): """Applies a translation by :obj:`tx`, :obj:`ty` to the transformation in this matrix. The effect of the new transformation is to first translate the coordinates by :obj:`tx` and :obj:`ty`, then apply the original transformation to the coordinates. ...
Applies a translation by :obj:`tx`, :obj:`ty` to the transformation in this matrix. The effect of the new transformation is to first translate the coordinates by :obj:`tx` and :obj:`ty`, then apply the original transformation to the coordinates. .. note:: This chang...
Below is the the instruction that describes the task: ### Input: Applies a translation by :obj:`tx`, :obj:`ty` to the transformation in this matrix. The effect of the new transformation is to first translate the coordinates by :obj:`tx` and :obj:`ty`, then apply the original transfo...
def first(self, default=None, as_dict=False, as_ordereddict=False): """Returns a single record for the RecordCollection, or `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.""" # Try to get a record, or return/raise default. ...
Returns a single record for the RecordCollection, or `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.
Below is the the instruction that describes the task: ### Input: Returns a single record for the RecordCollection, or `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it. ### Response: def first(self, default=None, as_dict=False, as_ordereddict=Fal...
def elasprep(self): """ dx4, dy4, dx2dy2, D = elasprep(dx,dy,Te,E=1E11,nu=0.25) Defines the variables that are required to create the 2D finite difference solution coefficient matrix """ if self.Method != 'SAS_NG': self.dx4 = self.dx**4 self.dy4 = self.dy**4 self.dx2...
dx4, dy4, dx2dy2, D = elasprep(dx,dy,Te,E=1E11,nu=0.25) Defines the variables that are required to create the 2D finite difference solution coefficient matrix
Below is the the instruction that describes the task: ### Input: dx4, dy4, dx2dy2, D = elasprep(dx,dy,Te,E=1E11,nu=0.25) Defines the variables that are required to create the 2D finite difference solution coefficient matrix ### Response: def elasprep(self): """ dx4, dy4, dx2dy2, D = elasprep(...
def toxml(self): """ Exports this object into a LEMS XML object """ return '<DerivedVariable name="{0}"'.format(self.name) +\ (' dimension="{0}"'.format(self.dimension) if self.dimension else '') +\ (' exposure="{0}"'.format(self.exposure) if self.exposure else '') +...
Exports this object into a LEMS XML object
Below is the the instruction that describes the task: ### Input: Exports this object into a LEMS XML object ### Response: def toxml(self): """ Exports this object into a LEMS XML object """ return '<DerivedVariable name="{0}"'.format(self.name) +\ (' dimension="{0}"'.form...
def transfer(self, from_acct: Account, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to call the Transfer method in ope4 that transfer an amount of tokens from one account to another account. :pa...
This interface is used to call the Transfer method in ope4 that transfer an amount of tokens from one account to another account. :param from_acct: an Account class that send the oep4 token. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: an int...
Below is the the instruction that describes the task: ### Input: This interface is used to call the Transfer method in ope4 that transfer an amount of tokens from one account to another account. :param from_acct: an Account class that send the oep4 token. :param b58_to_address: a base58 enc...
def _expand_spatial_bounds_to_fit_axes(bounds, ax_width, ax_height): """ Parameters ---------- bounds: dict ax_width: float ax_height: float Returns ------- spatial_bounds """ b = bounds height_meters = util.wgs84_distance(b['lat_min'], b['lon_min'], b['lat_max'], b['lon...
Parameters ---------- bounds: dict ax_width: float ax_height: float Returns ------- spatial_bounds
Below is the the instruction that describes the task: ### Input: Parameters ---------- bounds: dict ax_width: float ax_height: float Returns ------- spatial_bounds ### Response: def _expand_spatial_bounds_to_fit_axes(bounds, ax_width, ax_height): """ Parameters ---------- ...
def radius_cmp(a, b, offsets): '''return +1 or -1 for for sorting''' diff = radius(a, offsets) - radius(b, offsets) if diff > 0: return 1 if diff < 0: return -1 return 0
return +1 or -1 for for sorting
Below is the the instruction that describes the task: ### Input: return +1 or -1 for for sorting ### Response: def radius_cmp(a, b, offsets): '''return +1 or -1 for for sorting''' diff = radius(a, offsets) - radius(b, offsets) if diff > 0: return 1 if diff < 0: return -1 return ...
def regenerate_thumbs(self): """ Handle re-generating the thumbnails. All this involves is reading the original file, then saving the same exact thing. Kind of annoying, but it's simple. """ Model = self.model instances = Model.objects.all() num_instances ...
Handle re-generating the thumbnails. All this involves is reading the original file, then saving the same exact thing. Kind of annoying, but it's simple.
Below is the the instruction that describes the task: ### Input: Handle re-generating the thumbnails. All this involves is reading the original file, then saving the same exact thing. Kind of annoying, but it's simple. ### Response: def regenerate_thumbs(self): """ Handle re-generat...
def csv_to_num_matrix(csv_file_path): """Load a CSV file consisting only of numbers into a Python matrix of floats. Args: csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) """ mtx = [] with open(csv_file_path) as csv_data_file: for row in csv_data_file: ...
Load a CSV file consisting only of numbers into a Python matrix of floats. Args: csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv)
Below is the the instruction that describes the task: ### Input: Load a CSV file consisting only of numbers into a Python matrix of floats. Args: csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) ### Response: def csv_to_num_matrix(csv_file_path): """Load a CSV file consistin...
def nack(self, message, subscription_id=None, **kwargs): """Reject receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be rejected, OR a dictionary containing a field 'mess...
Reject receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be rejected, OR a dictionary containing a field 'message-id'. :param subscription_id: ID of the associated subscr...
Below is the the instruction that describes the task: ### Input: Reject receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be rejected, OR a dictionary containing a field 'mes...
def infomax(data, weights=None, l_rate=None, block=None, w_change=1e-12, anneal_deg=60., anneal_step=0.9, extended=False, n_subgauss=1, kurt_size=6000, ext_blocks=1, max_iter=200, random_state=None, verbose=None): """Run the (extended) Infomax ICA decomposition on raw data b...
Run the (extended) Infomax ICA decomposition on raw data based on the publications of Bell & Sejnowski 1995 (Infomax) and Lee, Girolami & Sejnowski, 1999 (extended Infomax) Parameters ---------- data : np.ndarray, shape (n_samples, n_features) The data to unmix. w_init : np.ndarray, sh...
Below is the the instruction that describes the task: ### Input: Run the (extended) Infomax ICA decomposition on raw data based on the publications of Bell & Sejnowski 1995 (Infomax) and Lee, Girolami & Sejnowski, 1999 (extended Infomax) Parameters ---------- data : np.ndarray, shape (n_sample...