code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def ListDescendentPathInfos(self, client_id, path_type, components, timestamp=None, max_depth=None, cursor=None): """Lists path info rec...
Lists path info records that correspond to descendants of given path.
Below is the the instruction that describes the task: ### Input: Lists path info records that correspond to descendants of given path. ### Response: def ListDescendentPathInfos(self, client_id, path_type, components, ...
def new_request_session(config, cookies): """Create a new request session.""" session = requests.Session() if cookies: session.cookies = cookies session.max_redirects = config["maxhttpredirects"] session.headers.update({ "User-Agent": config["useragent"], }) if config["cookie...
Create a new request session.
Below is the the instruction that describes the task: ### Input: Create a new request session. ### Response: def new_request_session(config, cookies): """Create a new request session.""" session = requests.Session() if cookies: session.cookies = cookies session.max_redirects = config["maxht...
def clean_jobs(self, recursive=False): """Clean up all the jobs associated with this object. If recursive is True this also clean jobs dispatch by this object.""" self._interface.clean_jobs(self.scatter_link, clean_all=recursive)
Clean up all the jobs associated with this object. If recursive is True this also clean jobs dispatch by this object.
Below is the the instruction that describes the task: ### Input: Clean up all the jobs associated with this object. If recursive is True this also clean jobs dispatch by this object. ### Response: def clean_jobs(self, recursive=False): """Clean up all the jobs associated with this object. ...
def GetClientsByStatus(self): """Get all the clients in a dict of {status: [client_list]}.""" started = self.GetClients() completed = self.GetCompletedClients() outstanding = started - completed return { "STARTED": started, "COMPLETED": completed, "OUTSTANDING": outstanding ...
Get all the clients in a dict of {status: [client_list]}.
Below is the the instruction that describes the task: ### Input: Get all the clients in a dict of {status: [client_list]}. ### Response: def GetClientsByStatus(self): """Get all the clients in a dict of {status: [client_list]}.""" started = self.GetClients() completed = self.GetCompletedClients() o...
def vals(self, var_type): """ Create a dictionary with name/value pairs listing the variables of a particular type that have a value. """ return {x: y for x, y in self.items() if y.has_value_of_type(var_type)}
Create a dictionary with name/value pairs listing the variables of a particular type that have a value.
Below is the the instruction that describes the task: ### Input: Create a dictionary with name/value pairs listing the variables of a particular type that have a value. ### Response: def vals(self, var_type): """ Create a dictionary with name/value pairs listing the variables of a p...
def log_to_file(path=None, io=False, level='INFO'): """ Install a new :class:`logging.Handler` writing applications logs to the filesystem. Useful when debugging slave IO problems. Parameters to this function may be overridden at runtime using environment variables. See :ref:`logging-env-vars`. ...
Install a new :class:`logging.Handler` writing applications logs to the filesystem. Useful when debugging slave IO problems. Parameters to this function may be overridden at runtime using environment variables. See :ref:`logging-env-vars`. :param str path: If not :data:`None`, a filesystem pat...
Below is the the instruction that describes the task: ### Input: Install a new :class:`logging.Handler` writing applications logs to the filesystem. Useful when debugging slave IO problems. Parameters to this function may be overridden at runtime using environment variables. See :ref:`logging-env-vars`...
def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it wa...
Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by ...
Below is the the instruction that describes the task: ### Input: Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of th...
def path(self) -> str: """ :return: path of this config value as a string """ path: str = ELIBConfig.config_sep_str.join(self._raw_path) if ELIBConfig.root_path: prefix = ELIBConfig.config_sep_str.join(ELIBConfig.root_path) path = ELIBConfig.config_sep_str...
:return: path of this config value as a string
Below is the the instruction that describes the task: ### Input: :return: path of this config value as a string ### Response: def path(self) -> str: """ :return: path of this config value as a string """ path: str = ELIBConfig.config_sep_str.join(self._raw_path) if ELIBConfi...
def get_function_signature(func): """ Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ... TypeError: Th...
Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ... TypeError: The argument must be a function object: None typ...
Below is the the instruction that describes the task: ### Input: Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ...
def build_node_data_bag(): """Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as the filename (LittleChef filenames ...
Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as the filename (LittleChef filenames should be fqdns) 'hostname...
Below is the the instruction that describes the task: ### Input: Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as ...
def check(self): """ Determine how long until the next scheduled time for a Task. Returns the number of seconds until the next scheduled time or zero if the task needs to be run immediately. If it's an hourly task and it's never been run, run it now. If it's a daily task ...
Determine how long until the next scheduled time for a Task. Returns the number of seconds until the next scheduled time or zero if the task needs to be run immediately. If it's an hourly task and it's never been run, run it now. If it's a daily task and it's never been run and the hour ...
Below is the the instruction that describes the task: ### Input: Determine how long until the next scheduled time for a Task. Returns the number of seconds until the next scheduled time or zero if the task needs to be run immediately. If it's an hourly task and it's never been run, run it no...
def user_provenance(self, document): # type: (ProvDocument) -> None """Add the user provenance.""" self.self_check() (username, fullname) = _whoami() if not self.full_name: self.full_name = fullname document.add_namespace(UUID) document.add_namespace(ORCID)...
Add the user provenance.
Below is the the instruction that describes the task: ### Input: Add the user provenance. ### Response: def user_provenance(self, document): # type: (ProvDocument) -> None """Add the user provenance.""" self.self_check() (username, fullname) = _whoami() if not self.full_name: ...
def must_be_true(self, constraints, expression) -> bool: """Check if expression is True and that it can not be False with current constraints""" solutions = self.get_all_values(constraints, expression, maxcnt=2, silent=True) return solutions == [True]
Check if expression is True and that it can not be False with current constraints
Below is the the instruction that describes the task: ### Input: Check if expression is True and that it can not be False with current constraints ### Response: def must_be_true(self, constraints, expression) -> bool: """Check if expression is True and that it can not be False with current constraints""" ...
def is_running(self): """ Return true if the node is running """ self.__update_status() return self.status == Status.UP or self.status == Status.DECOMMISSIONED
Return true if the node is running
Below is the the instruction that describes the task: ### Input: Return true if the node is running ### Response: def is_running(self): """ Return true if the node is running """ self.__update_status() return self.status == Status.UP or self.status == Status.DECOMMISSIONED
def _add_status(scheduling_block): """This function adds status fields to all the section in the scheduling block instance""" scheduling_block['status'] = "created" for block in scheduling_block: if isinstance(scheduling_block[block], list): for field in sched...
This function adds status fields to all the section in the scheduling block instance
Below is the the instruction that describes the task: ### Input: This function adds status fields to all the section in the scheduling block instance ### Response: def _add_status(scheduling_block): """This function adds status fields to all the section in the scheduling block instance""" ...
def clear_cluster(name): ''' Clears accumulated statistics on all nodes in the cluster. .. code-block:: yaml clear_ats_cluster: trafficserver.clear_cluster ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __opts__['te...
Clears accumulated statistics on all nodes in the cluster. .. code-block:: yaml clear_ats_cluster: trafficserver.clear_cluster
Below is the the instruction that describes the task: ### Input: Clears accumulated statistics on all nodes in the cluster. .. code-block:: yaml clear_ats_cluster: trafficserver.clear_cluster ### Response: def clear_cluster(name): ''' Clears accumulated statistics on all nodes in th...
def promote_pipeline(conf, args): """Export a pipeline from a lower environment and import into higher environment.""" src = conf.config['instances'][args.src_instance] src_url = api.build_pipeline_url(build_instance_url(src)) src_auth = tuple([conf.creds['instances'][args.src_instance]['user'], conf.cr...
Export a pipeline from a lower environment and import into higher environment.
Below is the the instruction that describes the task: ### Input: Export a pipeline from a lower environment and import into higher environment. ### Response: def promote_pipeline(conf, args): """Export a pipeline from a lower environment and import into higher environment.""" src = conf.config['instances']...
def find_dates(text, source=False, index=False, strict=False, base_date=None): """ Extract datetime strings from text :param text: A string that contains one or more natural language or literal datetime strings :type text: str|unicode :param source: Return the original strin...
Extract datetime strings from text :param text: A string that contains one or more natural language or literal datetime strings :type text: str|unicode :param source: Return the original string segment :type source: boolean :param index: Return the indices where the ...
Below is the the instruction that describes the task: ### Input: Extract datetime strings from text :param text: A string that contains one or more natural language or literal datetime strings :type text: str|unicode :param source: Return the original string segment :type so...
def set_title(title, mode=0): ''' Set the title of the terminal window/tab/icon. Arguments: title: str mode: | 0 | 'both' - Set icon/taskbar and window/tab title | 1 | 'icon' - Set only icon/taskbar title | 2 | 'title' - Set only window/t...
Set the title of the terminal window/tab/icon. Arguments: title: str mode: | 0 | 'both' - Set icon/taskbar and window/tab title | 1 | 'icon' - Set only icon/taskbar title | 2 | 'title' - Set only window/tab title
Below is the the instruction that describes the task: ### Input: Set the title of the terminal window/tab/icon. Arguments: title: str mode: | 0 | 'both' - Set icon/taskbar and window/tab title | 1 | 'icon' - Set only icon/taskbar title | 2...
def _compute_magnitude_term(self, C, rup): """ This computes the term f1 equation 8 Drouet & Cotton (2015) """ return C['c2'] * (rup.mag - 8.0) + C['c3'] * (rup.mag - 8.0) ** 2
This computes the term f1 equation 8 Drouet & Cotton (2015)
Below is the the instruction that describes the task: ### Input: This computes the term f1 equation 8 Drouet & Cotton (2015) ### Response: def _compute_magnitude_term(self, C, rup): """ This computes the term f1 equation 8 Drouet & Cotton (2015) """ return C['c2'] * (rup.mag - 8.0) ...
def _function(self): """ This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ """ # some generic function import time import random self.data['random data...
This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__
Below is the the instruction that describes the task: ### Input: This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ ### Response: def _function(self): """ This is the actual function that ...
def liftover(args): """ %prog liftover blastfile anchorfile [options] Typical use for this program is given a list of anchors (syntennic genes), choose from the blastfile the pairs that are close to the anchors. Anchorfile has the following format, each row defines a pair. geneA geneB ...
%prog liftover blastfile anchorfile [options] Typical use for this program is given a list of anchors (syntennic genes), choose from the blastfile the pairs that are close to the anchors. Anchorfile has the following format, each row defines a pair. geneA geneB geneC geneD
Below is the the instruction that describes the task: ### Input: %prog liftover blastfile anchorfile [options] Typical use for this program is given a list of anchors (syntennic genes), choose from the blastfile the pairs that are close to the anchors. Anchorfile has the following format, each row def...
def _convert_bundle(bundle): """ Converts ambry bundle to dict ready to send to CKAN API. Args: bundle (ambry.bundle.Bundle): bundle to convert. Returns: dict: dict to send to CKAN to create dataset. See http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.package_creat...
Converts ambry bundle to dict ready to send to CKAN API. Args: bundle (ambry.bundle.Bundle): bundle to convert. Returns: dict: dict to send to CKAN to create dataset. See http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.package_create
Below is the the instruction that describes the task: ### Input: Converts ambry bundle to dict ready to send to CKAN API. Args: bundle (ambry.bundle.Bundle): bundle to convert. Returns: dict: dict to send to CKAN to create dataset. See http://docs.ckan.org/en/latest/api/#ckan.l...
def sendNotification(snmpDispatcher, authData, transportTarget, notifyType, *varBinds, **options): """Creates a generator to send SNMP notification. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4.2.6`). The...
Creates a generator to send SNMP notification. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4.2.6`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ...
Below is the the instruction that describes the task: ### Input: Creates a generator to send SNMP notification. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4.2.6`). The iterator yields :py:class:`asyncio.Future` which gets don...
def add_constraint(self, name, coefficients={}, ub=0): """ Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to linear coefficients. The constraint can only have an upper bound. To make a constraint with a lower bound, multiply all coe...
Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to linear coefficients. The constraint can only have an upper bound. To make a constraint with a lower bound, multiply all coefficients by -1.
Below is the the instruction that describes the task: ### Input: Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to linear coefficients. The constraint can only have an upper bound. To make a constraint with a lower bound, multiply all coefficie...
def NetFxSdkDir(self): """ Microsoft .NET Framework SDK directory. """ for ver in self.NetFxSdkVersion: loc = os.path.join(self.ri.netfx_sdk, ver) sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder') if sdkdir: break return sd...
Microsoft .NET Framework SDK directory.
Below is the the instruction that describes the task: ### Input: Microsoft .NET Framework SDK directory. ### Response: def NetFxSdkDir(self): """ Microsoft .NET Framework SDK directory. """ for ver in self.NetFxSdkVersion: loc = os.path.join(self.ri.netfx_sdk, ver) ...
def run_job(self, job=None): """Run a job, either passed in or from the queue. A job is a tuple of function and optional args. Keyword arguments can be passed via use of functools.partial. The job should return a string that should be sent by the gateway protocol. The function will ...
Run a job, either passed in or from the queue. A job is a tuple of function and optional args. Keyword arguments can be passed via use of functools.partial. The job should return a string that should be sent by the gateway protocol. The function will be called with the arguments and the...
Below is the the instruction that describes the task: ### Input: Run a job, either passed in or from the queue. A job is a tuple of function and optional args. Keyword arguments can be passed via use of functools.partial. The job should return a string that should be sent by the gateway pro...
def cli(env, account_id, content_url): """Cache one or more files on all edge nodes.""" manager = SoftLayer.CDNManager(env.client) manager.load_content(account_id, content_url)
Cache one or more files on all edge nodes.
Below is the the instruction that describes the task: ### Input: Cache one or more files on all edge nodes. ### Response: def cli(env, account_id, content_url): """Cache one or more files on all edge nodes.""" manager = SoftLayer.CDNManager(env.client) manager.load_content(account_id, content_url)
def select_k_best(self, k): """Selects k best features in dataset :param k: features to select :return: k best features """ x_new = SelectKBest(chi2, k=k).fit_transform(self.x_train, self.y_train) return x_new
Selects k best features in dataset :param k: features to select :return: k best features
Below is the the instruction that describes the task: ### Input: Selects k best features in dataset :param k: features to select :return: k best features ### Response: def select_k_best(self, k): """Selects k best features in dataset :param k: features to select :return: k...
def show_form_for_method(self, view, method, request, obj): """ Returns True if a form should be shown for this method. """ if method not in view.allowed_methods: return # Not a valid method try: view.check_permissions(request) if obj is not ...
Returns True if a form should be shown for this method.
Below is the the instruction that describes the task: ### Input: Returns True if a form should be shown for this method. ### Response: def show_form_for_method(self, view, method, request, obj): """ Returns True if a form should be shown for this method. """ if method not in view.al...
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_arguments) < 2: return self.print_help() audio_file_path = self.actual_arguments[0] mode = self.actual_arguments[1] if mode...
Perform command and return the appropriate exit code. :rtype: int
Below is the the instruction that describes the task: ### Input: Perform command and return the appropriate exit code. :rtype: int ### Response: def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_...
def fetch(self, cluster, metric, topology, component, instance, timerange, environ=None): ''' :param cluster: :param metric: :param topology: :param component: :param instance: :param timerange: :param environ: :return: ''' components = [component] if component != "*" else (y...
:param cluster: :param metric: :param topology: :param component: :param instance: :param timerange: :param environ: :return:
Below is the the instruction that describes the task: ### Input: :param cluster: :param metric: :param topology: :param component: :param instance: :param timerange: :param environ: :return: ### Response: def fetch(self, cluster, metric, topology, component, instance, timerange, environ...
def profiler_set_config(mode='symbolic', filename='profile.json'): """Set up the configure of profiler (Deprecated). Parameters ---------- mode : string, optional Indicates whether to enable the profiler, can be 'symbolic', or 'all'. Defaults to `symbolic`. filename : string, option...
Set up the configure of profiler (Deprecated). Parameters ---------- mode : string, optional Indicates whether to enable the profiler, can be 'symbolic', or 'all'. Defaults to `symbolic`. filename : string, optional The name of output trace file. Defaults to 'profile.json'.
Below is the the instruction that describes the task: ### Input: Set up the configure of profiler (Deprecated). Parameters ---------- mode : string, optional Indicates whether to enable the profiler, can be 'symbolic', or 'all'. Defaults to `symbolic`. filename : string, optional ...
def showbox(self, force_rerun=False): """Create the dummy PDB box around the selected spheres. Args: force_rerun (bool): If method should be rerun even if output file exists """ log.debug('{}: running box maker...'.format(self.id)) if not self.sphsel_path: ...
Create the dummy PDB box around the selected spheres. Args: force_rerun (bool): If method should be rerun even if output file exists
Below is the the instruction that describes the task: ### Input: Create the dummy PDB box around the selected spheres. Args: force_rerun (bool): If method should be rerun even if output file exists ### Response: def showbox(self, force_rerun=False): """Create the dummy PDB box around t...
def filter_stopwords(phrase): """Filter out stop words and return as a list of words""" if not isinstance(phrase, list): phrase = phrase.split() stopwords = ['the', 'a', 'in', 'to'] return [word.lower() for word in phrase if word.lower() not in stopwords]
Filter out stop words and return as a list of words
Below is the the instruction that describes the task: ### Input: Filter out stop words and return as a list of words ### Response: def filter_stopwords(phrase): """Filter out stop words and return as a list of words""" if not isinstance(phrase, list): phrase = phrase.split() stopwords = ['the'...
def multipublish(self, topic, messages): """Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish """ self.send(nsq.multipublish(topic, messages))
Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish
Below is the the instruction that describes the task: ### Input: Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish ### Response: def multipublish(self, topic, messages): """Publish an ite...
def clusterstatus(self): """ Returns a slightly slimmed down version of the clusterstatus api command. It also gets count of documents in each shard on each replica and returns it as doc_count key for each replica. """ res = self.cluster_status_raw() cluster = res['clu...
Returns a slightly slimmed down version of the clusterstatus api command. It also gets count of documents in each shard on each replica and returns it as doc_count key for each replica.
Below is the the instruction that describes the task: ### Input: Returns a slightly slimmed down version of the clusterstatus api command. It also gets count of documents in each shard on each replica and returns it as doc_count key for each replica. ### Response: def clusterstatus(self): """ ...
def compute_results(self, voting_method, votes=None, winners=1, **kwargs): """Compute voting results to decide the winner(s) from the :attr:`votes`. The votes should have been made for the current :attr:`~creamas.vote.VoteOrganizer.candidates`. :param voting_method: ...
Compute voting results to decide the winner(s) from the :attr:`votes`. The votes should have been made for the current :attr:`~creamas.vote.VoteOrganizer.candidates`. :param voting_method: A function which computes the results from the votes. Should accept at le...
Below is the the instruction that describes the task: ### Input: Compute voting results to decide the winner(s) from the :attr:`votes`. The votes should have been made for the current :attr:`~creamas.vote.VoteOrganizer.candidates`. :param voting_method: A function which...
def setLateralAlignment(self, vehID, align): """setLateralAlignment(string, string) -> None Sets the preferred lateral alignment for this vehicle. """ self._connection._sendStringCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_LATALIGNMENT, vehID, align)
setLateralAlignment(string, string) -> None Sets the preferred lateral alignment for this vehicle.
Below is the the instruction that describes the task: ### Input: setLateralAlignment(string, string) -> None Sets the preferred lateral alignment for this vehicle. ### Response: def setLateralAlignment(self, vehID, align): """setLateralAlignment(string, string) -> None Sets the preferred ...
def from_pandas_df(df, i_variables, d_variable, alpha_merge=0.05, max_depth=2, min_parent_node_size=30, min_child_node_size=30, split_threshold=0, weight=None, dep_variable_type='categorical'): """ Helper method to pre-process a pandas data frame in order to...
Helper method to pre-process a pandas data frame in order to run CHAID analysis Parameters ---------- df : pandas.DataFrame the dataframe with the dependent and independent variables in which to slice from i_variables : dict dict of instance v...
Below is the the instruction that describes the task: ### Input: Helper method to pre-process a pandas data frame in order to run CHAID analysis Parameters ---------- df : pandas.DataFrame the dataframe with the dependent and independent variables in which to...
def get_strategic_global_state(self) -> GlobalState: """ Returns the first uncovered global state in the work list if it exists, otherwise super_strategy.get_strategic_global_state() is returned. """ for global_state in self.work_list: if not self._is_covered(global_s...
Returns the first uncovered global state in the work list if it exists, otherwise super_strategy.get_strategic_global_state() is returned.
Below is the the instruction that describes the task: ### Input: Returns the first uncovered global state in the work list if it exists, otherwise super_strategy.get_strategic_global_state() is returned. ### Response: def get_strategic_global_state(self) -> GlobalState: """ Returns the firs...
def queue(self, project): """ Get a queue of notifications Use it with Python with """ queue = NotificationQueue() self._listeners.setdefault(project.id, set()) self._listeners[project.id].add(queue) yield queue self._listeners[project.id].remove(...
Get a queue of notifications Use it with Python with
Below is the the instruction that describes the task: ### Input: Get a queue of notifications Use it with Python with ### Response: def queue(self, project): """ Get a queue of notifications Use it with Python with """ queue = NotificationQueue() self._list...
def get_panels(config): """Execute the panels phase :param config: a Mordred config object """ task = TaskPanels(config) task.execute() task = TaskPanelsMenu(config) task.execute() logging.info("Panels creation finished!")
Execute the panels phase :param config: a Mordred config object
Below is the the instruction that describes the task: ### Input: Execute the panels phase :param config: a Mordred config object ### Response: def get_panels(config): """Execute the panels phase :param config: a Mordred config object """ task = TaskPanels(config) task.execute() task...
def _define_fixed(wrapped, callable_): """For the callable see how many positional parameters are required""" is_class = inspect.isclass(wrapped) style = callable_._splpy_style if hasattr(callable_, '_splpy_style') else wrapped._splpy_style if style == 'dictionary': return -1 fixed_count =...
For the callable see how many positional parameters are required
Below is the the instruction that describes the task: ### Input: For the callable see how many positional parameters are required ### Response: def _define_fixed(wrapped, callable_): """For the callable see how many positional parameters are required""" is_class = inspect.isclass(wrapped) style = calla...
def _needs_hiding(mod_name): """ >>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False ...
>>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False >>> _needs_hiding('Cython') True
Below is the the instruction that describes the task: ### Input: >>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _ne...
def build_intent(self, intent_name): """Builds an Intent object of the given name""" # TODO: contexts is_fallback = self.assist._intent_fallbacks[intent_name] contexts = self.assist._required_contexts[intent_name] events = self.assist._intent_events[intent_name] new_inten...
Builds an Intent object of the given name
Below is the the instruction that describes the task: ### Input: Builds an Intent object of the given name ### Response: def build_intent(self, intent_name): """Builds an Intent object of the given name""" # TODO: contexts is_fallback = self.assist._intent_fallbacks[intent_name] con...
def int(self, item, default=None): """ Return value of key as an int :param item: key of value to transform :param default: value to return if item does not exist :return: int of value """ try: item = self.__getattr__(item) except AttributeError as er...
Return value of key as an int :param item: key of value to transform :param default: value to return if item does not exist :return: int of value
Below is the the instruction that describes the task: ### Input: Return value of key as an int :param item: key of value to transform :param default: value to return if item does not exist :return: int of value ### Response: def int(self, item, default=None): """ Return value of ke...
def _valid_distaxis(shapes, ax): """`ax` is a valid candidate for a distributed axis if the given subarray shapes are all the same when ignoring axis `ax`""" compare_shapes = np.vstack(shapes) if ax < compare_shapes.shape[1]: compare_shapes[:, ax] = -1 return np.count...
`ax` is a valid candidate for a distributed axis if the given subarray shapes are all the same when ignoring axis `ax`
Below is the the instruction that describes the task: ### Input: `ax` is a valid candidate for a distributed axis if the given subarray shapes are all the same when ignoring axis `ax` ### Response: def _valid_distaxis(shapes, ax): """`ax` is a valid candidate for a distributed axis if the given ...
def parse(self, output): """ Find stems for a given text. """ output = self._get_lines_with_stems(output) words = self._make_unique(output) return self._parse_for_simple_stems(words)
Find stems for a given text.
Below is the the instruction that describes the task: ### Input: Find stems for a given text. ### Response: def parse(self, output): """ Find stems for a given text. """ output = self._get_lines_with_stems(output) words = self._make_unique(output) return self._parse_...
def setY(self,Y): """ set pheno """ if Y.ndim==1: Y = Y[:,SP.newaxis] self.n,self.t = Y.shape self.Y = Y self.Y_has_changed = True
set pheno
Below is the the instruction that describes the task: ### Input: set pheno ### Response: def setY(self,Y): """ set pheno """ if Y.ndim==1: Y = Y[:,SP.newaxis] self.n,self.t = Y.shape self.Y = Y self.Y_has_changed = True
def handle_import(self, options): """ Gets posts from Blogger. """ blog_id = options.get("blog_id") if blog_id is None: raise CommandError("Usage is import_blogger %s" % self.args) try: from gdata import service except ImportError: ...
Gets posts from Blogger.
Below is the the instruction that describes the task: ### Input: Gets posts from Blogger. ### Response: def handle_import(self, options): """ Gets posts from Blogger. """ blog_id = options.get("blog_id") if blog_id is None: raise CommandError("Usage is import_bl...
def sr(self, multi=0): """sr([multi=1]) -> (SndRcvList, PacketList) Matches packets in the list and return ( (matched couples), (unmatched packets) )""" # noqa: E501 remain = self.res[:] sr = [] i = 0 while i < len(remain): s = remain[i] j = i ...
sr([multi=1]) -> (SndRcvList, PacketList) Matches packets in the list and return ( (matched couples), (unmatched packets) )
Below is the the instruction that describes the task: ### Input: sr([multi=1]) -> (SndRcvList, PacketList) Matches packets in the list and return ( (matched couples), (unmatched packets) ) ### Response: def sr(self, multi=0): """sr([multi=1]) -> (SndRcvList, PacketList) Matches packets in t...
def serve(application, host='127.0.0.1', port=8080, socket=None, **options): """Basic FastCGI support via flup. This web server has many, many options. Please see the Flup project documentation for details. """ # Allow either on-disk socket (recommended) or TCP/IP socket use. if not socket: bindAddress = (ho...
Basic FastCGI support via flup. This web server has many, many options. Please see the Flup project documentation for details.
Below is the the instruction that describes the task: ### Input: Basic FastCGI support via flup. This web server has many, many options. Please see the Flup project documentation for details. ### Response: def serve(application, host='127.0.0.1', port=8080, socket=None, **options): """Basic FastCGI support via...
def _rest_op(self, operation, suburi, request_headers, request_body): """Generic REST Operation handler.""" url = urlparse.urlparse('https://' + self.host + suburi) # Used for logging on redirection error. start_url = url.geturl() LOG.debug(self._("%(operation)s %(url)s"), ...
Generic REST Operation handler.
Below is the the instruction that describes the task: ### Input: Generic REST Operation handler. ### Response: def _rest_op(self, operation, suburi, request_headers, request_body): """Generic REST Operation handler.""" url = urlparse.urlparse('https://' + self.host + suburi) # Used for log...
def __get_remote_index(self): """ Gets the index of news crawl files from commoncrawl.org and returns an array of names :return: """ # cleanup subprocess.getoutput("rm tmpaws.txt") # get the remote info cmd = "aws s3 ls --recursive s3://commoncrawl/crawl-d...
Gets the index of news crawl files from commoncrawl.org and returns an array of names :return:
Below is the the instruction that describes the task: ### Input: Gets the index of news crawl files from commoncrawl.org and returns an array of names :return: ### Response: def __get_remote_index(self): """ Gets the index of news crawl files from commoncrawl.org and returns an array of nam...
def to_hsl(self): ''' Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB` ''' from .hsl import HSL # prevent circular import h, l, s = colorsys.rgb_to_hls(float(self.r)/255, float(self.g)/255, float(self.b)/255) retur...
Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB`
Below is the the instruction that describes the task: ### Input: Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB` ### Response: def to_hsl(self): ''' Return a corresponding HSL color for this RGB color. Returns: :class:`~...
def get_vnetwork_dvs_output_vnetwork_dvs_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_dvs = ET.Element("get_vnetwork_dvs") config = get_vnetwork_dvs output = ET.SubElement(get_vnetwork_dvs, "output") vnetwork_dvs = ET...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_vnetwork_dvs_output_vnetwork_dvs_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_dvs = ET.Element("get_vnetwork_dvs") config...
def skip_http_error(statuses): ''' A decorator to wrap with try..except to swallow specific HTTP errors. @skip_http_error((404, 503)) def fetch(): ... ''' assert isinstance(statuses, tuple) def decorator(func): def wrapper(*args, **kwargs): try: ...
A decorator to wrap with try..except to swallow specific HTTP errors. @skip_http_error((404, 503)) def fetch(): ...
Below is the the instruction that describes the task: ### Input: A decorator to wrap with try..except to swallow specific HTTP errors. @skip_http_error((404, 503)) def fetch(): ... ### Response: def skip_http_error(statuses): ''' A decorator to wrap with try..except to swallow spec...
def add_sms_spec_to_request(self, req, federation='', loes=None, context=''): """ Update a request with signed metadata statements. :param req: The request :param federation: Federation Operator ID :param loes: List of :py:class:`fedoidc....
Update a request with signed metadata statements. :param req: The request :param federation: Federation Operator ID :param loes: List of :py:class:`fedoidc.operator.LessOrEqual` instances :param context: :return: The updated request
Below is the the instruction that describes the task: ### Input: Update a request with signed metadata statements. :param req: The request :param federation: Federation Operator ID :param loes: List of :py:class:`fedoidc.operator.LessOrEqual` instances :param context: ...
def __run(self): """ Internal function that is run in a separate thread. Do not call directly. """ self.interval_start = time.time() while self.status != STOPPED: if self.status == RUNNING: self.current_interval_duration = time.time() - self.interval_start # If max_duration is set, stop the clock if...
Internal function that is run in a separate thread. Do not call directly.
Below is the the instruction that describes the task: ### Input: Internal function that is run in a separate thread. Do not call directly. ### Response: def __run(self): """ Internal function that is run in a separate thread. Do not call directly. """ self.interval_start = time.time() while self.status...
def is_authorized(hijack, hijacked): ''' Evaluates the authorization check specified in settings ''' authorization_check = import_string(hijack_settings.HIJACK_AUTHORIZATION_CHECK) return authorization_check(hijack, hijacked)
Evaluates the authorization check specified in settings
Below is the the instruction that describes the task: ### Input: Evaluates the authorization check specified in settings ### Response: def is_authorized(hijack, hijacked): ''' Evaluates the authorization check specified in settings ''' authorization_check = import_string(hijack_settings.HIJACK_AUTH...
def peer_exchange(self, peer_host, peer_port): """ Exchange peers. Add the given peer to the list of new peers to consider. Return the list of healthy peers """ # get peers peer_list = atlas_get_live_neighbors( "%s:%s" % (peer_host, peer_port) ) if len(pee...
Exchange peers. Add the given peer to the list of new peers to consider. Return the list of healthy peers
Below is the the instruction that describes the task: ### Input: Exchange peers. Add the given peer to the list of new peers to consider. Return the list of healthy peers ### Response: def peer_exchange(self, peer_host, peer_port): """ Exchange peers. Add the given peer to t...
def _set_igp_sync(self, v, load=False): """ Setter method for igp_sync, mapped from YANG variable /mpls_state/rsvp/igp_sync (container) If this variable is read-only (config: false) in the source YANG file, then _set_igp_sync is considered as a private method. Backends looking to populate this varia...
Setter method for igp_sync, mapped from YANG variable /mpls_state/rsvp/igp_sync (container) If this variable is read-only (config: false) in the source YANG file, then _set_igp_sync is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_igp_sy...
Below is the the instruction that describes the task: ### Input: Setter method for igp_sync, mapped from YANG variable /mpls_state/rsvp/igp_sync (container) If this variable is read-only (config: false) in the source YANG file, then _set_igp_sync is considered as a private method. Backends looking to po...
def readline(self, size=None): """Reads a single line of text. The functions reads one entire line from the file-like object. A trailing end-of-line indicator (newline by default) is kept in the byte string (but may be absent when a file ends with an incomplete line). An empty byte string is return...
Reads a single line of text. The functions reads one entire line from the file-like object. A trailing end-of-line indicator (newline by default) is kept in the byte string (but may be absent when a file ends with an incomplete line). An empty byte string is returned only when end-of-file is encountere...
Below is the the instruction that describes the task: ### Input: Reads a single line of text. The functions reads one entire line from the file-like object. A trailing end-of-line indicator (newline by default) is kept in the byte string (but may be absent when a file ends with an incomplete line). An ...
def points_from_x0y0x1y1(xyxy): """ Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1] """ x0 = xyxy[0] y0 = xyxy[1] x1 = xyxy[2] y1 = xyxy[3] return "%s,%s %s,%s %s,%s %s,%s" % ( x0, y0, x1, y0, x1, y1, x0, y1 )
Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1]
Below is the the instruction that describes the task: ### Input: Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1] ### Response: def points_from_x0y0x1y1(xyxy): """ Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1] """ ...
def charsUntil(self, characters, opposite=False): """ Returns a string of characters from the stream up to but not including any character in 'characters' or EOF. 'characters' must be a container that supports the 'in' method and iteration over its characters. """ # Use ...
Returns a string of characters from the stream up to but not including any character in 'characters' or EOF. 'characters' must be a container that supports the 'in' method and iteration over its characters.
Below is the the instruction that describes the task: ### Input: Returns a string of characters from the stream up to but not including any character in 'characters' or EOF. 'characters' must be a container that supports the 'in' method and iteration over its characters. ### Response: def c...
def createrawtransaction(self, inputs, outputs): """[{"txid":input_txid,"vout":0}, ...], {recv_addr: amount, change: amount, ...}""" if not isinstance(outputs, dict): raise TypeError("outputs variable must be a dictionary") if not isinstance(inputs, list): raise TypeError...
[{"txid":input_txid,"vout":0}, ...], {recv_addr: amount, change: amount, ...}
Below is the the instruction that describes the task: ### Input: [{"txid":input_txid,"vout":0}, ...], {recv_addr: amount, change: amount, ...} ### Response: def createrawtransaction(self, inputs, outputs): """[{"txid":input_txid,"vout":0}, ...], {recv_addr: amount, change: amount, ...}""" if not is...
def endElementNS(self, name, qname): """ End a previously started element. `name` must be a ``(namespace_uri, localname)`` tuple and `qname` is ignored. """ if self._ns_prefixes_floating_out: raise RuntimeError("namespace prefix has not been closed") if self....
End a previously started element. `name` must be a ``(namespace_uri, localname)`` tuple and `qname` is ignored.
Below is the the instruction that describes the task: ### Input: End a previously started element. `name` must be a ``(namespace_uri, localname)`` tuple and `qname` is ignored. ### Response: def endElementNS(self, name, qname): """ End a previously started element. `name` must be a ``(names...
def load_python_object(name): """ Loads a python module from string """ logger = getLoggerWithNullHandler('commando.load_python_object') (module_name, _, object_name) = name.rpartition(".") if module_name == '': (module_name, object_name) = (object_name, module_name) try: log...
Loads a python module from string
Below is the the instruction that describes the task: ### Input: Loads a python module from string ### Response: def load_python_object(name): """ Loads a python module from string """ logger = getLoggerWithNullHandler('commando.load_python_object') (module_name, _, object_name) = name.rpartiti...
def on_epoch_end(self, epoch: int, smooth_loss: Tensor, last_metrics: MetricsList, **kwargs: Any) -> bool: "Add a line with `epoch` number, `smooth_loss` and `last_metrics`." last_metrics = ifnone(last_metrics, []) stats = [str(stat) if isinstance(stat, int) else '#na#' if stat is None else f'{s...
Add a line with `epoch` number, `smooth_loss` and `last_metrics`.
Below is the the instruction that describes the task: ### Input: Add a line with `epoch` number, `smooth_loss` and `last_metrics`. ### Response: def on_epoch_end(self, epoch: int, smooth_loss: Tensor, last_metrics: MetricsList, **kwargs: Any) -> bool: "Add a line with `epoch` number, `smooth_loss` and `las...
def _check_diff(changes): ''' Check the diff for signs of incorrect argument handling in previous releases, as discovered here: https://github.com/saltstack/salt/pull/39996#issuecomment-288025200 ''' for conf_dict in changes: if conf_dict == 'Networks': continue for ...
Check the diff for signs of incorrect argument handling in previous releases, as discovered here: https://github.com/saltstack/salt/pull/39996#issuecomment-288025200
Below is the the instruction that describes the task: ### Input: Check the diff for signs of incorrect argument handling in previous releases, as discovered here: https://github.com/saltstack/salt/pull/39996#issuecomment-288025200 ### Response: def _check_diff(changes): ''' Check the diff for sign...
def resolution_order(lang, override=None): """ Return order of languages which should be checked for parameter language. First is always the parameter language, later are fallback languages. Override parameter has priority over FALLBACK_LANGUAGES. """ if not settings.ENABLE_FALLBACKS: re...
Return order of languages which should be checked for parameter language. First is always the parameter language, later are fallback languages. Override parameter has priority over FALLBACK_LANGUAGES.
Below is the the instruction that describes the task: ### Input: Return order of languages which should be checked for parameter language. First is always the parameter language, later are fallback languages. Override parameter has priority over FALLBACK_LANGUAGES. ### Response: def resolution_order(lang, ...
def _get_bin_width(stdev, count): """Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501 """ w = int(round((3.5 * stdev) / (count ** (1.0 / 3)))) if w: return w else: return 1
Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501
Below is the the instruction that describes the task: ### Input: Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501 ### Response: def _get_bin_width(stdev, count): """Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501 ...
def _drawContents(self, reason=None, initiator=None): """ Converts the (zero-dimensional) sliced array to string and puts it in the text editor. The reason and initiator parameters are ignored. See AbstractInspector.updateContents for their description. """ logger.debug(...
Converts the (zero-dimensional) sliced array to string and puts it in the text editor. The reason and initiator parameters are ignored. See AbstractInspector.updateContents for their description.
Below is the the instruction that describes the task: ### Input: Converts the (zero-dimensional) sliced array to string and puts it in the text editor. The reason and initiator parameters are ignored. See AbstractInspector.updateContents for their description. ### Response: def _drawConten...
def db_set_indexing(cls, is_indexing, impl, working_dir): """ Set lockfile path as to whether or not the system is indexing. NOT THREAD SAFE, USE ONLY FOR CRASH DETECTION. """ indexing_lockfile_path = config.get_lockfile_filename(impl, working_dir) if is_indexing: ...
Set lockfile path as to whether or not the system is indexing. NOT THREAD SAFE, USE ONLY FOR CRASH DETECTION.
Below is the the instruction that describes the task: ### Input: Set lockfile path as to whether or not the system is indexing. NOT THREAD SAFE, USE ONLY FOR CRASH DETECTION. ### Response: def db_set_indexing(cls, is_indexing, impl, working_dir): """ Set lockfile path as to whether or not t...
def unix_socket(sock=None, socket_name='tmp.socket', close=True): """Create temporary unix socket. Creates and binds a temporary unix socket that will be closed and removed on exit. :param sock: If not `None`, will not created a new unix socket, but bind the passed in one instead. ...
Create temporary unix socket. Creates and binds a temporary unix socket that will be closed and removed on exit. :param sock: If not `None`, will not created a new unix socket, but bind the passed in one instead. :param socket_name: The name for the socket file (will be placed in a ...
Below is the the instruction that describes the task: ### Input: Create temporary unix socket. Creates and binds a temporary unix socket that will be closed and removed on exit. :param sock: If not `None`, will not created a new unix socket, but bind the passed in one instead. :pa...
def strip_bewit(url): """ Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str """ m = re.search('[?&]bewit=([^&]+)', url) if not m: rai...
Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str
Below is the the instruction that describes the task: ### Input: Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str ### Response: def strip_bewit(url): "...
def _save_config(jira_url, username, password, error_reporting): """ Saves the username and password to the config """ # Delete what is there before we re-write. New user means new everything os.path.exists(_config) and os.remove(_config) config = ConfigParser.SafeConfigParser() config.read...
Saves the username and password to the config
Below is the the instruction that describes the task: ### Input: Saves the username and password to the config ### Response: def _save_config(jira_url, username, password, error_reporting): """ Saves the username and password to the config """ # Delete what is there before we re-write. New user mea...
def draw_figure(self,data_for_color=None, data_for_size=None, data_for_clouds=None, rot_bonds=None, color_for_clouds="Blues", color_type_color="viridis"): """ Draws molecule through Molecule() and then puts the final figure together with Figure(). """ self.molecule = Molecule(sel...
Draws molecule through Molecule() and then puts the final figure together with Figure().
Below is the the instruction that describes the task: ### Input: Draws molecule through Molecule() and then puts the final figure together with Figure(). ### Response: def draw_figure(self,data_for_color=None, data_for_size=None, data_for_clouds=None, rot_bonds=None, color_for_clouds="Blues", color_type_co...
def query(self, query_type, query=None): """Run the given query on the connection (POST request to /query)""" return self.handleresult(self.r.post(urljoin(self.url + "query/", query_type), data=json.dumps(q...
Run the given query on the connection (POST request to /query)
Below is the the instruction that describes the task: ### Input: Run the given query on the connection (POST request to /query) ### Response: def query(self, query_type, query=None): """Run the given query on the connection (POST request to /query)""" return self.handleresult(self.r.post(urljoin(se...
def create_network(self): """Create a new network by reading the configuration file.""" class_ = getattr(networks, self.network_class) return class_(max_size=self.quorum)
Create a new network by reading the configuration file.
Below is the the instruction that describes the task: ### Input: Create a new network by reading the configuration file. ### Response: def create_network(self): """Create a new network by reading the configuration file.""" class_ = getattr(networks, self.network_class) return class_(max_siz...
def matrix_str(p, decimal_places=2, print_zero=True, label_columns=False): '''Pretty-print the matrix.''' return '[{0}]'.format("\n ".join([(str(i) if label_columns else '') + vector_str(a, decimal_places, print_zero) for i, a in enumerate(p)]))
Pretty-print the matrix.
Below is the the instruction that describes the task: ### Input: Pretty-print the matrix. ### Response: def matrix_str(p, decimal_places=2, print_zero=True, label_columns=False): '''Pretty-print the matrix.''' return '[{0}]'.format("\n ".join([(str(i) if label_columns else '') + vector_str(a, decimal_plac...
def get_parens(line,retlevel=0,retblevel=0): """ By default akes a string starting with an open parenthesis and returns the portion of the string going to the corresponding close parenthesis. If retlevel != 0 then will return when that level (for parentheses) is reached. Same for retblevel. """ ...
By default akes a string starting with an open parenthesis and returns the portion of the string going to the corresponding close parenthesis. If retlevel != 0 then will return when that level (for parentheses) is reached. Same for retblevel.
Below is the the instruction that describes the task: ### Input: By default akes a string starting with an open parenthesis and returns the portion of the string going to the corresponding close parenthesis. If retlevel != 0 then will return when that level (for parentheses) is reached. Same for retblevel. ...
def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by vi...
Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibilit...
Below is the the instruction that describes the task: ### Input: Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provid...
def _find_error(vals): """Find the errors in the energy values. This function finds the errors in the enthalpys. Parameters ---------- vals : list of lists of floats Returns ------- err_vals : list of lists containing the errors. """ err_vals = [] for en in vals: ...
Find the errors in the energy values. This function finds the errors in the enthalpys. Parameters ---------- vals : list of lists of floats Returns ------- err_vals : list of lists containing the errors.
Below is the the instruction that describes the task: ### Input: Find the errors in the energy values. This function finds the errors in the enthalpys. Parameters ---------- vals : list of lists of floats Returns ------- err_vals : list of lists containing the errors. ### Response: d...
def k_means( X, n_clusters, init="k-means||", precompute_distances="auto", n_init=1, max_iter=300, verbose=False, tol=1e-4, random_state=None, copy_x=True, n_jobs=-1, algorithm="full", return_n_iter=False, oversampling_factor=2, init_max_iter=None, ): """K...
K-means algorithm for clustering Differences from scikit-learn: * init='k-means||' * oversampling_factor keyword * n_jobs=-1
Below is the the instruction that describes the task: ### Input: K-means algorithm for clustering Differences from scikit-learn: * init='k-means||' * oversampling_factor keyword * n_jobs=-1 ### Response: def k_means( X, n_clusters, init="k-means||", precompute_distances="auto", ...
def transform(self, program: moderngl.Program, buffer: moderngl.Buffer, mode=None, vertices=-1, first=0, instances=1): """ Transform vertices. Stores the output in a single buffer. Args: program: The ``moderngl.Program`` buffer: The ``moderngl.buffer`` ...
Transform vertices. Stores the output in a single buffer. Args: program: The ``moderngl.Program`` buffer: The ``moderngl.buffer`` to store the output Keyword Args: mode: Draw mode (for example ``moderngl.POINTS``) vertices (int): The number of vertices t...
Below is the the instruction that describes the task: ### Input: Transform vertices. Stores the output in a single buffer. Args: program: The ``moderngl.Program`` buffer: The ``moderngl.buffer`` to store the output Keyword Args: mode: Draw mode (for example ``mo...
def mpl_outside_legend(ax, **kwargs): """ Places a legend box outside a matplotlib Axes instance. """ box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.75, box.height]) # Put a legend to the right of the current axis ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)
Places a legend box outside a matplotlib Axes instance.
Below is the the instruction that describes the task: ### Input: Places a legend box outside a matplotlib Axes instance. ### Response: def mpl_outside_legend(ax, **kwargs): """ Places a legend box outside a matplotlib Axes instance. """ box = ax.get_position() ax.set_position([box.x0, box.y0, box.width...
def init_coords(cb, params): """ Initializes coordinates and zoom for first use. Loads coordinates from Mandelbrot-space. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :return: """ w = cb.wid...
Initializes coordinates and zoom for first use. Loads coordinates from Mandelbrot-space. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :return:
Below is the the instruction that describes the task: ### Input: Initializes coordinates and zoom for first use. Loads coordinates from Mandelbrot-space. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :re...
def glob7s(p, Input, flags): ''' /* VERSION OF GLOBE FOR LOWER ATMOSPHERE 10/26/99 */ ''' pset = 2.0 t = [0.0]*14 dr=1.72142E-2; dgtr=1.74533E-2; #/* confirm parameter set */ if (p[99]==0): # pragma: no cover p[99]=pset; #for j in range(14): #Already taken care of ...
/* VERSION OF GLOBE FOR LOWER ATMOSPHERE 10/26/99 */
Below is the the instruction that describes the task: ### Input: /* VERSION OF GLOBE FOR LOWER ATMOSPHERE 10/26/99 */ ### Response: def glob7s(p, Input, flags): ''' /* VERSION OF GLOBE FOR LOWER ATMOSPHERE 10/26/99 */ ''' pset = 2.0 t = [0.0]*14 dr=1.72142E-2; dgtr=1.74533E-2; #...
def isfile(path): """Test whether a path is a regular file""" try: st = os.stat(path) except os.error: return False return stat.S_ISREG(st.st_mode)
Test whether a path is a regular file
Below is the the instruction that describes the task: ### Input: Test whether a path is a regular file ### Response: def isfile(path): """Test whether a path is a regular file""" try: st = os.stat(path) except os.error: return False return stat.S_ISREG(st.st_mode)
def sync(self, json_obj=None): """ synchronize self from Ariane server according its id :return: """ LOGGER.debug("Container.sync") if json_obj is None: params = None if self.id is not None: params = SessionService.complete_transact...
synchronize self from Ariane server according its id :return:
Below is the the instruction that describes the task: ### Input: synchronize self from Ariane server according its id :return: ### Response: def sync(self, json_obj=None): """ synchronize self from Ariane server according its id :return: """ LOGGER.debug("Container.s...
def _iter_config_files(self): # type: () -> Iterable[Tuple[Kind, List[str]]] """Yields variant and configuration files associated with it. This should be treated like items of a dictionary. """ # SMELL: Move the conditions out of this function # environment variables ha...
Yields variant and configuration files associated with it. This should be treated like items of a dictionary.
Below is the the instruction that describes the task: ### Input: Yields variant and configuration files associated with it. This should be treated like items of a dictionary. ### Response: def _iter_config_files(self): # type: () -> Iterable[Tuple[Kind, List[str]]] """Yields variant and co...
def logstats(self): """ Print the node's current statistics to log. """ lines = [ "node {} current stats".format(self), "--------------------------------------------------------", "node inbox size : {}".format(len(self.nodeInBox)), ...
Print the node's current statistics to log.
Below is the the instruction that describes the task: ### Input: Print the node's current statistics to log. ### Response: def logstats(self): """ Print the node's current statistics to log. """ lines = [ "node {} current stats".format(self), "---------------...
def getUserName(self): """Return the authenticated user name (server side).""" if not self._server_side: return mech = self._authenticator.current_mech return mech.getUserName() if mech else None
Return the authenticated user name (server side).
Below is the the instruction that describes the task: ### Input: Return the authenticated user name (server side). ### Response: def getUserName(self): """Return the authenticated user name (server side).""" if not self._server_side: return mech = self._authenticator.current_mec...
def getfield(self, pkt, s): """ We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, zero lengths are always...
We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, zero lengths are always explicit.
Below is the the instruction that describes the task: ### Input: We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, ze...
def execute(prog, argv): """Execute whole program :param prog: program name :param argv: list: script arguments :return: """ if pathlib.Path(prog).parts[-1] in ('versionner', 'versionner.py'): print("versionner name is deprecated, use \"ver\" now!", file=sys.stderr) cfg_files = [ ...
Execute whole program :param prog: program name :param argv: list: script arguments :return:
Below is the the instruction that describes the task: ### Input: Execute whole program :param prog: program name :param argv: list: script arguments :return: ### Response: def execute(prog, argv): """Execute whole program :param prog: program name :param argv: list: script arguments :...
def AckFlowProcessingRequests(self, requests, cursor=None): """Deletes a list of flow processing requests from the database.""" if not requests: return query = "DELETE FROM flow_processing_requests WHERE " conditions = [] args = [] for r in requests: conditions.append( "(...
Deletes a list of flow processing requests from the database.
Below is the the instruction that describes the task: ### Input: Deletes a list of flow processing requests from the database. ### Response: def AckFlowProcessingRequests(self, requests, cursor=None): """Deletes a list of flow processing requests from the database.""" if not requests: return que...
def _initialize(self): """ Initialize the binary. :return: None """ # figure out section alignments for section in self.project.loader.main_object.sections: in_segment = False for segment in self.project.loader.main_object.segments: ...
Initialize the binary. :return: None
Below is the the instruction that describes the task: ### Input: Initialize the binary. :return: None ### Response: def _initialize(self): """ Initialize the binary. :return: None """ # figure out section alignments for section in self.project.loader.main_...
def namespace_inclusion_builder(namespace: Strings) -> NodePredicate: """Build a predicate for namespace inclusion.""" if isinstance(namespace, str): def namespace_filter(_: BELGraph, node: BaseEntity) -> bool: """Pass only for a node that has the enclosed namespace.""" return NA...
Build a predicate for namespace inclusion.
Below is the the instruction that describes the task: ### Input: Build a predicate for namespace inclusion. ### Response: def namespace_inclusion_builder(namespace: Strings) -> NodePredicate: """Build a predicate for namespace inclusion.""" if isinstance(namespace, str): def namespace_filter(_: BEL...