code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _standard_params(klass, ids, metric_groups, **kwargs): """ Sets the standard params for a stats request """ end_time = kwargs.get('end_time', datetime.utcnow()) start_time = kwargs.get('start_time', end_time - timedelta(seconds=604800)) granularity = kwargs.get('granu...
Sets the standard params for a stats request
Below is the the instruction that describes the task: ### Input: Sets the standard params for a stats request ### Response: def _standard_params(klass, ids, metric_groups, **kwargs): """ Sets the standard params for a stats request """ end_time = kwargs.get('end_time', datetime.utcn...
def get_random_choral(log=True): """ Gets a choral from the J. S. Bach chorals corpus (in Music21). """ choral_file = corpus.getBachChorales()[random.randint(0, 399)] choral = corpus.parse(choral_file) if log: print("Chosen choral:", choral.metadata.title) return choral
Gets a choral from the J. S. Bach chorals corpus (in Music21).
Below is the the instruction that describes the task: ### Input: Gets a choral from the J. S. Bach chorals corpus (in Music21). ### Response: def get_random_choral(log=True): """ Gets a choral from the J. S. Bach chorals corpus (in Music21). """ choral_file = corpus.getBachChorales()[random.randint(0, 399)] ...
def _get_population(self, freq, t): # freq in THz """Return phonon population number Three types of combinations of array inputs are possible. - single freq and single t - single freq and len(t) > 1 - len(freq) > 1 and single t """ condition = t > 1.0 i...
Return phonon population number Three types of combinations of array inputs are possible. - single freq and single t - single freq and len(t) > 1 - len(freq) > 1 and single t
Below is the the instruction that describes the task: ### Input: Return phonon population number Three types of combinations of array inputs are possible. - single freq and single t - single freq and len(t) > 1 - len(freq) > 1 and single t ### Response: def _get_population(self, fr...
def pop_callback(obj): """Pop a single callback.""" callbacks = obj._callbacks if not callbacks: return if isinstance(callbacks, Node): node = callbacks obj._callbacks = None else: node = callbacks.first callbacks.remove(node) if not callbacks: ...
Pop a single callback.
Below is the the instruction that describes the task: ### Input: Pop a single callback. ### Response: def pop_callback(obj): """Pop a single callback.""" callbacks = obj._callbacks if not callbacks: return if isinstance(callbacks, Node): node = callbacks obj._callbacks = Non...
def trace_decorator(self): """Decorator to trace a function.""" def decorator(func): def wrapper(*args, **kwargs): self.tracer.start_span(name=func.__name__) return_value = func(*args, **kwargs) self.tracer.end_span() return r...
Decorator to trace a function.
Below is the the instruction that describes the task: ### Input: Decorator to trace a function. ### Response: def trace_decorator(self): """Decorator to trace a function.""" def decorator(func): def wrapper(*args, **kwargs): self.tracer.start_span(name=func.__name__) ...
def parse_job_files(self): """Check for job definitions in known zuul files.""" repo_jobs = [] for rel_job_file_path, job_info in self.job_files.items(): LOGGER.debug("Checking for job definitions in %s", rel_job_file_path) jobs = self.parse_job_definitions(rel_job_file_p...
Check for job definitions in known zuul files.
Below is the the instruction that describes the task: ### Input: Check for job definitions in known zuul files. ### Response: def parse_job_files(self): """Check for job definitions in known zuul files.""" repo_jobs = [] for rel_job_file_path, job_info in self.job_files.items(): ...
def get_teams_by_name(org, team_names): """Find team(s) in org by name(s). Parameters ---------- org: github.Organization.Organization org to search for team(s) teams: list(str) list of team names to search for Returns ------- list of github.Team.Team objects Rais...
Find team(s) in org by name(s). Parameters ---------- org: github.Organization.Organization org to search for team(s) teams: list(str) list of team names to search for Returns ------- list of github.Team.Team objects Raises ------ github.GithubException ...
Below is the the instruction that describes the task: ### Input: Find team(s) in org by name(s). Parameters ---------- org: github.Organization.Organization org to search for team(s) teams: list(str) list of team names to search for Returns ------- list of github.Team....
def get_results_as_numpy_array(self, parameter_space, result_parsing_function, runs): """ Return the results relative to the desired parameter space in the form of a numpy array. Args: parameter_space (dict): dictionary containing ...
Return the results relative to the desired parameter space in the form of a numpy array. Args: parameter_space (dict): dictionary containing parameter/list-of-values pairs. result_parsing_function (function): user-defined function, taking a result...
Below is the the instruction that describes the task: ### Input: Return the results relative to the desired parameter space in the form of a numpy array. Args: parameter_space (dict): dictionary containing parameter/list-of-values pairs. result_parsing_functi...
def image_tile_create(comptparms, clrspc): """Creates a new image structure. Wraps the openjp2 library function opj_image_tile_create. Parameters ---------- cmptparms : comptparms_t The component parameters. clrspc : int Specifies the color space. Returns ------- i...
Creates a new image structure. Wraps the openjp2 library function opj_image_tile_create. Parameters ---------- cmptparms : comptparms_t The component parameters. clrspc : int Specifies the color space. Returns ------- image : ImageType Reference to ImageType in...
Below is the the instruction that describes the task: ### Input: Creates a new image structure. Wraps the openjp2 library function opj_image_tile_create. Parameters ---------- cmptparms : comptparms_t The component parameters. clrspc : int Specifies the color space. Return...
def normalized_energy_at_conditions(self, pH, V): """ Energy at an electrochemical condition, compatible with numpy arrays for pH/V input Args: pH (float): pH at condition V (float): applied potential at condition Returns: energy normalized b...
Energy at an electrochemical condition, compatible with numpy arrays for pH/V input Args: pH (float): pH at condition V (float): applied potential at condition Returns: energy normalized by number of non-O/H atoms at condition
Below is the the instruction that describes the task: ### Input: Energy at an electrochemical condition, compatible with numpy arrays for pH/V input Args: pH (float): pH at condition V (float): applied potential at condition Returns: energy normalized by...
def _get_default_dependencies(self): ''' Get default dependencies for archive Get default dependencies from requirements file or (if no requirements file) from previous version ''' # Get default dependencies from requirements file default_dependencies = { ...
Get default dependencies for archive Get default dependencies from requirements file or (if no requirements file) from previous version
Below is the the instruction that describes the task: ### Input: Get default dependencies for archive Get default dependencies from requirements file or (if no requirements file) from previous version ### Response: def _get_default_dependencies(self): ''' Get default dependencies f...
def get_pixel_size_from_nside(nside): """ Returns an estimate of the pixel size from the HEALPix nside coordinate This just uses a lookup table to provide a nice round number for each HEALPix order. """ order = int(np.log2(nside)) if order < 0 or order > 13: raise ValueError('HEALPix o...
Returns an estimate of the pixel size from the HEALPix nside coordinate This just uses a lookup table to provide a nice round number for each HEALPix order.
Below is the the instruction that describes the task: ### Input: Returns an estimate of the pixel size from the HEALPix nside coordinate This just uses a lookup table to provide a nice round number for each HEALPix order. ### Response: def get_pixel_size_from_nside(nside): """ Returns an estimate of t...
def doesIntersect(self, other): ''' :param: other - Line subclass :return: boolean Returns True iff: ccw(self.A,self.B,other.A) * ccw(self.A,self.B,other.B) <= 0 and ccw(other.A,other.B,self.A) * ccw(other.A,other.B,self.B) <= 0 ''' if s...
:param: other - Line subclass :return: boolean Returns True iff: ccw(self.A,self.B,other.A) * ccw(self.A,self.B,other.B) <= 0 and ccw(other.A,other.B,self.A) * ccw(other.A,other.B,self.B) <= 0
Below is the the instruction that describes the task: ### Input: :param: other - Line subclass :return: boolean Returns True iff: ccw(self.A,self.B,other.A) * ccw(self.A,self.B,other.B) <= 0 and ccw(other.A,other.B,self.A) * ccw(other.A,other.B,self.B) <= 0 ### Resp...
def _add_edge_dmap_fun(graph, edges_weights=None): """ Adds edge to the dispatcher map. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param edges_weights: Edge weights. :type edges_weights: dict, optional :return: A function that ad...
Adds edge to the dispatcher map. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param edges_weights: Edge weights. :type edges_weights: dict, optional :return: A function that adds an edge to the `graph`. :rtype: callable
Below is the the instruction that describes the task: ### Input: Adds edge to the dispatcher map. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param edges_weights: Edge weights. :type edges_weights: dict, optional :return: A function t...
def delete_grade(self, grade_id): """Deletes a ``Grade``. arg: grade_id (osid.id.Id): the ``Id`` of the ``Grade`` to remove raise: NotFound - ``grade_id`` not found raise: NullArgument - ``grade_id`` is ``null`` raise: OperationFailed - unable to complete r...
Deletes a ``Grade``. arg: grade_id (osid.id.Id): the ``Id`` of the ``Grade`` to remove raise: NotFound - ``grade_id`` not found raise: NullArgument - ``grade_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - aut...
Below is the the instruction that describes the task: ### Input: Deletes a ``Grade``. arg: grade_id (osid.id.Id): the ``Id`` of the ``Grade`` to remove raise: NotFound - ``grade_id`` not found raise: NullArgument - ``grade_id`` is ``null`` raise: OperationFaile...
def cors_allow_any(request, response): """ Add headers to permit CORS requests from any origin, with or without credentials, with any headers. """ origin = request.META.get('HTTP_ORIGIN') if not origin: return response # From the CORS spec: The string "*" cannot be used for a resour...
Add headers to permit CORS requests from any origin, with or without credentials, with any headers.
Below is the the instruction that describes the task: ### Input: Add headers to permit CORS requests from any origin, with or without credentials, with any headers. ### Response: def cors_allow_any(request, response): """ Add headers to permit CORS requests from any origin, with or without credentials,...
def absent(name, orgname=None, profile='grafana'): ''' Ensure the named grafana dashboard is absent. name Name of the grafana dashboard. orgname Name of the organization in which the dashboard should be present. profile Configuration profile used to connect to the Grafana ...
Ensure the named grafana dashboard is absent. name Name of the grafana dashboard. orgname Name of the organization in which the dashboard should be present. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'.
Below is the the instruction that describes the task: ### Input: Ensure the named grafana dashboard is absent. name Name of the grafana dashboard. orgname Name of the organization in which the dashboard should be present. profile Configuration profile used to connect to the Gr...
def delete_doc_by_query(self, collection, query, **kwargs): """ :param str collection: The name of the collection for the request :param str query: Query selecting documents to be deleted. Deletes items from Solr based on a given query. :: >>> solr.delete_doc_by_query('Solr...
:param str collection: The name of the collection for the request :param str query: Query selecting documents to be deleted. Deletes items from Solr based on a given query. :: >>> solr.delete_doc_by_query('SolrClient_unittest','*:*')
Below is the the instruction that describes the task: ### Input: :param str collection: The name of the collection for the request :param str query: Query selecting documents to be deleted. Deletes items from Solr based on a given query. :: >>> solr.delete_doc_by_query('SolrClient_unit...
def children(self, alias, bank_id): """ URL for getting or setting child relationships for the specified bank :param alias: :param bank_id: :return: """ return self._root + self._safe_alias(alias) + '/child/ids/' + str(bank_id)
URL for getting or setting child relationships for the specified bank :param alias: :param bank_id: :return:
Below is the the instruction that describes the task: ### Input: URL for getting or setting child relationships for the specified bank :param alias: :param bank_id: :return: ### Response: def children(self, alias, bank_id): """ URL for getting or setting child relationships ...
def gzip_cache(path): """ Another GZIP handler for Bottle functions. This may be used to cache the files statically on the disc on given `path`. If the browser accepts GZIP and there is file at ``path + ".gz"``, this file is returned, correct headers are set (Content-Encoding, Last-Modified, Co...
Another GZIP handler for Bottle functions. This may be used to cache the files statically on the disc on given `path`. If the browser accepts GZIP and there is file at ``path + ".gz"``, this file is returned, correct headers are set (Content-Encoding, Last-Modified, Content-Length, Date and so on). ...
Below is the the instruction that describes the task: ### Input: Another GZIP handler for Bottle functions. This may be used to cache the files statically on the disc on given `path`. If the browser accepts GZIP and there is file at ``path + ".gz"``, this file is returned, correct headers are set (Cont...
def add(self, template, resource, name=None): """Add a route to a resource. The optional `name` assigns a name to this route that can be used when building URLs. The name must be unique within this Mapper object. """ # Special case for standalone handler functions if has...
Add a route to a resource. The optional `name` assigns a name to this route that can be used when building URLs. The name must be unique within this Mapper object.
Below is the the instruction that describes the task: ### Input: Add a route to a resource. The optional `name` assigns a name to this route that can be used when building URLs. The name must be unique within this Mapper object. ### Response: def add(self, template, resource, name=None): "...
def temperature(self): """ Get the temperature in degree celcius """ result = self.i2c_read(2) value = struct.unpack('>H', result)[0] if value < 32768: return value / 256.0 else: return (value - 65536) / 256.0
Get the temperature in degree celcius
Below is the the instruction that describes the task: ### Input: Get the temperature in degree celcius ### Response: def temperature(self): """ Get the temperature in degree celcius """ result = self.i2c_read(2) value = struct.unpack('>H', result)[0] if value < 32768: ...
def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000, stopThr=1e-3, verbose=False, log=False): """ Compute the unmixing of an observation with a given dictionary using Wasserstein distance The function solve the following optimization problem: .. math:: \mathbf{h} = arg\min_\m...
Compute the unmixing of an observation with a given dictionary using Wasserstein distance The function solve the following optimization problem: .. math:: \mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h}) where : - :m...
Below is the the instruction that describes the task: ### Input: Compute the unmixing of an observation with a given dictionary using Wasserstein distance The function solve the following optimization problem: .. math:: \mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})...
def init (self, base_ref, base_url, parent_url, recursion_level, aggregate, line, column, page, name, url_encoding, extern): """Initialize the scheme.""" super(FileUrl, self).init(base_ref, base_url, parent_url, recursion_level, aggregate, line, column, page, name, url_encoding, e...
Initialize the scheme.
Below is the the instruction that describes the task: ### Input: Initialize the scheme. ### Response: def init (self, base_ref, base_url, parent_url, recursion_level, aggregate, line, column, page, name, url_encoding, extern): """Initialize the scheme.""" super(FileUrl, self).init(bas...
def setup(app): """Sphinx extension entry point""" app.add_config_value('jsdoc_source_root', '..', 'env') app.add_config_value('jsdoc_output_root', 'javascript', 'env') app.add_config_value('jsdoc_exclude', [], 'env') app.connect('builder-inited', generate_docs)
Sphinx extension entry point
Below is the the instruction that describes the task: ### Input: Sphinx extension entry point ### Response: def setup(app): """Sphinx extension entry point""" app.add_config_value('jsdoc_source_root', '..', 'env') app.add_config_value('jsdoc_output_root', 'javascript', 'env') app.add_config_value('...
def set(self, name, value, force=False): """Set a form element identified by ``name`` to a specified ``value``. The type of element (input, textarea, select, ...) does not need to be given; it is inferred by the following methods: :func:`~Form.set_checkbox`, :func:`~Form.set_radi...
Set a form element identified by ``name`` to a specified ``value``. The type of element (input, textarea, select, ...) does not need to be given; it is inferred by the following methods: :func:`~Form.set_checkbox`, :func:`~Form.set_radio`, :func:`~Form.set_input`, :func:`...
Below is the the instruction that describes the task: ### Input: Set a form element identified by ``name`` to a specified ``value``. The type of element (input, textarea, select, ...) does not need to be given; it is inferred by the following methods: :func:`~Form.set_checkbox`, :fun...
def monitor_layer_outputs(self): """ Monitoring the outputs of each layer. Useful for troubleshooting convergence problems. """ for layer, hidden in zip(self.layers, self._hidden_outputs): self.training_monitors.append(('mean(%s)' % (layer.name), abs(hidden).mean()))
Monitoring the outputs of each layer. Useful for troubleshooting convergence problems.
Below is the the instruction that describes the task: ### Input: Monitoring the outputs of each layer. Useful for troubleshooting convergence problems. ### Response: def monitor_layer_outputs(self): """ Monitoring the outputs of each layer. Useful for troubleshooting convergence pro...
def new(self, bootstrap_with=None, use_timer=False): """ Actual constructor of the solver. """ if not self.minisat: self.minisat = pysolvers.minisat22_new() if bootstrap_with: for clause in bootstrap_with: self.add_clause(...
Actual constructor of the solver.
Below is the the instruction that describes the task: ### Input: Actual constructor of the solver. ### Response: def new(self, bootstrap_with=None, use_timer=False): """ Actual constructor of the solver. """ if not self.minisat: self.minisat = pysolvers.minisat22_ne...
def addChild(self,item): """ When you add a child to a Node, you are adding yourself as a parent to the child You cannot have the same node as a child more than once. If you add a Node, it is used. If you add a non-node, a new child Node is created. Thus: You cannot add a child as an item which is a...
When you add a child to a Node, you are adding yourself as a parent to the child You cannot have the same node as a child more than once. If you add a Node, it is used. If you add a non-node, a new child Node is created. Thus: You cannot add a child as an item which is a Node. (You can, however, construct s...
Below is the the instruction that describes the task: ### Input: When you add a child to a Node, you are adding yourself as a parent to the child You cannot have the same node as a child more than once. If you add a Node, it is used. If you add a non-node, a new child Node is created. Thus: You cannot a...
def get_enrollment(self, id): """Retrieves an enrollment. Useful to check its type and related metadata. Args: id (str): The id of the device account to update See: https://auth0.com/docs/api/management/v2#!/Guardian/get_enrollments_by_id """ url = self._url...
Retrieves an enrollment. Useful to check its type and related metadata. Args: id (str): The id of the device account to update See: https://auth0.com/docs/api/management/v2#!/Guardian/get_enrollments_by_id
Below is the the instruction that describes the task: ### Input: Retrieves an enrollment. Useful to check its type and related metadata. Args: id (str): The id of the device account to update See: https://auth0.com/docs/api/management/v2#!/Guardian/get_enrollments_by_id ### Res...
def to_sql(self, connection, grammar): """ Get the raw SQL statements for the blueprint. :param connection: The connection to use :type connection: orator.connections.Connection :param grammar: The grammar to user :type grammar: orator.schema.grammars.SchemaGrammar ...
Get the raw SQL statements for the blueprint. :param connection: The connection to use :type connection: orator.connections.Connection :param grammar: The grammar to user :type grammar: orator.schema.grammars.SchemaGrammar :rtype: list
Below is the the instruction that describes the task: ### Input: Get the raw SQL statements for the blueprint. :param connection: The connection to use :type connection: orator.connections.Connection :param grammar: The grammar to user :type grammar: orator.schema.grammars.SchemaGr...
def Extract(self, components): """Extracts interesting paths from a given path. Args: components: Source string represented as a list of components. Returns: A list of extracted paths (as strings). """ for index, component in enumerate(components): if component.lower().endswith(...
Extracts interesting paths from a given path. Args: components: Source string represented as a list of components. Returns: A list of extracted paths (as strings).
Below is the the instruction that describes the task: ### Input: Extracts interesting paths from a given path. Args: components: Source string represented as a list of components. Returns: A list of extracted paths (as strings). ### Response: def Extract(self, components): """Extracts int...
def store_widget_properties(self, widget, widget_name): """Sets configuration values for widgets If the widget is a window, then the size and position are stored. If the widget is a pane, then only the position is stored. If the window is maximized the last insert position before being maximize...
Sets configuration values for widgets If the widget is a window, then the size and position are stored. If the widget is a pane, then only the position is stored. If the window is maximized the last insert position before being maximized is keep in the config and the maximized flag set to True....
Below is the the instruction that describes the task: ### Input: Sets configuration values for widgets If the widget is a window, then the size and position are stored. If the widget is a pane, then only the position is stored. If the window is maximized the last insert position before being maximi...
def derivation(self): """ Deserialize and return a Derivation object for UDF- or JSON-formatted derivation data; otherwise return the original string. """ drv = self.get('derivation') if drv is not None: if isinstance(drv, dict): drv = ...
Deserialize and return a Derivation object for UDF- or JSON-formatted derivation data; otherwise return the original string.
Below is the the instruction that describes the task: ### Input: Deserialize and return a Derivation object for UDF- or JSON-formatted derivation data; otherwise return the original string. ### Response: def derivation(self): """ Deserialize and return a Derivation object for UDF- o...
def main(): """ Use threads and Netmiko to connect to each of the devices. Execute 'show version' on each device. Record the amount of time required to do this. """ start_time = datetime.now() for a_device in devices: my_thread = threading.Thread(target=show_version, args=(a_device,)) ...
Use threads and Netmiko to connect to each of the devices. Execute 'show version' on each device. Record the amount of time required to do this.
Below is the the instruction that describes the task: ### Input: Use threads and Netmiko to connect to each of the devices. Execute 'show version' on each device. Record the amount of time required to do this. ### Response: def main(): """ Use threads and Netmiko to connect to each of the devices. Exec...
def least_squares_effective_mass( cartesian_k_points, eigenvalues ): """ Calculate the effective mass using a least squares quadratic fit. Args: cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points eigenvalues (np.array): Energy eigenvalues at each k-point...
Calculate the effective mass using a least squares quadratic fit. Args: cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points eigenvalues (np.array): Energy eigenvalues at each k-point to be used in the fit. Returns: (float): The fitted effective mass ...
Below is the the instruction that describes the task: ### Input: Calculate the effective mass using a least squares quadratic fit. Args: cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points eigenvalues (np.array): Energy eigenvalues at each k-point to be used ...
def add(self, member): """ Adds @member to the set -> #int the number of @members that were added to the set, excluding pre-existing members (1 or 0) """ return self._client.sadd(self.key_prefix, self._dumps(member))
Adds @member to the set -> #int the number of @members that were added to the set, excluding pre-existing members (1 or 0)
Below is the the instruction that describes the task: ### Input: Adds @member to the set -> #int the number of @members that were added to the set, excluding pre-existing members (1 or 0) ### Response: def add(self, member): """ Adds @member to the set -> #int the nu...
async def get_info(self): ''' Retrieves a brief information about the compute session. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}'.format(s...
Retrieves a brief information about the compute session.
Below is the the instruction that describes the task: ### Input: Retrieves a brief information about the compute session. ### Response: async def get_info(self): ''' Retrieves a brief information about the compute session. ''' params = {} if self.owner_access_key: ...
def setup_session(self, server, hooks, graph_default_context): """ Creates and then enters the session for this model (finalizes the graph). Args: server (tf.train.Server): The tf.train.Server object to connect to (None for single execution). hooks (list): A list of (sav...
Creates and then enters the session for this model (finalizes the graph). Args: server (tf.train.Server): The tf.train.Server object to connect to (None for single execution). hooks (list): A list of (saver, summary, etc..) hooks to be passed to the session. graph_default_co...
Below is the the instruction that describes the task: ### Input: Creates and then enters the session for this model (finalizes the graph). Args: server (tf.train.Server): The tf.train.Server object to connect to (None for single execution). hooks (list): A list of (saver, summary, e...
def _data_execute(self, data, program, executor): """Execute the Data object. The activities carried out here include target directory preparation, executor copying, setting serialization and actual execution of the object. :param data: The :class:`~resolwe.flow.models.Data` ob...
Execute the Data object. The activities carried out here include target directory preparation, executor copying, setting serialization and actual execution of the object. :param data: The :class:`~resolwe.flow.models.Data` object to execute. :param program: The proc...
Below is the the instruction that describes the task: ### Input: Execute the Data object. The activities carried out here include target directory preparation, executor copying, setting serialization and actual execution of the object. :param data: The :class:`~resolwe.flow.models....
def simplify(cls, content_type): """ The MIME types main- and sub-label can both start with <tt>x-</tt>, which indicates that it is a non-registered name. Of course, after registration this flag can disappear, adds to the confusing proliferation of MIME types. The simplified stri...
The MIME types main- and sub-label can both start with <tt>x-</tt>, which indicates that it is a non-registered name. Of course, after registration this flag can disappear, adds to the confusing proliferation of MIME types. The simplified string has the <tt>x-</tt> removed and are transl...
Below is the the instruction that describes the task: ### Input: The MIME types main- and sub-label can both start with <tt>x-</tt>, which indicates that it is a non-registered name. Of course, after registration this flag can disappear, adds to the confusing proliferation of MIME types. The...
def unite(df, colname, *args, **kwargs): """ Does the inverse of `separate`, joining columns together by a specified separator. Any columns that are not strings will be converted to strings. Args: df (pandas.DataFrame): DataFrame passed in through the pipe. colname (str): the name ...
Does the inverse of `separate`, joining columns together by a specified separator. Any columns that are not strings will be converted to strings. Args: df (pandas.DataFrame): DataFrame passed in through the pipe. colname (str): the name of the new joined column. *args: list of colu...
Below is the the instruction that describes the task: ### Input: Does the inverse of `separate`, joining columns together by a specified separator. Any columns that are not strings will be converted to strings. Args: df (pandas.DataFrame): DataFrame passed in through the pipe. colname ...
def normalize_text(text: str) -> str: """ Performs a normalization that is very similar to that done by the normalization functions in SQuAD and TriviaQA. This involves splitting and rejoining the text, and could be a somewhat expensive operation. """ return ' '.join([token ...
Performs a normalization that is very similar to that done by the normalization functions in SQuAD and TriviaQA. This involves splitting and rejoining the text, and could be a somewhat expensive operation.
Below is the the instruction that describes the task: ### Input: Performs a normalization that is very similar to that done by the normalization functions in SQuAD and TriviaQA. This involves splitting and rejoining the text, and could be a somewhat expensive operation. ### Response: def normalize_text(te...
def add_http_basic_auth(url, user=None, password=None, https_only=False): ''' Return a string with http basic auth incorporated into it ''' if user is None and password is None: return url else: urltuple = urlpar...
Return a string with http basic auth incorporated into it
Below is the the instruction that describes the task: ### Input: Return a string with http basic auth incorporated into it ### Response: def add_http_basic_auth(url, user=None, password=None, https_only=False): ''' Return a string with...
def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors...
Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.
Below is the the instruction that describes the task: ### Input: Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response. ### Response: def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid fro...
def get(self, name, ns=None, default=None): """ Get the value of an attribute by name. @param name: The name of the attribute. @type name: basestring @param ns: The optional attribute's namespace. @type ns: (I{prefix}, I{name}) @param default: An optional value t...
Get the value of an attribute by name. @param name: The name of the attribute. @type name: basestring @param ns: The optional attribute's namespace. @type ns: (I{prefix}, I{name}) @param default: An optional value to be returned when either the attribute does not exi...
Below is the the instruction that describes the task: ### Input: Get the value of an attribute by name. @param name: The name of the attribute. @type name: basestring @param ns: The optional attribute's namespace. @type ns: (I{prefix}, I{name}) @param default: An optional va...
def process_part(self, char): '''Process chars while in a part''' if char in self.whitespace or char == self.eol_char: # End of the part. self.parts.append( ''.join(self.part) ) self.part = [] # Switch back to processing a delimiter. self.proce...
Process chars while in a part
Below is the the instruction that describes the task: ### Input: Process chars while in a part ### Response: def process_part(self, char): '''Process chars while in a part''' if char in self.whitespace or char == self.eol_char: # End of the part. self.parts.append( ''.join(s...
def UTCFromGps(gpsWeek, SOW, leapSecs=14): """converts gps week and seconds to UTC see comments of inverse function! SOW = seconds of week gpsWeek is the full number (not modulo 1024) """ secFract = SOW % 1 epochTuple = gpsEpoch + (-1, -1, 0) t0 = time.mktime(epochTuple) - time.timezo...
converts gps week and seconds to UTC see comments of inverse function! SOW = seconds of week gpsWeek is the full number (not modulo 1024)
Below is the the instruction that describes the task: ### Input: converts gps week and seconds to UTC see comments of inverse function! SOW = seconds of week gpsWeek is the full number (not modulo 1024) ### Response: def UTCFromGps(gpsWeek, SOW, leapSecs=14): """converts gps week and seconds to U...
def get_input_widget(self, fieldname, arnum=0, **kw): """Get the field widget of the AR in column <arnum> :param fieldname: The base fieldname :type fieldname: string """ # temporary AR Context context = self.get_ar() # request = self.request schema = co...
Get the field widget of the AR in column <arnum> :param fieldname: The base fieldname :type fieldname: string
Below is the the instruction that describes the task: ### Input: Get the field widget of the AR in column <arnum> :param fieldname: The base fieldname :type fieldname: string ### Response: def get_input_widget(self, fieldname, arnum=0, **kw): """Get the field widget of the AR in column <ar...
def p_block_statements(self, p): 'block_statements : block_statements block_statement' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
block_statements : block_statements block_statement
Below is the the instruction that describes the task: ### Input: block_statements : block_statements block_statement ### Response: def p_block_statements(self, p): 'block_statements : block_statements block_statement' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
def send_password_changed_email(self, user): """Send the 'password has changed' notification email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_SEND_PASSWORD_CHANGED_EMAIL: return # Notification emails are sent to...
Send the 'password has changed' notification email.
Below is the the instruction that describes the task: ### Input: Send the 'password has changed' notification email. ### Response: def send_password_changed_email(self, user): """Send the 'password has changed' notification email.""" # Verify config settings if not self.user_manager.USER_E...
def execute_greenlet_async(func, *args, **kwargs): """ Executes `func` in a separate greenlet in the same process. Memory and other resources are available (e.g. TCP connections etc.) `args` and `kwargs` are passed to `func`. """ global _GREENLET_EXECUTOR if _GREENLET_EXECUTOR is None: _GREENLET_EXECU...
Executes `func` in a separate greenlet in the same process. Memory and other resources are available (e.g. TCP connections etc.) `args` and `kwargs` are passed to `func`.
Below is the the instruction that describes the task: ### Input: Executes `func` in a separate greenlet in the same process. Memory and other resources are available (e.g. TCP connections etc.) `args` and `kwargs` are passed to `func`. ### Response: def execute_greenlet_async(func, *args, **kwargs): """ Ex...
def ttSparseALS(cooP, shape, x0=None, ttRank=1, tol=1e-5, maxnsweeps=20, verbose=True, alpha=1e-2): ''' TT completion via Alternating Least Squares algorithm. Parameters: :dict: cooP dictionary with two records - 'indices': numpy.array of P x d shape, ...
TT completion via Alternating Least Squares algorithm. Parameters: :dict: cooP dictionary with two records - 'indices': numpy.array of P x d shape, contains index subspace of P known elements; each string is an index of one element. ...
Below is the the instruction that describes the task: ### Input: TT completion via Alternating Least Squares algorithm. Parameters: :dict: cooP dictionary with two records - 'indices': numpy.array of P x d shape, contains index subspace of P known element...
def enter_alternate_screen(self): """ Go to alternate screen buffer. """ if not self._in_alternate_screen: GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 # Create a new console buffer and activate that one. handle = self._winapi(wind...
Go to alternate screen buffer.
Below is the the instruction that describes the task: ### Input: Go to alternate screen buffer. ### Response: def enter_alternate_screen(self): """ Go to alternate screen buffer. """ if not self._in_alternate_screen: GENERIC_READ = 0x80000000 GENERIC_WRITE = ...
def normalizeHSP(hsp, queryLen, diamondTask): """ Examine an HSP and return information about where the query and subject match begins and ends. Return a dict with keys that allow the query to be displayed against the subject. The returned readStartInSubject and readEndInSubject indices are offsets...
Examine an HSP and return information about where the query and subject match begins and ends. Return a dict with keys that allow the query to be displayed against the subject. The returned readStartInSubject and readEndInSubject indices are offsets into the subject. I.e., they indicate where in the su...
Below is the the instruction that describes the task: ### Input: Examine an HSP and return information about where the query and subject match begins and ends. Return a dict with keys that allow the query to be displayed against the subject. The returned readStartInSubject and readEndInSubject indices ...
def returner(ret): ''' Write the return data to a file on the minion. ''' opts = _get_options(ret) try: with salt.utils.files.flopen(opts['filename'], 'a') as logfile: salt.utils.json.dump(ret, logfile) logfile.write(str('\n')) # future lint: disable=blacklisted-func...
Write the return data to a file on the minion.
Below is the the instruction that describes the task: ### Input: Write the return data to a file on the minion. ### Response: def returner(ret): ''' Write the return data to a file on the minion. ''' opts = _get_options(ret) try: with salt.utils.files.flopen(opts['filename'], 'a') as lo...
def _reset_file_descriptors(self): """Close open file descriptors and redirect standard streams.""" if self.close_open_files: # Attempt to determine the max number of open files max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if max_fds == resource.RLIM_INFINI...
Close open file descriptors and redirect standard streams.
Below is the the instruction that describes the task: ### Input: Close open file descriptors and redirect standard streams. ### Response: def _reset_file_descriptors(self): """Close open file descriptors and redirect standard streams.""" if self.close_open_files: # Attempt to determine ...
def hex_to_rgb(self, h): """Converts a valid hex color string to an RGB array.""" rgb = (self.hex_to_red(h), self.hex_to_green(h), self.hex_to_blue(h)) return rgb
Converts a valid hex color string to an RGB array.
Below is the the instruction that describes the task: ### Input: Converts a valid hex color string to an RGB array. ### Response: def hex_to_rgb(self, h): """Converts a valid hex color string to an RGB array.""" rgb = (self.hex_to_red(h), self.hex_to_green(h), self.hex_to_blue(h)) return rg...
def _get_settings(self): """ Return any settings defined by the user, as well as any pre-defined settings files that exist for the image modalities to be registered. """ # If user-defined settings exist... if isdefined(self.inputs.settings): # Note this in the...
Return any settings defined by the user, as well as any pre-defined settings files that exist for the image modalities to be registered.
Below is the the instruction that describes the task: ### Input: Return any settings defined by the user, as well as any pre-defined settings files that exist for the image modalities to be registered. ### Response: def _get_settings(self): """ Return any settings defined by the user, as we...
def cid_ce(x, normalize): """ This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks, valleys etc.). It calculates the value of .. math:: \\sqrt{ \\sum_{i=0}^{n-2lag} ( x_{i} - x_{i+1})^2 } .. rubric:: References | [1] Bat...
This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks, valleys etc.). It calculates the value of .. math:: \\sqrt{ \\sum_{i=0}^{n-2lag} ( x_{i} - x_{i+1})^2 } .. rubric:: References | [1] Batista, Gustavo EAPA, et al (2014). ...
Below is the the instruction that describes the task: ### Input: This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks, valleys etc.). It calculates the value of .. math:: \\sqrt{ \\sum_{i=0}^{n-2lag} ( x_{i} - x_{i+1})^2 } .. rubr...
def by_id(self, region, encrypted_summoner_id): """ Get a summoner by summoner ID. :param string region: The region to execute this request on :param string encrypted_summoner_id: Summoner ID :returns: SummonerDTO: represents a summoner """ ...
Get a summoner by summoner ID. :param string region: The region to execute this request on :param string encrypted_summoner_id: Summoner ID :returns: SummonerDTO: represents a summoner
Below is the the instruction that describes the task: ### Input: Get a summoner by summoner ID. :param string region: The region to execute this request on :param string encrypted_summoner_id: Summoner ID :returns: SummonerDTO: represents a summoner ### Response: def ...
def Depends(self, target, dependency): """Explicity specify that 'target's depend on 'dependency'.""" tlist = self.arg2nodes(target, self.fs.Entry) dlist = self.arg2nodes(dependency, self.fs.Entry) for t in tlist: t.add_dependency(dlist) return tlist
Explicity specify that 'target's depend on 'dependency'.
Below is the the instruction that describes the task: ### Input: Explicity specify that 'target's depend on 'dependency'. ### Response: def Depends(self, target, dependency): """Explicity specify that 'target's depend on 'dependency'.""" tlist = self.arg2nodes(target, self.fs.Entry) dlist =...
def timeid(self, data: ['SASdata', str] = None, by: str = None, id: str = None, out: [str, 'SASdata'] = None, procopts: str = None, stmtpassthrough: str = None, **kwargs: dict) -> 'SASresults': """ Python method to...
Python method to call the TIMEID procedure Documentation link: http://support.sas.com/documentation/cdl//en/etsug/68148/HTML/default/viewer.htm#etsug_timeid_syntax.htm :param data: SASdata object or string. This parameter is required. :parm by: The by variable can only be a string type...
Below is the the instruction that describes the task: ### Input: Python method to call the TIMEID procedure Documentation link: http://support.sas.com/documentation/cdl//en/etsug/68148/HTML/default/viewer.htm#etsug_timeid_syntax.htm :param data: SASdata object or string. This parameter is ...
def _trigger_events(view_obj, events_map, additional_kw=None): """ Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event. """ ...
Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event.
Below is the the instruction that describes the task: ### Input: Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event. ### Respon...
def WaitForJobChange(r, job_id, fields, prev_job_info, prev_log_serial): """ Waits for job changes. @type job_id: int @param job_id: Job ID for which to wait """ body = { "fields": fields, "previous_job_info": prev_job_info, "previous_log_serial": prev_log_serial, }...
Waits for job changes. @type job_id: int @param job_id: Job ID for which to wait
Below is the the instruction that describes the task: ### Input: Waits for job changes. @type job_id: int @param job_id: Job ID for which to wait ### Response: def WaitForJobChange(r, job_id, fields, prev_job_info, prev_log_serial): """ Waits for job changes. @type job_id: int @param job_...
def parse(self): """ Processes the files for each IRQ and each CPU in terms of the differences. Also produces accumulated interrupt count differences for each set of Ethernet IRQs. Generally Ethernet has 8 TxRx IRQs thus all are combined so that one can see the overall interrupts being generated by the ...
Processes the files for each IRQ and each CPU in terms of the differences. Also produces accumulated interrupt count differences for each set of Ethernet IRQs. Generally Ethernet has 8 TxRx IRQs thus all are combined so that one can see the overall interrupts being generated by the NIC. Simplified Interrup...
Below is the the instruction that describes the task: ### Input: Processes the files for each IRQ and each CPU in terms of the differences. Also produces accumulated interrupt count differences for each set of Ethernet IRQs. Generally Ethernet has 8 TxRx IRQs thus all are combined so that one can see the ov...
def deployment_groups(self): """ Gets the Deployment Groups API client. Returns: DeploymentGroups: """ if not self.__deployment_groups: self.__deployment_groups = DeploymentGroups(self.__connection) return self.__deployment_groups
Gets the Deployment Groups API client. Returns: DeploymentGroups:
Below is the the instruction that describes the task: ### Input: Gets the Deployment Groups API client. Returns: DeploymentGroups: ### Response: def deployment_groups(self): """ Gets the Deployment Groups API client. Returns: DeploymentGroups: """ ...
def copychildren(self, newdoc=None, idsuffix=""): """Generator creating a deep copy of the children of this element. Invokes :meth:`copy` on all children, parameters are the same. """ if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each...
Generator creating a deep copy of the children of this element. Invokes :meth:`copy` on all children, parameters are the same.
Below is the the instruction that describes the task: ### Input: Generator creating a deep copy of the children of this element. Invokes :meth:`copy` on all children, parameters are the same. ### Response: def copychildren(self, newdoc=None, idsuffix=""): """Generator creating a deep copy of the c...
def script(state, host, filename, chdir=None): ''' Upload and execute a local script on the remote host. + filename: local script filename to upload & execute + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_filename(filename) yield files.put(state, ...
Upload and execute a local script on the remote host. + filename: local script filename to upload & execute + chdir: directory to cd into before executing the script
Below is the the instruction that describes the task: ### Input: Upload and execute a local script on the remote host. + filename: local script filename to upload & execute + chdir: directory to cd into before executing the script ### Response: def script(state, host, filename, chdir=None): ''' Up...
def init_static_combine(): """ Process static combine, create md5 key according each static filename """ from uliweb import settings from hashlib import md5 import os d = {} if settings.get_var('STATIC_COMBINE_CONFIG/enable', False): for k, v in settings.get('STATI...
Process static combine, create md5 key according each static filename
Below is the the instruction that describes the task: ### Input: Process static combine, create md5 key according each static filename ### Response: def init_static_combine(): """ Process static combine, create md5 key according each static filename """ from uliweb import settings from has...
def interval(coro, interval=1, times=None, loop=None): """ Schedules the execution of a coroutine function every `x` amount of seconds. The function returns an `asyncio.Task`, which implements also an `asyncio.Future` interface, allowing the user to cancel the execution cycle. This functio...
Schedules the execution of a coroutine function every `x` amount of seconds. The function returns an `asyncio.Task`, which implements also an `asyncio.Future` interface, allowing the user to cancel the execution cycle. This function can be used as decorator. Arguments: coro (coroutine...
Below is the the instruction that describes the task: ### Input: Schedules the execution of a coroutine function every `x` amount of seconds. The function returns an `asyncio.Task`, which implements also an `asyncio.Future` interface, allowing the user to cancel the execution cycle. This funct...
def notebook_exists(self, notebook_id): """Does a notebook exist?""" if notebook_id not in self.mapping: return False path = self.get_path_by_name(self.mapping[notebook_id]) return os.path.isfile(path)
Does a notebook exist?
Below is the the instruction that describes the task: ### Input: Does a notebook exist? ### Response: def notebook_exists(self, notebook_id): """Does a notebook exist?""" if notebook_id not in self.mapping: return False path = self.get_path_by_name(self.mapping[notebook_id]) ...
def replace_initializer_configuration(self, name, body, **kwargs): # noqa: E501 """replace_initializer_configuration # noqa: E501 replace the specified InitializerConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request,...
replace_initializer_configuration # noqa: E501 replace the specified InitializerConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_initializer_configuration(name,...
Below is the the instruction that describes the task: ### Input: replace_initializer_configuration # noqa: E501 replace the specified InitializerConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=...
def get_most_recent_network_by_name(self, name: str) -> Optional[Network]: """Get the most recently created network with the given name.""" return self.session.query(Network).filter(Network.name == name).order_by(Network.created.desc()).first()
Get the most recently created network with the given name.
Below is the the instruction that describes the task: ### Input: Get the most recently created network with the given name. ### Response: def get_most_recent_network_by_name(self, name: str) -> Optional[Network]: """Get the most recently created network with the given name.""" return self.session.q...
def total_rated_level(octave_frequencies): """ Calculates the A-rated total sound pressure level based on octave band frequencies """ sums = 0.0 for band in OCTAVE_BANDS.keys(): if band not in octave_frequencies: continue if octave_frequencies[band] is None: ...
Calculates the A-rated total sound pressure level based on octave band frequencies
Below is the the instruction that describes the task: ### Input: Calculates the A-rated total sound pressure level based on octave band frequencies ### Response: def total_rated_level(octave_frequencies): """ Calculates the A-rated total sound pressure level based on octave band frequencies """...
def to_fmt(self): """ Return an Fmt representation for pretty-printing """ params = "" txt = fmt.sep(" ", ['fun']) name = self.show_name() if name != "": txt.lsdata.append(name) tparams = [] if self.tparams is not None: tparams = list(self.tparams) if self.variadi...
Return an Fmt representation for pretty-printing
Below is the the instruction that describes the task: ### Input: Return an Fmt representation for pretty-printing ### Response: def to_fmt(self): """ Return an Fmt representation for pretty-printing """ params = "" txt = fmt.sep(" ", ['fun']) name = self.show_name() if name != "": ...
def convert_from_bytes_if_necessary(prefix, suffix): """ Depending on how we extract data from pysam we may end up with either a string or a byte array of nucleotides. For consistency and simplicity, we want to only use strings in the rest of our code. """ if isinstance(prefix, bytes): p...
Depending on how we extract data from pysam we may end up with either a string or a byte array of nucleotides. For consistency and simplicity, we want to only use strings in the rest of our code.
Below is the the instruction that describes the task: ### Input: Depending on how we extract data from pysam we may end up with either a string or a byte array of nucleotides. For consistency and simplicity, we want to only use strings in the rest of our code. ### Response: def convert_from_bytes_if_necess...
def save(self, filename, compressed=True): """ Save a tensor to disk. """ # check for data if not self.has_data: return False # read ext and save accordingly _, file_ext = os.path.splitext(filename) if compressed: if file_ext != COMPRESSED_TENSOR_...
Save a tensor to disk.
Below is the the instruction that describes the task: ### Input: Save a tensor to disk. ### Response: def save(self, filename, compressed=True): """ Save a tensor to disk. """ # check for data if not self.has_data: return False # read ext and save accordingly _,...
def compare(self, textOrFingerprint1, textOrFingerprint2): """Returns the semantic similarity of texts or fingerprints. Each argument can be eiter a text or a fingerprint. Args: textOrFingerprint1, str OR list of integers textOrFingerprint2, str OR list of integers Return...
Returns the semantic similarity of texts or fingerprints. Each argument can be eiter a text or a fingerprint. Args: textOrFingerprint1, str OR list of integers textOrFingerprint2, str OR list of integers Returns: float: the semantic similarity in the range [0;1] ...
Below is the the instruction that describes the task: ### Input: Returns the semantic similarity of texts or fingerprints. Each argument can be eiter a text or a fingerprint. Args: textOrFingerprint1, str OR list of integers textOrFingerprint2, str OR list of integers Returns...
def show_ring(devname): ''' Queries the specified network device for rx/tx ring parameter information CLI Example: .. code-block:: bash salt '*' ethtool.show_ring <devname> ''' try: ring = ethtool.get_ringparam(devname) except IOError: log.error('Ring parameters n...
Queries the specified network device for rx/tx ring parameter information CLI Example: .. code-block:: bash salt '*' ethtool.show_ring <devname>
Below is the the instruction that describes the task: ### Input: Queries the specified network device for rx/tx ring parameter information CLI Example: .. code-block:: bash salt '*' ethtool.show_ring <devname> ### Response: def show_ring(devname): ''' Queries the specified network device...
def __convert_string(node): """Converts a StringProperty node to JSON format.""" converted = __convert_node(node, default_flags=vsflags(VSFlags.UserValue)) return __check_for_flag(converted)
Converts a StringProperty node to JSON format.
Below is the the instruction that describes the task: ### Input: Converts a StringProperty node to JSON format. ### Response: def __convert_string(node): """Converts a StringProperty node to JSON format.""" converted = __convert_node(node, default_flags=vsflags(VSFlags.UserValue)) return __check_for_f...
def maps(self): """ A dictionary of dictionaries. Each dictionary defines a map which is used to extend the metadata. The precise way maps interact with the metadata is defined by `figure.fit._extend_meta`. That method should be redefined or extended to suit specific use cases. ...
A dictionary of dictionaries. Each dictionary defines a map which is used to extend the metadata. The precise way maps interact with the metadata is defined by `figure.fit._extend_meta`. That method should be redefined or extended to suit specific use cases.
Below is the the instruction that describes the task: ### Input: A dictionary of dictionaries. Each dictionary defines a map which is used to extend the metadata. The precise way maps interact with the metadata is defined by `figure.fit._extend_meta`. That method should be redefined or exte...
def get_method_returning_field_value(self, field_name): """ Field values can be obtained from view or core. """ return ( super().get_method_returning_field_value(field_name) or self.core.get_method_returning_field_value(field_name) )
Field values can be obtained from view or core.
Below is the the instruction that describes the task: ### Input: Field values can be obtained from view or core. ### Response: def get_method_returning_field_value(self, field_name): """ Field values can be obtained from view or core. """ return ( super().get_method_retu...
def correct(self, z): '''Correct the given approximate solution ``z`` with respect to the linear system ``linear_system`` and the deflation space defined by ``U``.''' c = self.linear_system.Ml*( self.linear_system.b - self.linear_system.A*z) c = utils.inner(self.W, c,...
Correct the given approximate solution ``z`` with respect to the linear system ``linear_system`` and the deflation space defined by ``U``.
Below is the the instruction that describes the task: ### Input: Correct the given approximate solution ``z`` with respect to the linear system ``linear_system`` and the deflation space defined by ``U``. ### Response: def correct(self, z): '''Correct the given approximate solution ``z`` wit...
def is_fresh(self, freshness): """Return False if given freshness value has expired, else True.""" if self.expire_after is None: return True return self.freshness() - freshness <= self.expire_after
Return False if given freshness value has expired, else True.
Below is the the instruction that describes the task: ### Input: Return False if given freshness value has expired, else True. ### Response: def is_fresh(self, freshness): """Return False if given freshness value has expired, else True.""" if self.expire_after is None: return True ...
def multiply(x1, x2, output_shape=None, name=None): """Binary multiplication with broadcasting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ if not isinstance(x2, Tensor): return ScalarMultiplyOperation(x1, x2).outputs[...
Binary multiplication with broadcasting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor
Below is the the instruction that describes the task: ### Input: Binary multiplication with broadcasting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor ### Response: def multiply(x1, x2, output_shape=None, name=None): """Binary...
def _bowtie_args_from_config(data): """Configurable high level options for bowtie. """ config = data['config'] qual_format = config["algorithm"].get("quality_format", "") if qual_format.lower() == "illumina": qual_flags = ["--phred64-quals"] else: qual_flags = [] multi_mapper...
Configurable high level options for bowtie.
Below is the the instruction that describes the task: ### Input: Configurable high level options for bowtie. ### Response: def _bowtie_args_from_config(data): """Configurable high level options for bowtie. """ config = data['config'] qual_format = config["algorithm"].get("quality_format", "") i...
def cli(ctx, value, metadata=""): """Add a canned value Output: A dictionnary containing canned value description """ return ctx.gi.cannedvalues.add_value(value, metadata=metadata)
Add a canned value Output: A dictionnary containing canned value description
Below is the the instruction that describes the task: ### Input: Add a canned value Output: A dictionnary containing canned value description ### Response: def cli(ctx, value, metadata=""): """Add a canned value Output: A dictionnary containing canned value description """ return ctx.gi.can...
def derivative(self, x, der=1): """ return the derivative a an array of input values x : the inputs der : the order of derivative """ from scipy.interpolate import splev return splev(x, self._sp, der=der)
return the derivative a an array of input values x : the inputs der : the order of derivative
Below is the the instruction that describes the task: ### Input: return the derivative a an array of input values x : the inputs der : the order of derivative ### Response: def derivative(self, x, der=1): """ return the derivative a an array of input values x : the inp...
def _main(self, client, bucket, key, upload_id, parts, extra_args): """ :param client: The client to use when calling CompleteMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload ...
:param client: The client to use when calling CompleteMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param parts: A list of parts to use to complete the multipart upload:: ...
Below is the the instruction that describes the task: ### Input: :param client: The client to use when calling CompleteMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param parts: ...
def _send_and_wait(self, **kwargs): """ Send a frame to either the local ZigBee or a remote device and wait for a pre-defined amount of time for its response. """ frame_id = self.next_frame_id kwargs.update(dict(frame_id=frame_id)) self._send(**kwargs) tim...
Send a frame to either the local ZigBee or a remote device and wait for a pre-defined amount of time for its response.
Below is the the instruction that describes the task: ### Input: Send a frame to either the local ZigBee or a remote device and wait for a pre-defined amount of time for its response. ### Response: def _send_and_wait(self, **kwargs): """ Send a frame to either the local ZigBee or a remote d...
def save(self, *args, **kwargs): """ call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save """ after_save = kwargs.pop('after_save', True) super(LayerExternal, self).save(*args, **kwargs) # call after_e...
call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save
Below is the the instruction that describes the task: ### Input: call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save ### Response: def save(self, *args, **kwargs): """ call synchronizer "after_external_layer_saved" method ...
def patch_network_latency(seconds=0.01): """ Add random latency to all I/O operations """ # Accept float(0.1), "0.1", "0.1-0.2" def sleep(): if isinstance(seconds, float): time.sleep(seconds) elif isinstance(seconds, basestring): # pylint: disable=maybe-no-member ...
Add random latency to all I/O operations
Below is the the instruction that describes the task: ### Input: Add random latency to all I/O operations ### Response: def patch_network_latency(seconds=0.01): """ Add random latency to all I/O operations """ # Accept float(0.1), "0.1", "0.1-0.2" def sleep(): if isinstance(seconds, float): ...
def corruptDenseVector(vector, noiseLevel): """ Corrupts a binary vector by inverting noiseLevel percent of its bits. @param vector (array) binary vector to be corrupted @param noiseLevel (float) amount of noise to be applied on the vector. """ size = len(vector) for i in range(size): rnd = rando...
Corrupts a binary vector by inverting noiseLevel percent of its bits. @param vector (array) binary vector to be corrupted @param noiseLevel (float) amount of noise to be applied on the vector.
Below is the the instruction that describes the task: ### Input: Corrupts a binary vector by inverting noiseLevel percent of its bits. @param vector (array) binary vector to be corrupted @param noiseLevel (float) amount of noise to be applied on the vector. ### Response: def corruptDenseVector(vector, noi...
def check_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'], seqType='both', verbose=False): """Checks if source- and header-files, used as input when pre-processing MPL-containers, need fixing.""" # Check the input files for containers in their variadic form. ...
Checks if source- and header-files, used as input when pre-processing MPL-containers, need fixing.
Below is the the instruction that describes the task: ### Input: Checks if source- and header-files, used as input when pre-processing MPL-containers, need fixing. ### Response: def check_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'], seqType='both', verbose=Fa...
def random_connection(self): '''Pick a random living connection''' # While at the moment there's no need for this to be a context manager # per se, I would like to use that interface since I anticipate # adding some wrapping around it at some point. yield random.choice( ...
Pick a random living connection
Below is the the instruction that describes the task: ### Input: Pick a random living connection ### Response: def random_connection(self): '''Pick a random living connection''' # While at the moment there's no need for this to be a context manager # per se, I would like to use that interfa...
def select_if(df, fun): """Selects columns where fun(ction) is true Args: fun: a function that will be applied to columns """ def _filter_f(col): try: return fun(df[col]) except: return False cols = list(filter(_filter_f, df.columns)) return df[c...
Selects columns where fun(ction) is true Args: fun: a function that will be applied to columns
Below is the the instruction that describes the task: ### Input: Selects columns where fun(ction) is true Args: fun: a function that will be applied to columns ### Response: def select_if(df, fun): """Selects columns where fun(ction) is true Args: fun: a function that will be applied to...
def drop(self): """Drop the table from the database. Deletes both the schema and all the contents within it. """ with self.db.lock: if self.exists: self._threading_warn() self.table.drop(self.db.executable, checkfirst=True) sel...
Drop the table from the database. Deletes both the schema and all the contents within it.
Below is the the instruction that describes the task: ### Input: Drop the table from the database. Deletes both the schema and all the contents within it. ### Response: def drop(self): """Drop the table from the database. Deletes both the schema and all the contents within it. """...
def get_or_create(self, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ assert kwargs, \ 'get_or_create() mus...
Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created.
Below is the the instruction that describes the task: ### Input: Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. ### Response: def get_or_create(self, **kwargs): "...
def from_string(self, repo, name, string): """ Create a new Item from a data stream. :param repo: Repo object. :param name: Name of item. :param data: Data stream. :return: New Item class instance. """ try: log.debug('Creating new item: %s' %...
Create a new Item from a data stream. :param repo: Repo object. :param name: Name of item. :param data: Data stream. :return: New Item class instance.
Below is the the instruction that describes the task: ### Input: Create a new Item from a data stream. :param repo: Repo object. :param name: Name of item. :param data: Data stream. :return: New Item class instance. ### Response: def from_string(self, repo, name, string): ...