code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def inject(fun: Callable) -> Callable: """ A decorator for injection dependencies into functions/methods, based on their type annotations. .. code-block:: python class SomeClass: @inject def __init__(self, my_dep: DepType) -> None: self.my_dep = my_dep ...
A decorator for injection dependencies into functions/methods, based on their type annotations. .. code-block:: python class SomeClass: @inject def __init__(self, my_dep: DepType) -> None: self.my_dep = my_dep .. important:: On the opposite to :cla...
Below is the the instruction that describes the task: ### Input: A decorator for injection dependencies into functions/methods, based on their type annotations. .. code-block:: python class SomeClass: @inject def __init__(self, my_dep: DepType) -> None: self...
def geoid(self, potref, a=None, f=None, r=None, omega=None, order=2, lmax=None, lmax_calc=None, grid='DH2'): """ Create a global map of the height of the geoid and return an SHGeoid class instance. Usage ----- geoid = x.geoid(potref, [a, f, r, omega, order,...
Create a global map of the height of the geoid and return an SHGeoid class instance. Usage ----- geoid = x.geoid(potref, [a, f, r, omega, order, lmax, lmax_calc, grid]) Returns ------- geoid : SHGeoid class instance. Parameters ---------- ...
Below is the the instruction that describes the task: ### Input: Create a global map of the height of the geoid and return an SHGeoid class instance. Usage ----- geoid = x.geoid(potref, [a, f, r, omega, order, lmax, lmax_calc, grid]) Returns ------- geoid : ...
def render(self, **kwargs): """ Make breadcrumbs for a route :param kwargs: dictionary of named arguments used to construct the view :type kwargs: dict :return: List of dict items the view can use to construct the link. :rtype: {str: list({ "link": str, "title", str, "args", dic...
Make breadcrumbs for a route :param kwargs: dictionary of named arguments used to construct the view :type kwargs: dict :return: List of dict items the view can use to construct the link. :rtype: {str: list({ "link": str, "title", str, "args", dict})}
Below is the the instruction that describes the task: ### Input: Make breadcrumbs for a route :param kwargs: dictionary of named arguments used to construct the view :type kwargs: dict :return: List of dict items the view can use to construct the link. :rtype: {str: list({ "link": s...
def get_new_driver(self, browser=None, headless=None, servername=None, port=None, proxy=None, agent=None, switch_to=True, cap_file=None, disable_csp=None): """ This method spins up an extra browser for tests that require more than one. The first browser ...
This method spins up an extra browser for tests that require more than one. The first browser is already provided by tests that import base_case.BaseCase from seleniumbase. If parameters aren't specified, the method uses the same as the default driver. @Params ...
Below is the the instruction that describes the task: ### Input: This method spins up an extra browser for tests that require more than one. The first browser is already provided by tests that import base_case.BaseCase from seleniumbase. If parameters aren't specified, the method...
def parse_path(self, node): """ Parses <Path> @param node: Node containing the <Path> element @type node: xml.etree.Element """ if 'name' in node.lattrib: name = node.lattrib['name'] else: self.raise_error('<Path> must specify a name.') ...
Parses <Path> @param node: Node containing the <Path> element @type node: xml.etree.Element
Below is the the instruction that describes the task: ### Input: Parses <Path> @param node: Node containing the <Path> element @type node: xml.etree.Element ### Response: def parse_path(self, node): """ Parses <Path> @param node: Node containing the <Path> element ...
def _overlapping_channels(self, wavelengths): """ Return the channels that match the given wavelength array. """ sizes = self.meta["channel_sizes"] min_a, max_a = wavelengths.min(), wavelengths.max() matched_channel_names = [] for i, (name, size) in enumerate(zi...
Return the channels that match the given wavelength array.
Below is the the instruction that describes the task: ### Input: Return the channels that match the given wavelength array. ### Response: def _overlapping_channels(self, wavelengths): """ Return the channels that match the given wavelength array. """ sizes = self.meta["channel_size...
def set_indent(TokenClass, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_inden...
Set the previously saved indentation level.
Below is the the instruction that describes the task: ### Input: Set the previously saved indentation level. ### Response: def set_indent(TokenClass, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.inden...
def save(self, fname, mode=None, validate=True, wd=False, inline=False, relative=True, pack=False, encoding='utf-8'): """Save workflow to file For nlppln, the default is to save workflows with relative paths. """ super(WorkflowGenerator, self).save(fname, ...
Save workflow to file For nlppln, the default is to save workflows with relative paths.
Below is the the instruction that describes the task: ### Input: Save workflow to file For nlppln, the default is to save workflows with relative paths. ### Response: def save(self, fname, mode=None, validate=True, wd=False, inline=False, relative=True, pack=False, encoding='utf-8'): ...
def send(self, send_to, from_who, subject, message, reply_to=None): """Send Email. To use this module pass in a message, send_to, from_who, and subject. :param send_to: ``str`` :param from_who: ``str`` :param subject: ``str`` :param message: ``str`` :param reply...
Send Email. To use this module pass in a message, send_to, from_who, and subject. :param send_to: ``str`` :param from_who: ``str`` :param subject: ``str`` :param message: ``str`` :param reply_to: ``str``
Below is the the instruction that describes the task: ### Input: Send Email. To use this module pass in a message, send_to, from_who, and subject. :param send_to: ``str`` :param from_who: ``str`` :param subject: ``str`` :param message: ``str`` :param reply_to: ``str...
def normalizeStreamSources(self): """ TODO: document """ task = dict(self.__control) if 'dataset' in task: for stream in task['dataset']['streams']: self.normalizeStreamSource(stream) else: for subtask in task['tasks']: for stream in subtask['dataset']['streams']: ...
TODO: document
Below is the the instruction that describes the task: ### Input: TODO: document ### Response: def normalizeStreamSources(self): """ TODO: document """ task = dict(self.__control) if 'dataset' in task: for stream in task['dataset']['streams']: self.normalizeStreamSource(stream) ...
def gallery_images(self): """Instance depends on the API version: * 2018-06-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2018_06_01.operations.GalleryImagesOperations>` * 2019-03-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2019_03_01.operations.GalleryImagesOperatio...
Instance depends on the API version: * 2018-06-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2018_06_01.operations.GalleryImagesOperations>` * 2019-03-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2019_03_01.operations.GalleryImagesOperations>`
Below is the the instruction that describes the task: ### Input: Instance depends on the API version: * 2018-06-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2018_06_01.operations.GalleryImagesOperations>` * 2019-03-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2019_03_01....
def _get_fill(arr: ABCSparseArray) -> np.ndarray: """ Create a 0-dim ndarray containing the fill value Parameters ---------- arr : SparseArray Returns ------- fill_value : ndarray 0-dim ndarray with just the fill value. Notes ----- coerce fill_value to arr dtype if...
Create a 0-dim ndarray containing the fill value Parameters ---------- arr : SparseArray Returns ------- fill_value : ndarray 0-dim ndarray with just the fill value. Notes ----- coerce fill_value to arr dtype if possible int64 SparseArray can have NaN as fill_value if ...
Below is the the instruction that describes the task: ### Input: Create a 0-dim ndarray containing the fill value Parameters ---------- arr : SparseArray Returns ------- fill_value : ndarray 0-dim ndarray with just the fill value. Notes ----- coerce fill_value to arr d...
def set_column_count(self, count): """Sets the table column count. Args: count (int): column of rows """ current_row_count = self.row_count() current_column_count = self.column_count() if count > current_column_count: cl = TableEditableItem if sel...
Sets the table column count. Args: count (int): column of rows
Below is the the instruction that describes the task: ### Input: Sets the table column count. Args: count (int): column of rows ### Response: def set_column_count(self, count): """Sets the table column count. Args: count (int): column of rows """ cu...
def get(cls, parent=None, id=None, data=None): """Inherit info from parent and return new object""" # TODO - allow fetching of parent based on child? if parent is not None: route = copy(parent.route) else: route = {} if id is not None and cls.ID_NAME is ...
Inherit info from parent and return new object
Below is the the instruction that describes the task: ### Input: Inherit info from parent and return new object ### Response: def get(cls, parent=None, id=None, data=None): """Inherit info from parent and return new object""" # TODO - allow fetching of parent based on child? if parent is n...
def slice(x, start, length): """ Collection function: returns an array containing all the elements in `x` from index `start` (or starting from the end if `start` is negative) with the specified `length`. >>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ['x']) >>> df.select(slice(df.x, 2, 2...
Collection function: returns an array containing all the elements in `x` from index `start` (or starting from the end if `start` is negative) with the specified `length`. >>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ['x']) >>> df.select(slice(df.x, 2, 2).alias("sliced")).collect() [Row(sli...
Below is the the instruction that describes the task: ### Input: Collection function: returns an array containing all the elements in `x` from index `start` (or starting from the end if `start` is negative) with the specified `length`. >>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ['x']) >>...
def datasets_equal(dataset, other, fields_dataset=None, fields_distribution=None, return_diff=False): """Función de igualdad de dos datasets: se consideran iguales si los valores de los campos 'title', 'publisher.name', 'accrualPeriodicity' e 'issued' son iguales en ambos. Args: ...
Función de igualdad de dos datasets: se consideran iguales si los valores de los campos 'title', 'publisher.name', 'accrualPeriodicity' e 'issued' son iguales en ambos. Args: dataset (dict): un dataset, generado por la lectura de un catálogo other (dict): idem anterior Returns: ...
Below is the the instruction that describes the task: ### Input: Función de igualdad de dos datasets: se consideran iguales si los valores de los campos 'title', 'publisher.name', 'accrualPeriodicity' e 'issued' son iguales en ambos. Args: dataset (dict): un dataset, generado por la lectura de ...
def getAllUpcomingEvents(request, *, home=None): """ Return all the upcoming events (under home if given). :param request: Django request object :param home: only include events that are under this page (if given) :rtype: list of the namedtuple ThisEvent (title, page, url) """ qrys = [Simpl...
Return all the upcoming events (under home if given). :param request: Django request object :param home: only include events that are under this page (if given) :rtype: list of the namedtuple ThisEvent (title, page, url)
Below is the the instruction that describes the task: ### Input: Return all the upcoming events (under home if given). :param request: Django request object :param home: only include events that are under this page (if given) :rtype: list of the namedtuple ThisEvent (title, page, url) ### Response: de...
def t_multiline_OPTION_AND_VALUE(self, t): r'[^\r\n]+' t.lexer.multiline_newline_seen = False if t.value.endswith('\\'): return t.type = "OPTION_AND_VALUE" t.lexer.begin('INITIAL') value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1] t.lex...
r'[^\r\n]+
Below is the the instruction that describes the task: ### Input: r'[^\r\n]+ ### Response: def t_multiline_OPTION_AND_VALUE(self, t): r'[^\r\n]+' t.lexer.multiline_newline_seen = False if t.value.endswith('\\'): return t.type = "OPTION_AND_VALUE" t.lexer.begin('...
def reduce_l2(attrs, inputs, proto_obj): """Reduce input tensor by l2 normalization.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'}) return 'norm', new_attrs, inputs
Reduce input tensor by l2 normalization.
Below is the the instruction that describes the task: ### Input: Reduce input tensor by l2 normalization. ### Response: def reduce_l2(attrs, inputs, proto_obj): """Reduce input tensor by l2 normalization.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'}) return 'norm', new_a...
def continuous_periods(self): """ Return a list of continuous data periods by removing the data gaps from the overall record. """ result = [] # For the first period start_date = self.start_date for gap in self.pot_data_gaps: end_date = gap.start_date ...
Return a list of continuous data periods by removing the data gaps from the overall record.
Below is the the instruction that describes the task: ### Input: Return a list of continuous data periods by removing the data gaps from the overall record. ### Response: def continuous_periods(self): """ Return a list of continuous data periods by removing the data gaps from the overall record. ...
def del_permission_role(self, role, perm_view): """ Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view in role.permissions: try: ...
Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
Below is the the instruction that describes the task: ### Input: Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object ### Response: def del_permission_role(self, role, perm_view): """ ...
def patch(self, **kw): """Update the environment for the duration of a context.""" old_environ = self._environ self._environ = self._environ.copy() self._environ.update(kw) yield self._environ = old_environ
Update the environment for the duration of a context.
Below is the the instruction that describes the task: ### Input: Update the environment for the duration of a context. ### Response: def patch(self, **kw): """Update the environment for the duration of a context.""" old_environ = self._environ self._environ = self._environ.copy() self._environ.upda...
def cib_present(name, cibname, scope=None, extra_args=None): ''' Ensure that a CIB-file with the content of the current live CIB is created Should be run on one cluster node only (there may be races) name Irrelevant, not used (recommended: {{formulaname}}__cib_present_{{cibname}}) cibn...
Ensure that a CIB-file with the content of the current live CIB is created Should be run on one cluster node only (there may be races) name Irrelevant, not used (recommended: {{formulaname}}__cib_present_{{cibname}}) cibname name/path of the file containing the CIB scope sp...
Below is the the instruction that describes the task: ### Input: Ensure that a CIB-file with the content of the current live CIB is created Should be run on one cluster node only (there may be races) name Irrelevant, not used (recommended: {{formulaname}}__cib_present_{{cibname}}) cibname ...
def vector_poly_data(orig, vec): """ Creates a vtkPolyData object composed of vectors """ # shape, dimention checking if not isinstance(orig, np.ndarray): orig = np.asarray(orig) if not isinstance(vec, np.ndarray): vec = np.asarray(vec) if orig.ndim != 2: orig = orig.resha...
Creates a vtkPolyData object composed of vectors
Below is the the instruction that describes the task: ### Input: Creates a vtkPolyData object composed of vectors ### Response: def vector_poly_data(orig, vec): """ Creates a vtkPolyData object composed of vectors """ # shape, dimention checking if not isinstance(orig, np.ndarray): orig = np.a...
async def _submit(self, req_json: str) -> str: """ Submit (json) request to ledger; return (json) result. Raise AbsentPool for no pool, ClosedPool if pool is not yet open, or BadLedgerTxn on failure. :param req_json: json of request to sign and submit :return: json response ...
Submit (json) request to ledger; return (json) result. Raise AbsentPool for no pool, ClosedPool if pool is not yet open, or BadLedgerTxn on failure. :param req_json: json of request to sign and submit :return: json response
Below is the the instruction that describes the task: ### Input: Submit (json) request to ledger; return (json) result. Raise AbsentPool for no pool, ClosedPool if pool is not yet open, or BadLedgerTxn on failure. :param req_json: json of request to sign and submit :return: json response #...
def gunzipper(gzip_file): '''gunzips /path/to/foo.gz to /path/to/raw/2019/01/01/data.json ''' # TODO: take date as an input path_prefix = os.path.dirname(gzip_file) output_folder = os.path.join(path_prefix, 'raw/2019/01/01') outfile = os.path.join(output_folder, 'data.json') if not safe_is...
gunzips /path/to/foo.gz to /path/to/raw/2019/01/01/data.json
Below is the the instruction that describes the task: ### Input: gunzips /path/to/foo.gz to /path/to/raw/2019/01/01/data.json ### Response: def gunzipper(gzip_file): '''gunzips /path/to/foo.gz to /path/to/raw/2019/01/01/data.json ''' # TODO: take date as an input path_prefix = os.path.dirname(gzip...
def _fetch_targets(self, api_client, q, target): ''' Make an API call defined in metadata.json. Parse the returned object as implemented in the "parse_[object name]" method. :param api_client: :param q: :param target: :return: ''' # Handle & forma...
Make an API call defined in metadata.json. Parse the returned object as implemented in the "parse_[object name]" method. :param api_client: :param q: :param target: :return:
Below is the the instruction that describes the task: ### Input: Make an API call defined in metadata.json. Parse the returned object as implemented in the "parse_[object name]" method. :param api_client: :param q: :param target: :return: ### Response: def _fetch_targets(se...
def totals(self): """ Computes and returns dictionary containing home/away by player, shots and face-off totals :returns: dict of the form ``{ 'home/away': { 'all_keys': w_numeric_data } }`` """ def agg(d): keys = ['g','a','p','pm','pn','pim','s','ab','ms','h...
Computes and returns dictionary containing home/away by player, shots and face-off totals :returns: dict of the form ``{ 'home/away': { 'all_keys': w_numeric_data } }``
Below is the the instruction that describes the task: ### Input: Computes and returns dictionary containing home/away by player, shots and face-off totals :returns: dict of the form ``{ 'home/away': { 'all_keys': w_numeric_data } }`` ### Response: def totals(self): """ Computes and...
def enable_passive_host_checks(self, host): """Enable passive checks for a host Format of the line that triggers function call:: ENABLE_PASSIVE_HOST_CHECKS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None """ if n...
Enable passive checks for a host Format of the line that triggers function call:: ENABLE_PASSIVE_HOST_CHECKS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None
Below is the the instruction that describes the task: ### Input: Enable passive checks for a host Format of the line that triggers function call:: ENABLE_PASSIVE_HOST_CHECKS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None ### Respon...
def get_image(dockerRequirement, # type: Dict[Text, Text] pull_image, # type: bool force_pull=False # type: bool ): # type: (...) -> bool """ Acquire the software container image in the specified dockerRequirement using Sin...
Acquire the software container image in the specified dockerRequirement using Singularity and returns the success as a bool. Updates the provided dockerRequirement with the specific dockerImageId to the full path of the local image, if found. Likewise the dockerRequirement['dockerPull'] ...
Below is the the instruction that describes the task: ### Input: Acquire the software container image in the specified dockerRequirement using Singularity and returns the success as a bool. Updates the provided dockerRequirement with the specific dockerImageId to the full path of the local i...
def handle_error(self, code, message_values=None, raise_error=True): """Raise RuntimeError Args: code (integer): The error code from API or SDK. message (string): The error message from API or SDK. """ try: if message_values is None: m...
Raise RuntimeError Args: code (integer): The error code from API or SDK. message (string): The error message from API or SDK.
Below is the the instruction that describes the task: ### Input: Raise RuntimeError Args: code (integer): The error code from API or SDK. message (string): The error message from API or SDK. ### Response: def handle_error(self, code, message_values=None, raise_error=True): ...
def check_exists(required_files): """Decorator that checks if required files exist before running. Parameters ---------- required_files : list of str A list of strings indicating the filenames of regular files (not directories) that should be found in the input directory (which ...
Decorator that checks if required files exist before running. Parameters ---------- required_files : list of str A list of strings indicating the filenames of regular files (not directories) that should be found in the input directory (which is the first argument to the wrapped func...
Below is the the instruction that describes the task: ### Input: Decorator that checks if required files exist before running. Parameters ---------- required_files : list of str A list of strings indicating the filenames of regular files (not directories) that should be found in the inp...
def plot_CI( ax, sampler, modelidx=0, sed=True, confs=[3, 1, 0.5], e_unit=u.eV, label=None, e_range=None, e_npoints=100, threads=None, last_step=False, ): """Plot confidence interval. Parameters ---------- ax : `matplotlib.Axes` Axes to plot on. s...
Plot confidence interval. Parameters ---------- ax : `matplotlib.Axes` Axes to plot on. sampler : `emcee.EnsembleSampler` Sampler modelidx : int, optional Model index. Default is 0 sed : bool, optional Whether to plot SED or differential spectrum. If `None`, the ...
Below is the the instruction that describes the task: ### Input: Plot confidence interval. Parameters ---------- ax : `matplotlib.Axes` Axes to plot on. sampler : `emcee.EnsembleSampler` Sampler modelidx : int, optional Model index. Default is 0 sed : bool, optional ...
def info(endpoint): """Show metric info from a Prometheus endpoint. \b Example: $ ddev meta prom info :8080/_status/vars """ endpoint = sanitize_endpoint(endpoint) metrics = parse_metrics(endpoint) num_metrics = len(metrics) num_gauge = 0 num_counter = 0 num_histogram = 0 ...
Show metric info from a Prometheus endpoint. \b Example: $ ddev meta prom info :8080/_status/vars
Below is the the instruction that describes the task: ### Input: Show metric info from a Prometheus endpoint. \b Example: $ ddev meta prom info :8080/_status/vars ### Response: def info(endpoint): """Show metric info from a Prometheus endpoint. \b Example: $ ddev meta prom info :8080/...
def _encode_status(status): """Cast status to bytes representation of current Python version. According to :pep:`3333`, when using Python 3, the response status and headers must be bytes masquerading as unicode; that is, they must be of type "str" but are restricted to code points in th...
Cast status to bytes representation of current Python version. According to :pep:`3333`, when using Python 3, the response status and headers must be bytes masquerading as unicode; that is, they must be of type "str" but are restricted to code points in the "latin-1" set.
Below is the the instruction that describes the task: ### Input: Cast status to bytes representation of current Python version. According to :pep:`3333`, when using Python 3, the response status and headers must be bytes masquerading as unicode; that is, they must be of type "str" but are r...
def get_ticker(self, symbol, size=1, _async=False): """ 获取历史ticker :param symbol: :param size: 可选[1,2000] :return: """ params = {'symbol': symbol, 'size': size} url = u.MARKET_URL + '/market/history/trade' return http_get_request(url, params, _asy...
获取历史ticker :param symbol: :param size: 可选[1,2000] :return:
Below is the the instruction that describes the task: ### Input: 获取历史ticker :param symbol: :param size: 可选[1,2000] :return: ### Response: def get_ticker(self, symbol, size=1, _async=False): """ 获取历史ticker :param symbol: :param size: 可选[1,2000] :return...
def order_guest(self, guest_object, test=False): """Uses Product_Order::placeOrder to create a virtual guest. Useful when creating a virtual guest with options not supported by Virtual_Guest::createObject specifically ipv6 support. :param dictionary guest_object: See SoftLayer.CLI.virt...
Uses Product_Order::placeOrder to create a virtual guest. Useful when creating a virtual guest with options not supported by Virtual_Guest::createObject specifically ipv6 support. :param dictionary guest_object: See SoftLayer.CLI.virt.create._parse_create_args Example:: n...
Below is the the instruction that describes the task: ### Input: Uses Product_Order::placeOrder to create a virtual guest. Useful when creating a virtual guest with options not supported by Virtual_Guest::createObject specifically ipv6 support. :param dictionary guest_object: See SoftLayer...
def restore(self, time=None): """ Undeletes the object. Returns True if undeleted, False if it was already not deleted """ if self.deleted: time = time if time else self.deleted_at if time == self.deleted_at: self.deleted = False se...
Undeletes the object. Returns True if undeleted, False if it was already not deleted
Below is the the instruction that describes the task: ### Input: Undeletes the object. Returns True if undeleted, False if it was already not deleted ### Response: def restore(self, time=None): """ Undeletes the object. Returns True if undeleted, False if it was already not deleted """ ...
def create_handlers_map(): """Create new handlers map. Returns: list of (regexp, handler) pairs for WSGIApplication constructor. """ pipeline_handlers_map = [] if pipeline: pipeline_handlers_map = pipeline.create_handlers_map(prefix=".*/pipeline") return pipeline_handlers_map + [ # Task que...
Create new handlers map. Returns: list of (regexp, handler) pairs for WSGIApplication constructor.
Below is the the instruction that describes the task: ### Input: Create new handlers map. Returns: list of (regexp, handler) pairs for WSGIApplication constructor. ### Response: def create_handlers_map(): """Create new handlers map. Returns: list of (regexp, handler) pairs for WSGIApplication const...
def custom_str(self, sc_expr_str_fn): """ Works like Symbol.__str__(), but allows a custom format to be used for all symbol/choice references. See expr_str(). """ return "\n\n".join(node.custom_str(sc_expr_str_fn) for node in self.nodes)
Works like Symbol.__str__(), but allows a custom format to be used for all symbol/choice references. See expr_str().
Below is the the instruction that describes the task: ### Input: Works like Symbol.__str__(), but allows a custom format to be used for all symbol/choice references. See expr_str(). ### Response: def custom_str(self, sc_expr_str_fn): """ Works like Symbol.__str__(), but allows a custom form...
def client_disconnect(self, event): """ A client has disconnected, update possible subscriptions accordingly. :param event: """ self.log("Removing disconnected client from subscriptions", lvl=debug) client_uuid = event.clientuuid self._unsubscribe(client_uuid)
A client has disconnected, update possible subscriptions accordingly. :param event:
Below is the the instruction that describes the task: ### Input: A client has disconnected, update possible subscriptions accordingly. :param event: ### Response: def client_disconnect(self, event): """ A client has disconnected, update possible subscriptions accordingly. :param e...
def find_closest_divisor(to_divide, closest_to): """ This is used to find the right chunk size for importing a neuroglancer dataset that has a chunk import size that's not evenly divisible by 64,64,64. e.g. neuroglancer_chunk_size = find_closest_divisor(build_chunk_size, closest_to=[64,64,64]) Req...
This is used to find the right chunk size for importing a neuroglancer dataset that has a chunk import size that's not evenly divisible by 64,64,64. e.g. neuroglancer_chunk_size = find_closest_divisor(build_chunk_size, closest_to=[64,64,64]) Required: to_divide: (tuple) x,y,z chunk size to rechunk...
Below is the the instruction that describes the task: ### Input: This is used to find the right chunk size for importing a neuroglancer dataset that has a chunk import size that's not evenly divisible by 64,64,64. e.g. neuroglancer_chunk_size = find_closest_divisor(build_chunk_size, closest_to=[64,64...
def read_xml(self): """ read metadata from xml and set all the found properties. :return: the root element of the xml :rtype: ElementTree.Element """ with reading_ancillary_files(self): root = super(ImpactLayerMetadata, self).read_xml() if root i...
read metadata from xml and set all the found properties. :return: the root element of the xml :rtype: ElementTree.Element
Below is the the instruction that describes the task: ### Input: read metadata from xml and set all the found properties. :return: the root element of the xml :rtype: ElementTree.Element ### Response: def read_xml(self): """ read metadata from xml and set all the found properties. ...
def _gccalc(lon, lat, azimuth, maxdist=None): """ Original javascript on http://williams.best.vwh.net/gccalc.htm Translated into python by Thomas Lecocq This function is a black box, because trigonometry is difficult """ glat1 = lat * np.pi / 180. glon1 = lon * np.pi / 180. s = maxd...
Original javascript on http://williams.best.vwh.net/gccalc.htm Translated into python by Thomas Lecocq This function is a black box, because trigonometry is difficult
Below is the the instruction that describes the task: ### Input: Original javascript on http://williams.best.vwh.net/gccalc.htm Translated into python by Thomas Lecocq This function is a black box, because trigonometry is difficult ### Response: def _gccalc(lon, lat, azimuth, maxdist=None): """ Ori...
def bind_extensions(app): """Configure extensions. Args: app (Flask): initialized Flask app instance """ # bind plugin to app object app.db = app.config['PUZZLE_BACKEND'] app.db.init_app(app) # bind bootstrap blueprints bootstrap.init_app(app) markdown(app) @app.templa...
Configure extensions. Args: app (Flask): initialized Flask app instance
Below is the the instruction that describes the task: ### Input: Configure extensions. Args: app (Flask): initialized Flask app instance ### Response: def bind_extensions(app): """Configure extensions. Args: app (Flask): initialized Flask app instance """ # bind plugin to app ...
def info(self, *args) -> "Err": """ Creates an info message """ error = self._create_err("info", *args) print(self._errmsg(error)) return error
Creates an info message
Below is the the instruction that describes the task: ### Input: Creates an info message ### Response: def info(self, *args) -> "Err": """ Creates an info message """ error = self._create_err("info", *args) print(self._errmsg(error)) return error
def visitTypeExceptions(self, ctx: jsgParser.TypeExceptionsContext): """ typeExceptions: DASH idref+ """ for tkn in as_tokens(ctx.idref()): self._context.directives.append('_CONTEXT.TYPE_EXCEPTIONS.append("{}")'.format(tkn))
typeExceptions: DASH idref+
Below is the the instruction that describes the task: ### Input: typeExceptions: DASH idref+ ### Response: def visitTypeExceptions(self, ctx: jsgParser.TypeExceptionsContext): """ typeExceptions: DASH idref+ """ for tkn in as_tokens(ctx.idref()): self._context.directives.append('_CONTEX...
def plot_cylinder(ax, start, end, start_radius, end_radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): '''plot a 3d cylinder''' assert not np.all(start == end), 'Cylinder must have length' x, y, z = generate_cylindrical_points(start, end, start_radius, end_radius, ...
plot a 3d cylinder
Below is the the instruction that describes the task: ### Input: plot a 3d cylinder ### Response: def plot_cylinder(ax, start, end, start_radius, end_radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): '''plot a 3d cylinder''' assert not np.all(start == end), 'Cylinder must ...
def copy_config_input_target_config_target_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") copy_config = ET.Element("copy_config") config = copy_config input = ET.SubElement(copy_config, "input") target = ET.SubElement...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def copy_config_input_target_config_target_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") copy_config = ET.Element("copy_config") ...
def range_parse(s): """ >>> range_parse("chr1:1000-1") Range(seqid='chr1', start=1, end=1000, score=0, id=0) """ chr, se = s.split(":") start, end = se.split("-") start, end = int(start), int(end) if start > end: start, end = end, start return Range(chr, start, end, 0, 0)
>>> range_parse("chr1:1000-1") Range(seqid='chr1', start=1, end=1000, score=0, id=0)
Below is the the instruction that describes the task: ### Input: >>> range_parse("chr1:1000-1") Range(seqid='chr1', start=1, end=1000, score=0, id=0) ### Response: def range_parse(s): """ >>> range_parse("chr1:1000-1") Range(seqid='chr1', start=1, end=1000, score=0, id=0) """ chr, se = s.sp...
def __parse_dois(self, x): """ Parse the Dataset_DOI field. Could be one DOI string, or a list of DOIs :param any x: Str or List of DOI ids :return none: list is set to self """ # datasetDOI is a string. parse, validate and return a list of DOIs if isinstance(x, s...
Parse the Dataset_DOI field. Could be one DOI string, or a list of DOIs :param any x: Str or List of DOI ids :return none: list is set to self
Below is the the instruction that describes the task: ### Input: Parse the Dataset_DOI field. Could be one DOI string, or a list of DOIs :param any x: Str or List of DOI ids :return none: list is set to self ### Response: def __parse_dois(self, x): """ Parse the Dataset_DOI field. C...
def start_new_hypervisor(self, working_dir=None): """ Creates a new Dynamips process and start it. :param working_dir: working directory :returns: the new hypervisor instance """ if not self._dynamips_path: self.find_dynamips() if not working_dir: ...
Creates a new Dynamips process and start it. :param working_dir: working directory :returns: the new hypervisor instance
Below is the the instruction that describes the task: ### Input: Creates a new Dynamips process and start it. :param working_dir: working directory :returns: the new hypervisor instance ### Response: def start_new_hypervisor(self, working_dir=None): """ Creates a new Dynamips proc...
def _determine_nTrackIterations(self,nTrackIterations): """Determine a good value for nTrackIterations based on the misalignment between stream and orbit; just based on some rough experience for now""" if not nTrackIterations is None: self.nTrackIterations= nTrackIterations retur...
Determine a good value for nTrackIterations based on the misalignment between stream and orbit; just based on some rough experience for now
Below is the the instruction that describes the task: ### Input: Determine a good value for nTrackIterations based on the misalignment between stream and orbit; just based on some rough experience for now ### Response: def _determine_nTrackIterations(self,nTrackIterations): """Determine a good value for nT...
def list_check(*args, func=None): """Check if arguments are list type.""" func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (list, collections.UserList, collections.abc.MutableSequence)): name = type(var).__name__ raise ListError( f'...
Check if arguments are list type.
Below is the the instruction that describes the task: ### Input: Check if arguments are list type. ### Response: def list_check(*args, func=None): """Check if arguments are list type.""" func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (list, collections.UserList, co...
def validate_openbin_mode(mode, _valid_chars=frozenset("rwxab+")): # type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None """Check ``mode`` parameter of `~fs.base.FS.openbin` is valid. Arguments: mode (str): Mode parameter. Raises: `ValueError` if mode is not valid. """ if ...
Check ``mode`` parameter of `~fs.base.FS.openbin` is valid. Arguments: mode (str): Mode parameter. Raises: `ValueError` if mode is not valid.
Below is the the instruction that describes the task: ### Input: Check ``mode`` parameter of `~fs.base.FS.openbin` is valid. Arguments: mode (str): Mode parameter. Raises: `ValueError` if mode is not valid. ### Response: def validate_openbin_mode(mode, _valid_chars=frozenset("rwxab+")): ...
def top(self): """ list of processes in a running container :return: None or list of dicts """ # let's get resources from .stats() ps_args = "-eo pid,ppid,wchan,args" # returns {"Processes": [values], "Titles": [values]} # it's easier to play with list of...
list of processes in a running container :return: None or list of dicts
Below is the the instruction that describes the task: ### Input: list of processes in a running container :return: None or list of dicts ### Response: def top(self): """ list of processes in a running container :return: None or list of dicts """ # let's get resourc...
def cross_check_launchers(self, launchers): """ Performs consistency checks across all the launchers. """ if len(launchers) == 0: raise Exception('Empty launcher list') timestamps = [launcher.timestamp for launcher in launchers] if not all(timestamps[0] == tstamp for tst...
Performs consistency checks across all the launchers.
Below is the the instruction that describes the task: ### Input: Performs consistency checks across all the launchers. ### Response: def cross_check_launchers(self, launchers): """ Performs consistency checks across all the launchers. """ if len(launchers) == 0: raise Exception('Emp...
def distance_matrix(lons, lats, diameter=2*EARTH_RADIUS): """ :param lons: array of m longitudes :param lats: array of m latitudes :returns: matrix of (m, m) distances """ m = len(lons) assert m == len(lats), (m, len(lats)) lons = numpy.radians(lons) lats = numpy.radians(lats) co...
:param lons: array of m longitudes :param lats: array of m latitudes :returns: matrix of (m, m) distances
Below is the the instruction that describes the task: ### Input: :param lons: array of m longitudes :param lats: array of m latitudes :returns: matrix of (m, m) distances ### Response: def distance_matrix(lons, lats, diameter=2*EARTH_RADIUS): """ :param lons: array of m longitudes :param lats: ...
def _mark_received(self, tsn): """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True # consolidate misordered en...
Mark an incoming data TSN as received.
Below is the the instruction that describes the task: ### Input: Mark an incoming data TSN as received. ### Response: def _mark_received(self, tsn): """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._...
def install(self, update=False): """ install conda packages """ offline = self.offline or update self.create_env(offline) self.install_pkgs(offline) self.install_pip(offline) return tuple()
install conda packages
Below is the the instruction that describes the task: ### Input: install conda packages ### Response: def install(self, update=False): """ install conda packages """ offline = self.offline or update self.create_env(offline) self.install_pkgs(offline) self.ins...
def get_consistent_set_and_saxis(magmoms, saxis=None): """ Method to ensure a list of magmoms use the same spin axis. Returns a tuple of a list of Magmoms and their global spin axis. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :param saxis: can provide a specif...
Method to ensure a list of magmoms use the same spin axis. Returns a tuple of a list of Magmoms and their global spin axis. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :param saxis: can provide a specific global spin axis :return: (list of Magmoms, global spin axis) tu...
Below is the the instruction that describes the task: ### Input: Method to ensure a list of magmoms use the same spin axis. Returns a tuple of a list of Magmoms and their global spin axis. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :param saxis: can provide a specific glo...
def to_str(obj, encoding='utf-8', **encode_args): r""" Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For example:: >>> some_str = b"\xff" >>> some_unicode = u"\u1234" >>> some_exception = Exception(u'Error: ' + some_unicode) >>> r(to_str(some_str)) ...
r""" Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For example:: >>> some_str = b"\xff" >>> some_unicode = u"\u1234" >>> some_exception = Exception(u'Error: ' + some_unicode) >>> r(to_str(some_str)) b'\xff' >>> r(to_str(some_unicode)) ...
Below is the the instruction that describes the task: ### Input: r""" Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For example:: >>> some_str = b"\xff" >>> some_unicode = u"\u1234" >>> some_exception = Exception(u'Error: ' + some_unicode) >>> r(to_...
def serialise(self, element: Element) -> str: """ Serialises the given element into Compact JSON. >>> CompactJSONSerialiser().serialise(String(content='Hello')) '["string", null, null, "Hello"]' """ return json.dumps(self.serialise_element(element))
Serialises the given element into Compact JSON. >>> CompactJSONSerialiser().serialise(String(content='Hello')) '["string", null, null, "Hello"]'
Below is the the instruction that describes the task: ### Input: Serialises the given element into Compact JSON. >>> CompactJSONSerialiser().serialise(String(content='Hello')) '["string", null, null, "Hello"]' ### Response: def serialise(self, element: Element) -> str: """ Serialis...
def write(models, csvout, rulelist, write_header, base=None, logger=logging): ''' models - one or more input Versa models from which output is generated. ''' properties = [ k for (k, v) in rulelist ] numprops = len(properties) headers = [ v for (k, v) in rulelist ] if write_header: c...
models - one or more input Versa models from which output is generated.
Below is the the instruction that describes the task: ### Input: models - one or more input Versa models from which output is generated. ### Response: def write(models, csvout, rulelist, write_header, base=None, logger=logging): ''' models - one or more input Versa models from which output is generated. ...
def dispatch(self, requestProtocol, requestPayload): """ Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol :param requestPayload: <dict> request :param version: <float> version :param ...
Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol :param requestPayload: <dict> request :param version: <float> version :param method: <str> method name :param parameters: <dict> data para...
Below is the the instruction that describes the task: ### Input: Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol :param requestPayload: <dict> request :param version: <float> version :param meth...
def create_mutating_webhook_configuration(self, body, **kwargs): """ create a MutatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_mutating_webhook_configurat...
create a MutatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_mutating_webhook_configuration(body, async_req=True) >>> result = thread.get() :param async_req...
Below is the the instruction that describes the task: ### Input: create a MutatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_mutating_webhook_configuration(body, async_...
def plot_summaries(self, show=False, save=True, figure_type=None): """Plot summary graphs. Args: show: shows the figure if True. save: saves the figure if True. figure_type: optional, figure type to create. """ if not figure_type: figure_...
Plot summary graphs. Args: show: shows the figure if True. save: saves the figure if True. figure_type: optional, figure type to create.
Below is the the instruction that describes the task: ### Input: Plot summary graphs. Args: show: shows the figure if True. save: saves the figure if True. figure_type: optional, figure type to create. ### Response: def plot_summaries(self, show=False, save=True, figure...
def __prepare_local(data): """Prepare localpart of the JID :Parameters: - `data`: localpart of the JID :Types: - `data`: `unicode` :raise JIDError: if the local name is too long. :raise pyxmpp.xmppstringprep.StringprepError: if the local name...
Prepare localpart of the JID :Parameters: - `data`: localpart of the JID :Types: - `data`: `unicode` :raise JIDError: if the local name is too long. :raise pyxmpp.xmppstringprep.StringprepError: if the local name fails Nodeprep preparation.
Below is the the instruction that describes the task: ### Input: Prepare localpart of the JID :Parameters: - `data`: localpart of the JID :Types: - `data`: `unicode` :raise JIDError: if the local name is too long. :raise pyxmpp.xmppstringprep.StringprepError...
def lineSeqmentsDoIntersect(line1, line2): """ Return True if line segment line1 intersects line segment line2 and line1 and line2 are not parallel. """ (x1, y1), (x2, y2) = line1 (u1, v1), (u2, v2) = line2 (a, b), (c, d) = (x2 - x1, u1 - u2), (y2 - y1, v1 - v2) e, f = u1 - x1, v...
Return True if line segment line1 intersects line segment line2 and line1 and line2 are not parallel.
Below is the the instruction that describes the task: ### Input: Return True if line segment line1 intersects line segment line2 and line1 and line2 are not parallel. ### Response: def lineSeqmentsDoIntersect(line1, line2): """ Return True if line segment line1 intersects line segment line2 and ...
def split(self, t): """returns two segments, whose union is this segment and which join at self.point(t).""" bpoints1, bpoints2 = split_bezier(self.bpoints(), t) return QuadraticBezier(*bpoints1), QuadraticBezier(*bpoints2)
returns two segments, whose union is this segment and which join at self.point(t).
Below is the the instruction that describes the task: ### Input: returns two segments, whose union is this segment and which join at self.point(t). ### Response: def split(self, t): """returns two segments, whose union is this segment and which join at self.point(t).""" bpoints1, bp...
def _get_collisions(indices): # type: (...) -> Dict[int, List[int]] """ Return a dict ``{column_id: [possible term ids]}`` with collision information. """ collisions = defaultdict(list) # type: Dict[int, List[int]] for term_id, hash_id in enumerate(indices): collisions[hash_id].appe...
Return a dict ``{column_id: [possible term ids]}`` with collision information.
Below is the the instruction that describes the task: ### Input: Return a dict ``{column_id: [possible term ids]}`` with collision information. ### Response: def _get_collisions(indices): # type: (...) -> Dict[int, List[int]] """ Return a dict ``{column_id: [possible term ids]}`` with collision...
def json_splitter(buffer): """Attempt to parse a json object from a buffer. If there is at least one object, return it and the rest of the buffer, otherwise return None. """ buffer = buffer.strip() try: obj, index = json_decoder.raw_decode(buffer) rest = buffer[json.decoder.WHITESPAC...
Attempt to parse a json object from a buffer. If there is at least one object, return it and the rest of the buffer, otherwise return None.
Below is the the instruction that describes the task: ### Input: Attempt to parse a json object from a buffer. If there is at least one object, return it and the rest of the buffer, otherwise return None. ### Response: def json_splitter(buffer): """Attempt to parse a json object from a buffer. If there is ...
def private_messenger(): """ Thread which runs in parallel and constantly checks for new messages in the private pipe and sends them to the specific client. If client is not connected the message is discarded. """ while __websocket_server_running__: pipein = open(PRIVATE_PIPE, 'r') ...
Thread which runs in parallel and constantly checks for new messages in the private pipe and sends them to the specific client. If client is not connected the message is discarded.
Below is the the instruction that describes the task: ### Input: Thread which runs in parallel and constantly checks for new messages in the private pipe and sends them to the specific client. If client is not connected the message is discarded. ### Response: def private_messenger(): """ Thread whi...
def cast(obj): """ Many tools love to subclass built-in types in order to implement useful functionality, such as annotating the safety of a Unicode string, or adding additional methods to a dict. However, cPickle loves to preserve those subtypes during serialization, resulting in CallError during :...
Many tools love to subclass built-in types in order to implement useful functionality, such as annotating the safety of a Unicode string, or adding additional methods to a dict. However, cPickle loves to preserve those subtypes during serialization, resulting in CallError during :meth:`call <mitogen.par...
Below is the the instruction that describes the task: ### Input: Many tools love to subclass built-in types in order to implement useful functionality, such as annotating the safety of a Unicode string, or adding additional methods to a dict. However, cPickle loves to preserve those subtypes during seri...
def _dbus_notify(title, message): """ Shows system notification message via dbus. `title` Notification title. `message` Notification message. """ try: # fetch main account manager interface bus = dbus.SessionBus() obj = bus.get_object('or...
Shows system notification message via dbus. `title` Notification title. `message` Notification message.
Below is the the instruction that describes the task: ### Input: Shows system notification message via dbus. `title` Notification title. `message` Notification message. ### Response: def _dbus_notify(title, message): """ Shows system notification message via dbus. ...
def log_likelihood(self, y, _const=math.log(2.0*math.pi), quiet=False): """ Compute the marginalized likelihood of the GP model The factorized matrix from the previous call to :func:`GP.compute` is used so ``compute`` must be called first. Args: y (array[n]): The ob...
Compute the marginalized likelihood of the GP model The factorized matrix from the previous call to :func:`GP.compute` is used so ``compute`` must be called first. Args: y (array[n]): The observations at coordinates ``x`` from :func:`GP.compute`. quiet (...
Below is the the instruction that describes the task: ### Input: Compute the marginalized likelihood of the GP model The factorized matrix from the previous call to :func:`GP.compute` is used so ``compute`` must be called first. Args: y (array[n]): The observations at coordinat...
def _set_dict_translations(instance, dict_translations): """ Establece los atributos de traducciones a partir de una dict que contiene todas las traducciones. """ # If class has no translatable fields get out if not hasattr(instance._meta, "translatable_fields"): return False # If we are in a site with one l...
Establece los atributos de traducciones a partir de una dict que contiene todas las traducciones.
Below is the the instruction that describes the task: ### Input: Establece los atributos de traducciones a partir de una dict que contiene todas las traducciones. ### Response: def _set_dict_translations(instance, dict_translations): """ Establece los atributos de traducciones a partir de una dict que contiene...
def rename_cmd(argv): """Rename a virtualenv""" parser = argparse.ArgumentParser() parser.add_argument('source') parser.add_argument('target') pargs = parser.parse_args(argv) copy_virtualenv_project(pargs.source, pargs.target) return rmvirtualenvs([pargs.source])
Rename a virtualenv
Below is the the instruction that describes the task: ### Input: Rename a virtualenv ### Response: def rename_cmd(argv): """Rename a virtualenv""" parser = argparse.ArgumentParser() parser.add_argument('source') parser.add_argument('target') pargs = parser.parse_args(argv) copy_virtualenv_p...
def GetFormatSpecification(cls): """Retrieves the format specification. Returns: FormatSpecification: format specification. """ format_specification = specification.FormatSpecification(cls.NAME) format_specification.AddNewSignature(b'ElfFile\x00', offset=0) return format_specification
Retrieves the format specification. Returns: FormatSpecification: format specification.
Below is the the instruction that describes the task: ### Input: Retrieves the format specification. Returns: FormatSpecification: format specification. ### Response: def GetFormatSpecification(cls): """Retrieves the format specification. Returns: FormatSpecification: format specification...
def process_request(self, request): """ Log user in if `request` contains a valid login token. Return a HTTP redirect response that removes the token from the URL after a successful login when sessions are enabled, else ``None``. """ token = request.GET.get(TOKEN_NAME) ...
Log user in if `request` contains a valid login token. Return a HTTP redirect response that removes the token from the URL after a successful login when sessions are enabled, else ``None``.
Below is the the instruction that describes the task: ### Input: Log user in if `request` contains a valid login token. Return a HTTP redirect response that removes the token from the URL after a successful login when sessions are enabled, else ``None``. ### Response: def process_request(self, req...
def RangeFromChild(self, child) -> TextRange: """ Call IUIAutomationTextPattern::RangeFromChild. child: `Control` or its subclass. Return `TextRange` or None, a text range enclosing a child element such as an image, hyperlink, Microsoft Excel spreadsheet, or other embedded ob...
Call IUIAutomationTextPattern::RangeFromChild. child: `Control` or its subclass. Return `TextRange` or None, a text range enclosing a child element such as an image, hyperlink, Microsoft Excel spreadsheet, or other embedded object. Refer https://docs.microsoft.com/en-us/windows/deskt...
Below is the the instruction that describes the task: ### Input: Call IUIAutomationTextPattern::RangeFromChild. child: `Control` or its subclass. Return `TextRange` or None, a text range enclosing a child element such as an image, hyperlink, Microsoft Excel spreadsheet, or other embedded...
def to_csv(data, field_names=None, filename='data.csv', overwrite=True, write_headers=True, append=False, flat=True, primary_fields=None, sort_fields=True): """ DEPRECATED Write a list of dicts to a csv file :param data: List of dicts :param field_names: The ...
DEPRECATED Write a list of dicts to a csv file :param data: List of dicts :param field_names: The list column names :param filename: The name of the file :param overwrite: Overwrite the file if exists :param write_headers: Write the headers to the csv file :param append: Write new row...
Below is the the instruction that describes the task: ### Input: DEPRECATED Write a list of dicts to a csv file :param data: List of dicts :param field_names: The list column names :param filename: The name of the file :param overwrite: Overwrite the file if exists :param write_headers...
def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, n...
Get VM configuration
Below is the the instruction that describes the task: ### Input: Get VM configuration ### Response: def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in s...
def url(self, suffix=""): """ Return a constructed URL, appending an optional suffix (uri path). Arguments: suffix (str : ""): The suffix to append to the end of the URL Returns: str: The complete URL """ return super(neuroRemote, ...
Return a constructed URL, appending an optional suffix (uri path). Arguments: suffix (str : ""): The suffix to append to the end of the URL Returns: str: The complete URL
Below is the the instruction that describes the task: ### Input: Return a constructed URL, appending an optional suffix (uri path). Arguments: suffix (str : ""): The suffix to append to the end of the URL Returns: str: The complete URL ### Response: def url(self, suffix=""...
def firstElementChild(self): """Finds the first child node of that element which is a Element node Note the handling of entities references is different than in the W3C DOM element traversal spec since we don't have back reference from entities content to entities refere...
Finds the first child node of that element which is a Element node Note the handling of entities references is different than in the W3C DOM element traversal spec since we don't have back reference from entities content to entities references.
Below is the the instruction that describes the task: ### Input: Finds the first child node of that element which is a Element node Note the handling of entities references is different than in the W3C DOM element traversal spec since we don't have back reference from entities content ...
def evaluate(data_source, batch_size, ctx=None): """Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The context of the com...
Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The context of the computation. Returns ------- loss: float ...
Below is the the instruction that describes the task: ### Input: Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The conte...
def difference(self, boolean_switches): """ [COMPATIBILITY] Make a copy of the current instance, and then discard all options that are in boolean_switches. :param set boolean_switches: A collection of Boolean switches to disable. :return: A new SimState...
[COMPATIBILITY] Make a copy of the current instance, and then discard all options that are in boolean_switches. :param set boolean_switches: A collection of Boolean switches to disable. :return: A new SimStateOptions instance.
Below is the the instruction that describes the task: ### Input: [COMPATIBILITY] Make a copy of the current instance, and then discard all options that are in boolean_switches. :param set boolean_switches: A collection of Boolean switches to disable. :return: A new...
def normalize_linefeeds(self, a_string): """Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.` :param a_string: A string that may have non-normalized line feeds i.e. output returned from device, or a device prompt :type a_string: str """ newline = re.compile("(\r\r\r\n|\r\r\n|...
Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.` :param a_string: A string that may have non-normalized line feeds i.e. output returned from device, or a device prompt :type a_string: str
Below is the the instruction that describes the task: ### Input: Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.` :param a_string: A string that may have non-normalized line feeds i.e. output returned from device, or a device prompt :type a_string: str ### Response: def normalize_linefeeds(sel...
def close_room(self, room, namespace): """Remove all participants from a room.""" try: for sid in self.get_participants(namespace, room): self.leave_room(sid, namespace, room) except KeyError: pass
Remove all participants from a room.
Below is the the instruction that describes the task: ### Input: Remove all participants from a room. ### Response: def close_room(self, room, namespace): """Remove all participants from a room.""" try: for sid in self.get_participants(namespace, room): self.leave_room(s...
def iter_target_siblings_and_ancestors(self, target): """Produces an iterator over a target's siblings and ancestor lineage. :returns: A target iterator yielding the target and its siblings and then it ancestors from nearest to furthest removed. """ def iter_targets_in_spec_path(spec_path...
Produces an iterator over a target's siblings and ancestor lineage. :returns: A target iterator yielding the target and its siblings and then it ancestors from nearest to furthest removed.
Below is the the instruction that describes the task: ### Input: Produces an iterator over a target's siblings and ancestor lineage. :returns: A target iterator yielding the target and its siblings and then it ancestors from nearest to furthest removed. ### Response: def iter_target_siblings_and...
def rename_selected_state(self, key_value, modifier_mask): """Callback method for shortcut action rename Searches for a single selected state model and open the according page. Page is created if it is not existing. Then the rename method of the state controller is called. :param key_v...
Callback method for shortcut action rename Searches for a single selected state model and open the according page. Page is created if it is not existing. Then the rename method of the state controller is called. :param key_value: :param modifier_mask:
Below is the the instruction that describes the task: ### Input: Callback method for shortcut action rename Searches for a single selected state model and open the according page. Page is created if it is not existing. Then the rename method of the state controller is called. :param key_va...
def instruction_in_row(self, row, specification): """Parse an instruction. :param row: the row of the instruction :param specification: the specification of the instruction :return: the instruction in the row """ whole_instruction_ = self._as_instruction(specification) ...
Parse an instruction. :param row: the row of the instruction :param specification: the specification of the instruction :return: the instruction in the row
Below is the the instruction that describes the task: ### Input: Parse an instruction. :param row: the row of the instruction :param specification: the specification of the instruction :return: the instruction in the row ### Response: def instruction_in_row(self, row, specification): ...
def set_smearing_function(self, function_name): """ function_name == 'Normal': smearing is done by normal distribution. 'Cauchy': smearing is done by Cauchy distribution. """ if function_name == 'Cauchy': self._smearing_function = CauchyDistribution(self._sigm...
function_name == 'Normal': smearing is done by normal distribution. 'Cauchy': smearing is done by Cauchy distribution.
Below is the the instruction that describes the task: ### Input: function_name == 'Normal': smearing is done by normal distribution. 'Cauchy': smearing is done by Cauchy distribution. ### Response: def set_smearing_function(self, function_name): """ function_name == 'Normal'...
def set_license(self, key): """Set the license on a redfish system :param key: license key """ data = {'LicenseKey': key} license_service_uri = (utils.get_subresource_path_by(self, ['Oem', 'Hpe', 'Links', 'LicenseService'])) self._conn.post...
Set the license on a redfish system :param key: license key
Below is the the instruction that describes the task: ### Input: Set the license on a redfish system :param key: license key ### Response: def set_license(self, key): """Set the license on a redfish system :param key: license key """ data = {'LicenseKey': key} lice...
def t_multiline_NEWLINE(self, t): r'\r\n|\n|\r' if t.lexer.multiline_newline_seen: return self.t_multiline_OPTION_AND_VALUE(t) t.lexer.multiline_newline_seen = True
r'\r\n|\n|\r
Below is the the instruction that describes the task: ### Input: r'\r\n|\n|\r ### Response: def t_multiline_NEWLINE(self, t): r'\r\n|\n|\r' if t.lexer.multiline_newline_seen: return self.t_multiline_OPTION_AND_VALUE(t) t.lexer.multiline_newline_seen = True
def run(self): """ Runs the thread! Should not be used use start() method instead. """ self._running.set() self._status = TransferState.RUNNING self._time_started = time.time() parted_file = DPartedFile(self._temp_file, self._ses...
Runs the thread! Should not be used use start() method instead.
Below is the the instruction that describes the task: ### Input: Runs the thread! Should not be used use start() method instead. ### Response: def run(self): """ Runs the thread! Should not be used use start() method instead. """ self._running.set() self._status = TransferSt...
def request_search(self, txt=None): """ Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead. """ if self.checkBoxRegex.isChecked(): try: re.compile(self.lineEditSearc...
Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead.
Below is the the instruction that describes the task: ### Input: Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead. ### Response: def request_search(self, txt=None): """ Requests a search operation. ...
async def geoadd(self, name, *values): """ Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad latitude, longitude and ...
Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad latitude, longitude and name.
Below is the the instruction that describes the task: ### Input: Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad latitude, long...
def processors(self, processor_name=None): """Return a list of Processor objects. :param project_id: ObjectId of Genesis project :type project_id: string :rtype: list of Processor objects """ if processor_name: return self.api.processor.get(name=processor_na...
Return a list of Processor objects. :param project_id: ObjectId of Genesis project :type project_id: string :rtype: list of Processor objects
Below is the the instruction that describes the task: ### Input: Return a list of Processor objects. :param project_id: ObjectId of Genesis project :type project_id: string :rtype: list of Processor objects ### Response: def processors(self, processor_name=None): """Return a list o...
def get_interface_detail_output_interface_ifHCOutBroadcastPkts(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "o...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_interface_detail_output_interface_ifHCOutBroadcastPkts(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interfac...