code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def copy_course_content(self, course_id, exclude=None, only=None, source_course=None): """ Copy course content. DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API} Copies content from one course into another. The default is to copy a...
Copy course content. DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API} Copies content from one course into another. The default is to copy all course content. You can control specific types to copy by using either the 'except' option ...
Below is the the instruction that describes the task: ### Input: Copy course content. DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API} Copies content from one course into another. The default is to copy all course content. You can cont...
def _normalize_numpy_indices(i): """Normalize the index in case it is a numpy integer or boolean array.""" if isinstance(i, np.ndarray): if i.dtype == bool: i = tuple(j.tolist() for j in i.nonzero()) elif i.dtype == int: i = i.tolist() return i
Normalize the index in case it is a numpy integer or boolean array.
Below is the the instruction that describes the task: ### Input: Normalize the index in case it is a numpy integer or boolean array. ### Response: def _normalize_numpy_indices(i): """Normalize the index in case it is a numpy integer or boolean array.""" if isinstance(i, np.ndarray): if i.dt...
def _reset_model(self, response): """Update the fields value with the received information.""" # pylint: disable=no-member # Reset the model to the initial state self._provision_done = False # Set back the provision flag self._changes.clear() # Clear the changes ...
Update the fields value with the received information.
Below is the the instruction that describes the task: ### Input: Update the fields value with the received information. ### Response: def _reset_model(self, response): """Update the fields value with the received information.""" # pylint: disable=no-member # Reset the model to the initial...
def init_config(self, stype="idp"): """ Remaining init of the server configuration :param stype: The type of Server ("idp"/"aa") """ if stype == "aa": return # subject information is stored in a database # default database is in memory which is OK in some se...
Remaining init of the server configuration :param stype: The type of Server ("idp"/"aa")
Below is the the instruction that describes the task: ### Input: Remaining init of the server configuration :param stype: The type of Server ("idp"/"aa") ### Response: def init_config(self, stype="idp"): """ Remaining init of the server configuration :param stype: The type of Server ("idp...
def median(arr): """median of the values, must have more than 0 entries. :param arr: list of numbers :type arr: number[] a number array :return: median :rtype: float """ if len(arr) == 0: sys.stderr.write("ERROR: no content in array to take average\n") sys.exit() if len(arr) == 1: return arr[0...
median of the values, must have more than 0 entries. :param arr: list of numbers :type arr: number[] a number array :return: median :rtype: float
Below is the the instruction that describes the task: ### Input: median of the values, must have more than 0 entries. :param arr: list of numbers :type arr: number[] a number array :return: median :rtype: float ### Response: def median(arr): """median of the values, must have more than 0 entries. :pa...
def default_links_pagination_factory(page, urlkwargs): """Factory for record links generation.""" endpoint = '.communities_list' links = { 'self': url_for(endpoint, page=page.page, _external=True, **urlkwargs), } if page.has_prev: links['prev'] = url_for(endpoint, page=page.prev_nu...
Factory for record links generation.
Below is the the instruction that describes the task: ### Input: Factory for record links generation. ### Response: def default_links_pagination_factory(page, urlkwargs): """Factory for record links generation.""" endpoint = '.communities_list' links = { 'self': url_for(endpoint, page=page.pag...
def delete_index_item(item, model_name, refresh=True): ''' Deletes an item from the index. :param item: must be a serializable object. :param model_name: doctype, which must also be the model name. :param refresh: a boolean that determines whether to refresh the index, making all operations performe...
Deletes an item from the index. :param item: must be a serializable object. :param model_name: doctype, which must also be the model name. :param refresh: a boolean that determines whether to refresh the index, making all operations performed since the last refresh immediately available for search, inst...
Below is the the instruction that describes the task: ### Input: Deletes an item from the index. :param item: must be a serializable object. :param model_name: doctype, which must also be the model name. :param refresh: a boolean that determines whether to refresh the index, making all operations perfor...
def redistribute_duplicates(data): """Given a dictionary of photo sets, will look at lat/lon between sets, if they match, randomly move them around so the google map markeres do not overlap """ coordinate_list=[] # Build a list of coordinates for myset in data['sets']: coordinat...
Given a dictionary of photo sets, will look at lat/lon between sets, if they match, randomly move them around so the google map markeres do not overlap
Below is the the instruction that describes the task: ### Input: Given a dictionary of photo sets, will look at lat/lon between sets, if they match, randomly move them around so the google map markeres do not overlap ### Response: def redistribute_duplicates(data): """Given a dictionary of photo sets, ...
def init(self, input_dim=0, input_dims=None, no_prepare=False): """ Initialize the layer. :param no_prepare: avoid calling preparation function """ if self.initialized: return # configure input dimensions if input_dims: self.input_dims = in...
Initialize the layer. :param no_prepare: avoid calling preparation function
Below is the the instruction that describes the task: ### Input: Initialize the layer. :param no_prepare: avoid calling preparation function ### Response: def init(self, input_dim=0, input_dims=None, no_prepare=False): """ Initialize the layer. :param no_prepare: avoid calling prepa...
def get_authorized_tokens(self, oauth_verifier): """Returns a dict of authorized tokens after they go through the :class:`get_authentication_tokens` phase. :param oauth_verifier: (required) The oauth_verifier (or a.k.a PIN for non web apps) retrieved from the callback url querystring ...
Returns a dict of authorized tokens after they go through the :class:`get_authentication_tokens` phase. :param oauth_verifier: (required) The oauth_verifier (or a.k.a PIN for non web apps) retrieved from the callback url querystring :rtype: dict
Below is the the instruction that describes the task: ### Input: Returns a dict of authorized tokens after they go through the :class:`get_authentication_tokens` phase. :param oauth_verifier: (required) The oauth_verifier (or a.k.a PIN for non web apps) retrieved from the callback url query...
def exists(name=None, group=None, release=None, except_release=None, verbose=1): """ Determines if a virtual machine instance exists. """ verbose = int(verbose) instances = list_instances( name=name, group=group, release=release, except_release=except_release, ...
Determines if a virtual machine instance exists.
Below is the the instruction that describes the task: ### Input: Determines if a virtual machine instance exists. ### Response: def exists(name=None, group=None, release=None, except_release=None, verbose=1): """ Determines if a virtual machine instance exists. """ verbose = int(verbose) instan...
def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None): """Convert the job description to init params that can be handled by the class constructor Args: job_details: the returned job details from a describe_training_job API call. model_channel_n...
Convert the job description to init params that can be handled by the class constructor Args: job_details: the returned job details from a describe_training_job API call. model_channel_name (str): Name of the channel where pre-trained model data will be downloaded. Returns: ...
Below is the the instruction that describes the task: ### Input: Convert the job description to init params that can be handled by the class constructor Args: job_details: the returned job details from a describe_training_job API call. model_channel_name (str): Name of the channel w...
def filter_excluded_tags(self, all_tags): """ Filter tags according exclude_tags and exclude_tags_regex option. :param list(dict) all_tags: Pre-filtered tags. :rtype: list(dict) :return: Filtered tags. """ filtered_tags = copy.deepcopy(all_tags) if self.o...
Filter tags according exclude_tags and exclude_tags_regex option. :param list(dict) all_tags: Pre-filtered tags. :rtype: list(dict) :return: Filtered tags.
Below is the the instruction that describes the task: ### Input: Filter tags according exclude_tags and exclude_tags_regex option. :param list(dict) all_tags: Pre-filtered tags. :rtype: list(dict) :return: Filtered tags. ### Response: def filter_excluded_tags(self, all_tags): """ ...
def save(self, UserSave=True, *args, **kwargs): """ Se sobreescribe el método salvar para poder gestionar la creación de un User en caso que no se haya creado y enlazado uno antes. Se puede elegir si se desea guardar los cambios efectuados en user. """ if hasattr(self, 'user') and self.user is not ...
Se sobreescribe el método salvar para poder gestionar la creación de un User en caso que no se haya creado y enlazado uno antes. Se puede elegir si se desea guardar los cambios efectuados en user.
Below is the the instruction that describes the task: ### Input: Se sobreescribe el método salvar para poder gestionar la creación de un User en caso que no se haya creado y enlazado uno antes. Se puede elegir si se desea guardar los cambios efectuados en user. ### Response: def save(self, UserSave=True, *...
def shallow_copy(obj, attribute_names, ignore_missing_attributes=True): """ Return a shallow copy of the given object, including only the specified attributes of this object. @param obj: an object to copy. @param attribute_names: a list of names of the attributes to copy. @param igno...
Return a shallow copy of the given object, including only the specified attributes of this object. @param obj: an object to copy. @param attribute_names: a list of names of the attributes to copy. @param ignore_missing_attributes: ``False`` indicates that the function can ignore attributes t...
Below is the the instruction that describes the task: ### Input: Return a shallow copy of the given object, including only the specified attributes of this object. @param obj: an object to copy. @param attribute_names: a list of names of the attributes to copy. @param ignore_missing_attributes: ...
def _constrain_glob(glob, paths, limit=5): """ Tweaks glob into a list of more specific globs that together still cover paths and not too much extra. Saves us minutes long listings for long dataset histories. Specifically, in this implementation the leftmost occurrences of "[0-9]" give rise to a f...
Tweaks glob into a list of more specific globs that together still cover paths and not too much extra. Saves us minutes long listings for long dataset histories. Specifically, in this implementation the leftmost occurrences of "[0-9]" give rise to a few separate globs that each specialize the expression t...
Below is the the instruction that describes the task: ### Input: Tweaks glob into a list of more specific globs that together still cover paths and not too much extra. Saves us minutes long listings for long dataset histories. Specifically, in this implementation the leftmost occurrences of "[0-9]" gi...
def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None, profile=None): ''' Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ...
Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id
Below is the the instruction that describes the task: ### Input: Create a new, empty pipeline. This function is idempotent. CLI example: .. code-block:: bash salt myminion boto_datapipeline.create_pipeline my_name my_unique_id ### Response: def create_pipeline(name, unique_id, description='', re...
def download_and_parse_mnist_file(fname, target_dir=None, force=False): """Download the IDX file named fname from the URL specified in dataset_url and return it as a numpy array. Parameters ---------- fname : str File name to download and parse target_dir : str Directory where ...
Download the IDX file named fname from the URL specified in dataset_url and return it as a numpy array. Parameters ---------- fname : str File name to download and parse target_dir : str Directory where to store the file force : bool Force downloading the file, if it a...
Below is the the instruction that describes the task: ### Input: Download the IDX file named fname from the URL specified in dataset_url and return it as a numpy array. Parameters ---------- fname : str File name to download and parse target_dir : str Directory where to store t...
def create_required_directories(self): """Creates any directories required for Engineer to function if they don't already exist.""" required = (self.CACHE_DIR, self.LOG_DIR, self.OUTPUT_DIR, self.ENGINEER.JINJA_CACHE_DIR,) for folder i...
Creates any directories required for Engineer to function if they don't already exist.
Below is the the instruction that describes the task: ### Input: Creates any directories required for Engineer to function if they don't already exist. ### Response: def create_required_directories(self): """Creates any directories required for Engineer to function if they don't already exist.""" r...
def show(self, commits=None, encoding='utf-8'): """Show the data of a set of commits. The method returns the output of Git show command for a set of commits using the following options: git show --raw --numstat --pretty=fuller --decorate=full --parents -M -C -c [<co...
Show the data of a set of commits. The method returns the output of Git show command for a set of commits using the following options: git show --raw --numstat --pretty=fuller --decorate=full --parents -M -C -c [<commit>...<commit>] When the list of commits is empt...
Below is the the instruction that describes the task: ### Input: Show the data of a set of commits. The method returns the output of Git show command for a set of commits using the following options: git show --raw --numstat --pretty=fuller --decorate=full --parents -M ...
def cli_run(): """docstring for argparse""" parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow') parser.add_argument('query', help="What's the problem ?", type=str, nargs='+') parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda') ...
docstring for argparse
Below is the the instruction that describes the task: ### Input: docstring for argparse ### Response: def cli_run(): """docstring for argparse""" parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow') parser.add_argument('query', help="What's the problem ?", typ...
def execute_command(self, parts, dry_run): """ Execute a command. Parameters ---------- parts : list Sequence of strings constituting a command. dry_run : bool Whether to just log the command instead of executing it. Returns -----...
Execute a command. Parameters ---------- parts : list Sequence of strings constituting a command. dry_run : bool Whether to just log the command instead of executing it. Returns ------- status : int Status code of the executed...
Below is the the instruction that describes the task: ### Input: Execute a command. Parameters ---------- parts : list Sequence of strings constituting a command. dry_run : bool Whether to just log the command instead of executing it. Returns ...
def split_words(sentence, modify=True, keep_shorts=False): """ Extract and yield the keywords from the sentence: - Drop keywords that are too short (keep_shorts=False) - Drop the accents (modify=True) - Make everything lower case (modify=True) - Try to separate the words as much as possible (usi...
Extract and yield the keywords from the sentence: - Drop keywords that are too short (keep_shorts=False) - Drop the accents (modify=True) - Make everything lower case (modify=True) - Try to separate the words as much as possible (using 2 list of separators, one being more complete than the others)
Below is the the instruction that describes the task: ### Input: Extract and yield the keywords from the sentence: - Drop keywords that are too short (keep_shorts=False) - Drop the accents (modify=True) - Make everything lower case (modify=True) - Try to separate the words as much as possible (using...
def subgroup(self, t, i): """Handle parenthesis.""" current = [] # (?flags) flags = self.get_flags(i) if flags: self.flags(flags[2:-1]) return [flags] # (?#comment) comments = self.get_comments(i) if comments: return ...
Handle parenthesis.
Below is the the instruction that describes the task: ### Input: Handle parenthesis. ### Response: def subgroup(self, t, i): """Handle parenthesis.""" current = [] # (?flags) flags = self.get_flags(i) if flags: self.flags(flags[2:-1]) return [flags]...
def noisy(pattern, noiseLevel, totalNumCells): """ Generate a noisy copy of a pattern. Given number of active bits w = len(pattern), deactivate noiseLevel*w cells, and activate noiseLevel*w other cells. @param pattern (set) A set of active indices @param noiseLevel (float) The percentage of the bits ...
Generate a noisy copy of a pattern. Given number of active bits w = len(pattern), deactivate noiseLevel*w cells, and activate noiseLevel*w other cells. @param pattern (set) A set of active indices @param noiseLevel (float) The percentage of the bits to shuffle @param totalNumCells (int) The number o...
Below is the the instruction that describes the task: ### Input: Generate a noisy copy of a pattern. Given number of active bits w = len(pattern), deactivate noiseLevel*w cells, and activate noiseLevel*w other cells. @param pattern (set) A set of active indices @param noiseLevel (float) The percentag...
def connect_widget(self): """Perform the initial connection of the widget the default implementation will connect to the widgets signal based on self.signal_name """ if self.signal_name is not None: # None for read only widgets sid = self.widget.connect(s...
Perform the initial connection of the widget the default implementation will connect to the widgets signal based on self.signal_name
Below is the the instruction that describes the task: ### Input: Perform the initial connection of the widget the default implementation will connect to the widgets signal based on self.signal_name ### Response: def connect_widget(self): """Perform the initial connection of the widget ...
def animate_panel(panel, keys=None, columns=None, interval=1000, blit=False, titles='', path='animate_panel', xlabel='Time', ylabel='Value', ext='gif', replot=False, linewidth=3, close=False, fontsize=24, background_color='white', alpha=1, figsize=(12,8), xlabel_rotation=-25, plot_kwargs=(('rotation'...
Animate a pandas.Panel by flipping through plots of the data in each dataframe Arguments: panel (pandas.Panel): Pandas Panel of DataFrames to animate (each DataFrame is an animation video frame) keys (list of str): ordered list of panel keys (pages) to animate columns (list of str): ordered list ...
Below is the the instruction that describes the task: ### Input: Animate a pandas.Panel by flipping through plots of the data in each dataframe Arguments: panel (pandas.Panel): Pandas Panel of DataFrames to animate (each DataFrame is an animation video frame) keys (list of str): ordered list of pan...
def _import_config(config_file): """returns a configuration object :param string config_file: path to config file """ # get config file path jocker_lgr.debug('config file is: {0}'.format(config_file)) # append to path for importing try: jocker_lgr.debug('importing config...') ...
returns a configuration object :param string config_file: path to config file
Below is the the instruction that describes the task: ### Input: returns a configuration object :param string config_file: path to config file ### Response: def _import_config(config_file): """returns a configuration object :param string config_file: path to config file """ # get config file ...
def put_annotation(self, key, value): """ Annotate segment or subsegment with a key-value pair. Annotations will be indexed for later search query. :param str key: annotation key :param object value: annotation value. Any type other than string/number/bool will be dr...
Annotate segment or subsegment with a key-value pair. Annotations will be indexed for later search query. :param str key: annotation key :param object value: annotation value. Any type other than string/number/bool will be dropped
Below is the the instruction that describes the task: ### Input: Annotate segment or subsegment with a key-value pair. Annotations will be indexed for later search query. :param str key: annotation key :param object value: annotation value. Any type other than string/number/bool...
def standard_output(self, ds, limit, check_name, groups): """ Generates the Terminal Output for Standard cases Returns the dataset needed for the verbose output, as well as the failure flags. """ score_list, points, out_of = self.get_points(groups, limit) issue_count = ...
Generates the Terminal Output for Standard cases Returns the dataset needed for the verbose output, as well as the failure flags.
Below is the the instruction that describes the task: ### Input: Generates the Terminal Output for Standard cases Returns the dataset needed for the verbose output, as well as the failure flags. ### Response: def standard_output(self, ds, limit, check_name, groups): """ Generates the Termi...
def handle_import_error(caught_exc, name): """Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is different, e.g. `...
Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is different, e.g. ``... undefined symbol: __curve_intersection_MOD_al...
Below is the the instruction that describes the task: ### Input: Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is di...
def scan_index(content_dir): """ Scan all files in a content directory """ def scan_directory(root, files): """ Helper function to scan a single directory """ try: for file in files: fullpath = os.path.join(root, file) relpath = os.path.relpath(fullpa...
Scan all files in a content directory
Below is the the instruction that describes the task: ### Input: Scan all files in a content directory ### Response: def scan_index(content_dir): """ Scan all files in a content directory """ def scan_directory(root, files): """ Helper function to scan a single directory """ try: ...
def _internal_add(self, pattern: Pattern, label, renaming) -> int: """Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. ...
Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. Args: pattern: The pattern to add. Returns: ...
Below is the the instruction that describes the task: ### Input: Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. Args:...
def indices_within_times(times, start, end): """ Return an index array into times that lie within the durations defined by start end arrays Parameters ---------- times: numpy.ndarray Array of times start: numpy.ndarray Array of duration start times end: numpy.ndarray ...
Return an index array into times that lie within the durations defined by start end arrays Parameters ---------- times: numpy.ndarray Array of times start: numpy.ndarray Array of duration start times end: numpy.ndarray Array of duration end times Returns ------- ...
Below is the the instruction that describes the task: ### Input: Return an index array into times that lie within the durations defined by start end arrays Parameters ---------- times: numpy.ndarray Array of times start: numpy.ndarray Array of duration start times end: numpy.nda...
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all toners cartridges.""" toner_status = {} for color in self.COLOR_NAMES: try: toner_stat = self.data.get( '{}_{}'.format(SyncThru.TONER, color),...
Return the state of all toners cartridges.
Below is the the instruction that describes the task: ### Input: Return the state of all toners cartridges. ### Response: def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all toners cartridges.""" toner_status = {} for color in self.COLOR_NA...
def ids_from_seq_two_step(seq, n, max_iterations, app, core_threshold, \ extra_threshold, lower_threshold, second_db=None): """Returns ids that match a seq, using a 2-tiered strategy. Optionally uses a second database for the second search. """ #first time through: reset 'h' and 'e' to core #-h...
Returns ids that match a seq, using a 2-tiered strategy. Optionally uses a second database for the second search.
Below is the the instruction that describes the task: ### Input: Returns ids that match a seq, using a 2-tiered strategy. Optionally uses a second database for the second search. ### Response: def ids_from_seq_two_step(seq, n, max_iterations, app, core_threshold, \ extra_threshold, lower_threshold, second...
def at(self, instant): """Iterates (in chronological order) over all events that are occuring during `instant`. Args: instant (Arrow object) """ for event in self: if event.begin <= instant <= event.end: yield event
Iterates (in chronological order) over all events that are occuring during `instant`. Args: instant (Arrow object)
Below is the the instruction that describes the task: ### Input: Iterates (in chronological order) over all events that are occuring during `instant`. Args: instant (Arrow object) ### Response: def at(self, instant): """Iterates (in chronological order) over all events that are occurin...
def _get_date_type(date): """ Returns the type of a date. :param str|datetime.date date: The date. :rtype: str """ if isinstance(date, str): return 'str' if isinstance(date, datetime.date): return 'date' if isinstance(date, int)...
Returns the type of a date. :param str|datetime.date date: The date. :rtype: str
Below is the the instruction that describes the task: ### Input: Returns the type of a date. :param str|datetime.date date: The date. :rtype: str ### Response: def _get_date_type(date): """ Returns the type of a date. :param str|datetime.date date: The date. :rty...
def update_m(data, old_M, old_W, selected_genes, disp=False, inner_max_iters=100, parallel=True, threads=4, write_progress_file=None, tol=0.0, regularization=0.0, **kwargs): """ This returns a new M matrix that contains all genes, given an M that was created from running state estimation with a subset of ge...
This returns a new M matrix that contains all genes, given an M that was created from running state estimation with a subset of genes. Args: data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all genes old_M (array): shape is (selected_genes, k) old_W (...
Below is the the instruction that describes the task: ### Input: This returns a new M matrix that contains all genes, given an M that was created from running state estimation with a subset of genes. Args: data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all gene...
def contact_number(self): """ This method returns the contact phone number. :return: """ try: number = self._ad_page_content.find( 'button', {'class': 'phone-number'}) return (base64.b64decode(number.attrs['data-p'])).decode('ascii') ...
This method returns the contact phone number. :return:
Below is the the instruction that describes the task: ### Input: This method returns the contact phone number. :return: ### Response: def contact_number(self): """ This method returns the contact phone number. :return: """ try: number = self._ad_page_cont...
def flux_producers(F, rtol=1e-05, atol=1e-12): r"""Return indexes of states that are net flux producers. Parameters ---------- F : (n, n) ndarray Matrix of flux values between pairs of states. rtol : float relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx)...
r"""Return indexes of states that are net flux producers. Parameters ---------- F : (n, n) ndarray Matrix of flux values between pairs of states. rtol : float relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx) < rtol atol : float absolute tolerance...
Below is the the instruction that describes the task: ### Input: r"""Return indexes of states that are net flux producers. Parameters ---------- F : (n, n) ndarray Matrix of flux values between pairs of states. rtol : float relative tolerance. fulfilled if max(outflux-influx, 0) / m...
def dvds_current_releases(self, **kwargs): """Gets the upcoming movies from the API. Args: page_limit (optional): number of movies to show per page, default=16 page (optional): results page number, default=1 country (optional): localized data for selected country, default=...
Gets the upcoming movies from the API. Args: page_limit (optional): number of movies to show per page, default=16 page (optional): results page number, default=1 country (optional): localized data for selected country, default="us" Returns: A dict respresentatio...
Below is the the instruction that describes the task: ### Input: Gets the upcoming movies from the API. Args: page_limit (optional): number of movies to show per page, default=16 page (optional): results page number, default=1 country (optional): localized data for selected co...
def parquet_to_df(filename, use_threads=1): """parquet_to_df: Reads a Parquet file into a Pandas DataFrame Args: filename (string): The full path to the filename for the Parquet file ntreads (int): The number of threads to use (defaults to 1) """ try: return pq.read_t...
parquet_to_df: Reads a Parquet file into a Pandas DataFrame Args: filename (string): The full path to the filename for the Parquet file ntreads (int): The number of threads to use (defaults to 1)
Below is the the instruction that describes the task: ### Input: parquet_to_df: Reads a Parquet file into a Pandas DataFrame Args: filename (string): The full path to the filename for the Parquet file ntreads (int): The number of threads to use (defaults to 1) ### Response: def parq...
def export_image(self, filename='refcycle.png', format=None, dot_executable='dot'): """ Export graph as an image. This requires that Graphviz is installed and that the ``dot`` executable is in your path. The *filename* argument specifies the output filename...
Export graph as an image. This requires that Graphviz is installed and that the ``dot`` executable is in your path. The *filename* argument specifies the output filename. The *format* argument lets you specify the output format. It may be any format that ``dot`` understands, ...
Below is the the instruction that describes the task: ### Input: Export graph as an image. This requires that Graphviz is installed and that the ``dot`` executable is in your path. The *filename* argument specifies the output filename. The *format* argument lets you specify the ou...
def to_array_list(df, length=None, by_id=True): """Converts a dataframe to a list of arrays, with one array for every unique index entry. Index is assumed to be 0-based contiguous. If there is a missing index entry, an empty numpy array is returned for it. Elements in the arrays are sorted by their id. ...
Converts a dataframe to a list of arrays, with one array for every unique index entry. Index is assumed to be 0-based contiguous. If there is a missing index entry, an empty numpy array is returned for it. Elements in the arrays are sorted by their id. :param df: :param length: :return:
Below is the the instruction that describes the task: ### Input: Converts a dataframe to a list of arrays, with one array for every unique index entry. Index is assumed to be 0-based contiguous. If there is a missing index entry, an empty numpy array is returned for it. Elements in the arrays are sorted...
def averaging(grid, numGrid, numPix): """ resize 2d pixel grid with numGrid to numPix and averages over the pixels :param grid: higher resolution pixel grid :param numGrid: number of pixels per axis in the high resolution input image :param numPix: lower number of pixels per axis in the output image...
resize 2d pixel grid with numGrid to numPix and averages over the pixels :param grid: higher resolution pixel grid :param numGrid: number of pixels per axis in the high resolution input image :param numPix: lower number of pixels per axis in the output image (numGrid/numPix is integer number) :return:
Below is the the instruction that describes the task: ### Input: resize 2d pixel grid with numGrid to numPix and averages over the pixels :param grid: higher resolution pixel grid :param numGrid: number of pixels per axis in the high resolution input image :param numPix: lower number of pixels per axis ...
def pref(preference, field=None, verbose_name=None, help_text='', static=True, readonly=False): """Marks a preference. :param preference: Preference variable. :param Field field: Django model field to represent this preference. :param str|unicode verbose_name: Field verbose name. :param str|unic...
Marks a preference. :param preference: Preference variable. :param Field field: Django model field to represent this preference. :param str|unicode verbose_name: Field verbose name. :param str|unicode help_text: Field help text. :param bool static: Leave this preference static (do not store in ...
Below is the the instruction that describes the task: ### Input: Marks a preference. :param preference: Preference variable. :param Field field: Django model field to represent this preference. :param str|unicode verbose_name: Field verbose name. :param str|unicode help_text: Field help text. ...
def adopt_module_key_flags(module, flag_values=_flagvalues.FLAGS): """Declares that all flags key to a module are key to the current module. Args: module: module, the module object from which all key flags will be declared as key flags to the current module. flag_values: FlagValues, the FlagValues ...
Declares that all flags key to a module are key to the current module. Args: module: module, the module object from which all key flags will be declared as key flags to the current module. flag_values: FlagValues, the FlagValues instance in which the flags will be declared as key flags. This ...
Below is the the instruction that describes the task: ### Input: Declares that all flags key to a module are key to the current module. Args: module: module, the module object from which all key flags will be declared as key flags to the current module. flag_values: FlagValues, the FlagValues ins...
def get_edge_mark(ttree): """ makes a simple Graph Mark object""" ## tree style if ttree._kwargs["tree_style"] in ["c", "cladogram"]: a=ttree.edges vcoordinates=ttree.verts else: a=ttree._lines vcoordinates=ttree._coords ## fixed args a...
makes a simple Graph Mark object
Below is the the instruction that describes the task: ### Input: makes a simple Graph Mark object ### Response: def get_edge_mark(ttree): """ makes a simple Graph Mark object""" ## tree style if ttree._kwargs["tree_style"] in ["c", "cladogram"]: a=ttree.edges vcoordinates=ttree.ver...
def create_logger(name: str) -> Logger: """ Creates a logger with the given name. :param name: name of the logger (gets prefixed with the package name) :return: the created logger """ logger = logging.getLogger(f"{PACKAGE_NAME}.{name}") logger.addHandler(StreamHandler()) return logger
Creates a logger with the given name. :param name: name of the logger (gets prefixed with the package name) :return: the created logger
Below is the the instruction that describes the task: ### Input: Creates a logger with the given name. :param name: name of the logger (gets prefixed with the package name) :return: the created logger ### Response: def create_logger(name: str) -> Logger: """ Creates a logger with the given name. ...
def _prepare_servers(self): """ Prepare the variables that are exposed to the servers. Most attributes in the server config are used directly. However, due to variations in how cloud providers treat regions and availability zones, this method allows either the ``availability_zo...
Prepare the variables that are exposed to the servers. Most attributes in the server config are used directly. However, due to variations in how cloud providers treat regions and availability zones, this method allows either the ``availability_zone`` or the ``region_name`` to be used a...
Below is the the instruction that describes the task: ### Input: Prepare the variables that are exposed to the servers. Most attributes in the server config are used directly. However, due to variations in how cloud providers treat regions and availability zones, this method allows either ...
def root_path(): """Get the absolute path to the root of the demosys package""" module_dir = os.path.dirname(globals()['__file__']) return os.path.dirname(os.path.dirname(module_dir))
Get the absolute path to the root of the demosys package
Below is the the instruction that describes the task: ### Input: Get the absolute path to the root of the demosys package ### Response: def root_path(): """Get the absolute path to the root of the demosys package""" module_dir = os.path.dirname(globals()['__file__']) return os.path.dirname(os.path.dirn...
def _set_system_max(self, v, load=False): """ Setter method for system_max, mapped from YANG variable /rbridge_id/system_max (container) If this variable is read-only (config: false) in the source YANG file, then _set_system_max is considered as a private method. Backends looking to populate this va...
Setter method for system_max, mapped from YANG variable /rbridge_id/system_max (container) If this variable is read-only (config: false) in the source YANG file, then _set_system_max is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_syste...
Below is the the instruction that describes the task: ### Input: Setter method for system_max, mapped from YANG variable /rbridge_id/system_max (container) If this variable is read-only (config: false) in the source YANG file, then _set_system_max is considered as a private method. Backends looking to p...
def bar(self,xdata,ydata,disp=True,**kwargs): '''Displays a bar graph. xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example. ydata: list of values associated with categories i...
Displays a bar graph. xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example. ydata: list of values associated with categories in xdata. If xdata includes a header, include a header lis...
Below is the the instruction that describes the task: ### Input: Displays a bar graph. xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example. ydata: list of values associated with ...
def create_space(deployment_name, space_name, security_policy='public', events_retention_days=0, metrics_retention_days=0, token_manager=None, app_url=defaults.APP_URL): """ create a space within the deployment...
create a space within the deployment specified and with the various rentention values set
Below is the the instruction that describes the task: ### Input: create a space within the deployment specified and with the various rentention values set ### Response: def create_space(deployment_name, space_name, security_policy='public', events_retention_da...
def assist(self, text_query): """Send a text request to the Assistant and playback the response. """ def iter_assist_requests(): config = embedded_assistant_pb2.AssistConfig( audio_out_config=embedded_assistant_pb2.AudioOutConfig( encoding='LINEAR1...
Send a text request to the Assistant and playback the response.
Below is the the instruction that describes the task: ### Input: Send a text request to the Assistant and playback the response. ### Response: def assist(self, text_query): """Send a text request to the Assistant and playback the response. """ def iter_assist_requests(): config ...
def add_tokens_for_group(self, with_pass=False): """Add the tokens for the group signature""" kls = self.groups.super_kls name = self.groups.kls_name # Reset indentation to beginning and add signature self.reset_indentation('') self.result.extend(self.tokens.make_describ...
Add the tokens for the group signature
Below is the the instruction that describes the task: ### Input: Add the tokens for the group signature ### Response: def add_tokens_for_group(self, with_pass=False): """Add the tokens for the group signature""" kls = self.groups.super_kls name = self.groups.kls_name # Reset indent...
def infer_list(values: List[GenericAny]) -> Array: """Infer the :class:`~ibis.expr.datatypes.Array` type of `values`.""" if not values: return Array(null) return Array(highest_precedence(map(infer, values)))
Infer the :class:`~ibis.expr.datatypes.Array` type of `values`.
Below is the the instruction that describes the task: ### Input: Infer the :class:`~ibis.expr.datatypes.Array` type of `values`. ### Response: def infer_list(values: List[GenericAny]) -> Array: """Infer the :class:`~ibis.expr.datatypes.Array` type of `values`.""" if not values: return Array(null) ...
def make_delete_request(url, params, headers, connection): """ Helper function that makes an HTTP DELETE request to the given firebase endpoint. Timeout is 60 seconds. `url`: The full URL of the firebase endpoint (DSN appended.) `params`: Python dict that is appended to the URL like a querystring. ...
Helper function that makes an HTTP DELETE request to the given firebase endpoint. Timeout is 60 seconds. `url`: The full URL of the firebase endpoint (DSN appended.) `params`: Python dict that is appended to the URL like a querystring. `headers`: Python dict. HTTP request headers. `connection`: Pred...
Below is the the instruction that describes the task: ### Input: Helper function that makes an HTTP DELETE request to the given firebase endpoint. Timeout is 60 seconds. `url`: The full URL of the firebase endpoint (DSN appended.) `params`: Python dict that is appended to the URL like a querystring. ...
def tokenize(self, config): """ Break the config into a series of tokens """ tokens = [] reg_ex = re.compile(self.TOKENS[0], re.M | re.I) for token in re.finditer(reg_ex, config): value = token.group(0) if token.group("operator"): ...
Break the config into a series of tokens
Below is the the instruction that describes the task: ### Input: Break the config into a series of tokens ### Response: def tokenize(self, config): """ Break the config into a series of tokens """ tokens = [] reg_ex = re.compile(self.TOKENS[0], re.M | re.I) for toke...
def _query( self, sql, url, fmt, log ): """* query* """ self.log.info('starting the ``_query`` method') try: response = requests.get( url=url, params={ "cmd": self._filtercomment(...
* query*
Below is the the instruction that describes the task: ### Input: * query* ### Response: def _query( self, sql, url, fmt, log ): """* query* """ self.log.info('starting the ``_query`` method') try: response = requests.get( ...
def match(cls, field, query, operator=None): ''' A family of match queries that accept text/numerics/dates, analyzes it, and constructs a query out of it. For example: { "match" : { "message" : "this is a test" } } Note, message is the nam...
A family of match queries that accept text/numerics/dates, analyzes it, and constructs a query out of it. For example: { "match" : { "message" : "this is a test" } } Note, message is the name of a field, you can subsitute the name of any field (including ...
Below is the the instruction that describes the task: ### Input: A family of match queries that accept text/numerics/dates, analyzes it, and constructs a query out of it. For example: { "match" : { "message" : "this is a test" } } Note, message is the...
def permission_required(*actions, obj=None, raise_exception=False): """Permission checking decorator -- works like the ``permission_required`` decorator in the default Django authentication system, except that it takes a sequence of actions to check, an object must be supplied, and the user must have ...
Permission checking decorator -- works like the ``permission_required`` decorator in the default Django authentication system, except that it takes a sequence of actions to check, an object must be supplied, and the user must have permission to perform all of the actions on the given object for the ...
Below is the the instruction that describes the task: ### Input: Permission checking decorator -- works like the ``permission_required`` decorator in the default Django authentication system, except that it takes a sequence of actions to check, an object must be supplied, and the user must have perm...
def merge_lists(src, new): """Update a value list with a list of new or updated values.""" l_min, l_max = (src, new) if len(src) < len(new) else (new, src) l_min.extend(None for i in range(len(l_min), len(l_max))) for i, val in enumerate(new): if isinstance(val, dict) and isinstance(src[i], di...
Update a value list with a list of new or updated values.
Below is the the instruction that describes the task: ### Input: Update a value list with a list of new or updated values. ### Response: def merge_lists(src, new): """Update a value list with a list of new or updated values.""" l_min, l_max = (src, new) if len(src) < len(new) else (new, src) l_min.ext...
def DateStringToDateObject(date_string): """Return a date object for a string "YYYYMMDD".""" # If this becomes a bottleneck date objects could be cached if re.match('^\d{8}$', date_string) == None: return None try: return datetime.date(int(date_string[0:4]), int(date_string[4:6]), ...
Return a date object for a string "YYYYMMDD".
Below is the the instruction that describes the task: ### Input: Return a date object for a string "YYYYMMDD". ### Response: def DateStringToDateObject(date_string): """Return a date object for a string "YYYYMMDD".""" # If this becomes a bottleneck date objects could be cached if re.match('^\d{8}$', date_str...
def inflate_plugin_list(plugin_list, inflate_plugin): """ Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_list (list): a list of str/dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a ...
Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_list (list): a list of str/dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a plugin instances list. Raises: ValueError: when a dic...
Below is the the instruction that describes the task: ### Input: Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_list (list): a list of str/dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a plugi...
def blockChildrenSignals(self, block): """ If block equals True, the signals of the combo boxes and spin boxes are blocked Returns the old blocking state. """ logger.debug("Blocking collector signals") for spinBox in self._spinBoxes: spinBox.blockSignals(block) ...
If block equals True, the signals of the combo boxes and spin boxes are blocked Returns the old blocking state.
Below is the the instruction that describes the task: ### Input: If block equals True, the signals of the combo boxes and spin boxes are blocked Returns the old blocking state. ### Response: def blockChildrenSignals(self, block): """ If block equals True, the signals of the combo boxes and spin...
def get_chempot_correction(element, temp, pres): """ Get the normalized correction term Δμ for chemical potential of a gas phase consisting of element at given temperature and pressure, referenced to that in the standard state (T_std = 298.15 K, T_std = 1 bar). The gas phase is l...
Get the normalized correction term Δμ for chemical potential of a gas phase consisting of element at given temperature and pressure, referenced to that in the standard state (T_std = 298.15 K, T_std = 1 bar). The gas phase is limited to be one of O2, N2, Cl2, F2, H2. Calculation formula ...
Below is the the instruction that describes the task: ### Input: Get the normalized correction term Δμ for chemical potential of a gas phase consisting of element at given temperature and pressure, referenced to that in the standard state (T_std = 298.15 K, T_std = 1 bar). The gas phase is l...
def get_gsim_lt(oqparam, trts=['*']): """ :param oqparam: an :class:`openquake.commonlib.oqvalidation.OqParam` instance :param trts: a sequence of tectonic region types as strings; trts=['*'] means that there is no filtering :returns: a GsimLogicTree instance obtained by ...
:param oqparam: an :class:`openquake.commonlib.oqvalidation.OqParam` instance :param trts: a sequence of tectonic region types as strings; trts=['*'] means that there is no filtering :returns: a GsimLogicTree instance obtained by filtering on the provided tectonic region ...
Below is the the instruction that describes the task: ### Input: :param oqparam: an :class:`openquake.commonlib.oqvalidation.OqParam` instance :param trts: a sequence of tectonic region types as strings; trts=['*'] means that there is no filtering :returns: a GsimLogicTree in...
def hierarchy_flatten(annotation): '''Flatten a multi_segment annotation into mir_eval style. Parameters ---------- annotation : jams.Annotation An annotation in the `multi_segment` namespace Returns ------- hier_intervalss : list A list of lists of intervals, ordered by in...
Flatten a multi_segment annotation into mir_eval style. Parameters ---------- annotation : jams.Annotation An annotation in the `multi_segment` namespace Returns ------- hier_intervalss : list A list of lists of intervals, ordered by increasing specificity. hier_labels : l...
Below is the the instruction that describes the task: ### Input: Flatten a multi_segment annotation into mir_eval style. Parameters ---------- annotation : jams.Annotation An annotation in the `multi_segment` namespace Returns ------- hier_intervalss : list A list of lists ...
def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) if not attr.startswith('_') and callable(getattr(obj, attr)) )
Return the names of all callable attributes of an object
Below is the the instruction that describes the task: ### Input: Return the names of all callable attributes of an object ### Response: def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) ...
def monitor(self, field, callback, poll_interval=None): """ Monitor `field` for change Will monitor ``field`` for change and execute ``callback`` when change is detected. Example usage:: def handle(resource, field, previous, current): print "Change from {} ...
Monitor `field` for change Will monitor ``field`` for change and execute ``callback`` when change is detected. Example usage:: def handle(resource, field, previous, current): print "Change from {} to {}".format(previous, current) switch = TapSwitch.obj...
Below is the the instruction that describes the task: ### Input: Monitor `field` for change Will monitor ``field`` for change and execute ``callback`` when change is detected. Example usage:: def handle(resource, field, previous, current): print "Change from {}...
def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1): """ Approximate computation of minimal eigenvalues in tensor train format This function uses alternating least-squares algorithm for the computation of several minimal eigenvalues. If you want maximal eigenvalues, just send -A to the funct...
Approximate computation of minimal eigenvalues in tensor train format This function uses alternating least-squares algorithm for the computation of several minimal eigenvalues. If you want maximal eigenvalues, just send -A to the function. :Reference: S. V. Dolgov, B. N. Khoromskij, I. V. Oselede...
Below is the the instruction that describes the task: ### Input: Approximate computation of minimal eigenvalues in tensor train format This function uses alternating least-squares algorithm for the computation of several minimal eigenvalues. If you want maximal eigenvalues, just send -A to the function. ...
def process_quotes(self, text): """Process quotes.""" escaped = False in_quotes = False current = [] quoted = [] i = _util.StringIter(text) iter(i) for t in i: if not escaped and t == "\\": escaped = True elif escap...
Process quotes.
Below is the the instruction that describes the task: ### Input: Process quotes. ### Response: def process_quotes(self, text): """Process quotes.""" escaped = False in_quotes = False current = [] quoted = [] i = _util.StringIter(text) iter(i) for t i...
def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name ''' write_mtl: When True and mesh has a texture, includes a mtllib reference in the .obj and writes a .mtl alongside. ''' import os import numpy as np...
write_mtl: When True and mesh has a texture, includes a mtllib reference in the .obj and writes a .mtl alongside.
Below is the the instruction that describes the task: ### Input: write_mtl: When True and mesh has a texture, includes a mtllib reference in the .obj and writes a .mtl alongside. ### Response: def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: di...
def set_stack(self, stack_dump, stack_top): """ Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command : ``dump binary memory [stack_dump] [begin_addr] [end_addr]`` We set the stack to the same addresses as the gdb session to avoid pointers corruption....
Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command : ``dump binary memory [stack_dump] [begin_addr] [end_addr]`` We set the stack to the same addresses as the gdb session to avoid pointers corruption. :param stack_dump: The dump file. :param stac...
Below is the the instruction that describes the task: ### Input: Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command : ``dump binary memory [stack_dump] [begin_addr] [end_addr]`` We set the stack to the same addresses as the gdb session to avoid pointers corrup...
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._country is not None: return False if self._expiry_time is not None: return False return True
:rtype: bool
Below is the the instruction that describes the task: ### Input: :rtype: bool ### Response: def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._country is not None: return False if self._expiry_...
def _set_authentication_key(self, v, load=False): """ Setter method for authentication_key, mapped from YANG variable /ntp/authentication_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_authentication_key is considered as a private method. Backends looking...
Setter method for authentication_key, mapped from YANG variable /ntp/authentication_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_authentication_key is considered as a private method. Backends looking to populate this variable should do so via calling thisOb...
Below is the the instruction that describes the task: ### Input: Setter method for authentication_key, mapped from YANG variable /ntp/authentication_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_authentication_key is considered as a private method. Backends ...
def from_pyvalue(name, value, **kwargs): """ Convenience wrapper for new_param() that constructs a Param element from an instance of a Python builtin type. See new_param() for a description of the valid keyword arguments. """ return new_param(name, ligolwtypes.FromPyType[type(value)], value, **kwargs)
Convenience wrapper for new_param() that constructs a Param element from an instance of a Python builtin type. See new_param() for a description of the valid keyword arguments.
Below is the the instruction that describes the task: ### Input: Convenience wrapper for new_param() that constructs a Param element from an instance of a Python builtin type. See new_param() for a description of the valid keyword arguments. ### Response: def from_pyvalue(name, value, **kwargs): """ Convenien...
def make_attributes(s, gff3=True, keep_attr_order=True): """ In GFF3, the last column is typically: ID=cds00002;Parent=mRNA00002; In GFF2, the last column is typically: Gene 22240.t000374; Note "Carbonic anhydrase" """ if gff3: """ hack: temporarily replace the '+' sign in t...
In GFF3, the last column is typically: ID=cds00002;Parent=mRNA00002; In GFF2, the last column is typically: Gene 22240.t000374; Note "Carbonic anhydrase"
Below is the the instruction that describes the task: ### Input: In GFF3, the last column is typically: ID=cds00002;Parent=mRNA00002; In GFF2, the last column is typically: Gene 22240.t000374; Note "Carbonic anhydrase" ### Response: def make_attributes(s, gff3=True, keep_attr_order=True): """ ...
def postprocess(self, images, augmenter, parents): """ A function to be called after the augmentation of images was performed. Returns ------- (N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray The input images, optionall...
A function to be called after the augmentation of images was performed. Returns ------- (N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray The input images, optionally modified.
Below is the the instruction that describes the task: ### Input: A function to be called after the augmentation of images was performed. Returns ------- (N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray The input images, optionally ...
def _set_hundredgigabitethernet(self, v, load=False): """ Setter method for hundredgigabitethernet, mapped from YANG variable /interface/hundredgigabitethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_hundredgigabitethernet is considered as a private me...
Setter method for hundredgigabitethernet, mapped from YANG variable /interface/hundredgigabitethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_hundredgigabitethernet is considered as a private method. Backends looking to populate this variable should do so ...
Below is the the instruction that describes the task: ### Input: Setter method for hundredgigabitethernet, mapped from YANG variable /interface/hundredgigabitethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_hundredgigabitethernet is considered as a private ...
def build_mismatched_common_meta_report(common_meta_df_shapes, sources, all_meta_df, all_meta_df_with_dups): """ Generate a report (dataframe) that indicates for the common metadata that does not match across the common metadata which source file had which of the different mismatch values Args: ...
Generate a report (dataframe) that indicates for the common metadata that does not match across the common metadata which source file had which of the different mismatch values Args: common_meta_df_shapes: list of tuples that are the shapes of the common meta dataframes sources: list of th...
Below is the the instruction that describes the task: ### Input: Generate a report (dataframe) that indicates for the common metadata that does not match across the common metadata which source file had which of the different mismatch values Args: common_meta_df_shapes: list of tuples that are...
def renegotiate_keys(self): """ Force this session to switch to new keys. Normally this is done automatically after the session hits a certain number of packets or bytes sent or received, but this method gives you the option of forcing new keys whenever you want. Negotiating ne...
Force this session to switch to new keys. Normally this is done automatically after the session hits a certain number of packets or bytes sent or received, but this method gives you the option of forcing new keys whenever you want. Negotiating new keys causes a pause in traffic both wa...
Below is the the instruction that describes the task: ### Input: Force this session to switch to new keys. Normally this is done automatically after the session hits a certain number of packets or bytes sent or received, but this method gives you the option of forcing new keys whenever you ...
def get_t(self, var, coords=None): """ Get the time coordinate of a variable This method searches for the time coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'T', otherwise it looks whether there is an interse...
Get the time coordinate of a variable This method searches for the time coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'T', otherwise it looks whether there is an intersection between the :attr:`t` attribute and the v...
Below is the the instruction that describes the task: ### Input: Get the time coordinate of a variable This method searches for the time coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'T', otherwise it looks whether there...
def get_display_names_metadata(self): """Gets the metadata for all display_names. return: (osid.Metadata) - metadata for the display_names *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._display_names_metadata) metadata.update({'exi...
Gets the metadata for all display_names. return: (osid.Metadata) - metadata for the display_names *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the metadata for all display_names. return: (osid.Metadata) - metadata for the display_names *compliance: mandatory -- This method must be implemented.* ### Response: def get_display_names_metadata(self): """Gets the met...
def ifft(invec, outvec): """ Inverse fourier transform from invec to outvec. Perform an inverse fourier transform. The type of transform is determined by the dtype of invec and outvec. Parameters ---------- invec : TimeSeries or FrequencySeries The input vector. outvec : TimeSeries...
Inverse fourier transform from invec to outvec. Perform an inverse fourier transform. The type of transform is determined by the dtype of invec and outvec. Parameters ---------- invec : TimeSeries or FrequencySeries The input vector. outvec : TimeSeries or FrequencySeries The o...
Below is the the instruction that describes the task: ### Input: Inverse fourier transform from invec to outvec. Perform an inverse fourier transform. The type of transform is determined by the dtype of invec and outvec. Parameters ---------- invec : TimeSeries or FrequencySeries The i...
def parse_arguments(argv): """Setup argument parser for command line arguments.""" parser = argparse.ArgumentParser(description=__doc__.format(__version__)) parser.add_argument('--application', '-a', dest='application', choices=scraper.APPLICATIONS, ...
Setup argument parser for command line arguments.
Below is the the instruction that describes the task: ### Input: Setup argument parser for command line arguments. ### Response: def parse_arguments(argv): """Setup argument parser for command line arguments.""" parser = argparse.ArgumentParser(description=__doc__.format(__version__)) parser.add_argume...
def order_by_line_nos(objs, line_nos): """Orders the set of `objs` by `line_nos` """ ordering = sorted(range(len(line_nos)), key=line_nos.__getitem__) return [objs[i] for i in ordering]
Orders the set of `objs` by `line_nos`
Below is the the instruction that describes the task: ### Input: Orders the set of `objs` by `line_nos` ### Response: def order_by_line_nos(objs, line_nos): """Orders the set of `objs` by `line_nos` """ ordering = sorted(range(len(line_nos)), key=line_nos.__getitem__) return [objs[i] for i in order...
def has_header_encryption(self): """Returns True if headers are encrypted """ if self._hdrenc_main: return True if self._main: if self._main.flags & RAR_MAIN_PASSWORD: return True return False
Returns True if headers are encrypted
Below is the the instruction that describes the task: ### Input: Returns True if headers are encrypted ### Response: def has_header_encryption(self): """Returns True if headers are encrypted """ if self._hdrenc_main: return True if self._main: if self._main.f...
def handleResponse(self, response): """Handle the response string received by KafkaProtocol. Ok, we've received the response from the broker. Find the requestId in the message, lookup & fire the deferred with the response. """ requestId = KafkaCodec.get_response_correlation_id(r...
Handle the response string received by KafkaProtocol. Ok, we've received the response from the broker. Find the requestId in the message, lookup & fire the deferred with the response.
Below is the the instruction that describes the task: ### Input: Handle the response string received by KafkaProtocol. Ok, we've received the response from the broker. Find the requestId in the message, lookup & fire the deferred with the response. ### Response: def handleResponse(self, response):...
async def shutdown(self, timeout: Optional[float]=15.0) -> None: """Worker process is about to exit, we need cleanup everything and stop accepting requests. It is especially important for keep-alive connections.""" self._force_close = True if self._keepalive_handle is not None: ...
Worker process is about to exit, we need cleanup everything and stop accepting requests. It is especially important for keep-alive connections.
Below is the the instruction that describes the task: ### Input: Worker process is about to exit, we need cleanup everything and stop accepting requests. It is especially important for keep-alive connections. ### Response: async def shutdown(self, timeout: Optional[float]=15.0) -> None: """...
def from_str(cls, input_string, fmt, primitive=False, sort=False, merge_tol=0.0): """ Reads a structure from a string. Args: input_string (str): String to parse. fmt (str): A format specification. primitive (bool): Whether to find a primitive...
Reads a structure from a string. Args: input_string (str): String to parse. fmt (str): A format specification. primitive (bool): Whether to find a primitive cell. Defaults to False. sort (bool): Whether to sort the sites in accordance to the defau...
Below is the the instruction that describes the task: ### Input: Reads a structure from a string. Args: input_string (str): String to parse. fmt (str): A format specification. primitive (bool): Whether to find a primitive cell. Defaults to False. ...
async def presentProof(self, proofRequest: ProofRequest) -> FullProof: """ Presents a proof to the verifier. :param proofRequest: description of a proof to be presented (revealed attributes, predicates, timestamps for non-revocation) :return: a proof (both primary and non-revoca...
Presents a proof to the verifier. :param proofRequest: description of a proof to be presented (revealed attributes, predicates, timestamps for non-revocation) :return: a proof (both primary and non-revocation) and revealed attributes (initial non-encoded values)
Below is the the instruction that describes the task: ### Input: Presents a proof to the verifier. :param proofRequest: description of a proof to be presented (revealed attributes, predicates, timestamps for non-revocation) :return: a proof (both primary and non-revocation) and revealed att...
def collapse_to_consensus(seqrecords, strict=False, do_iron=True): """Opposite of realign_seqs. Input sequences should all be the same length. The first record must be the consensus. """ level = 0 name = seqrecords[0].id # If this is a CMA alignment, extract additional info: if hasattr...
Opposite of realign_seqs. Input sequences should all be the same length. The first record must be the consensus.
Below is the the instruction that describes the task: ### Input: Opposite of realign_seqs. Input sequences should all be the same length. The first record must be the consensus. ### Response: def collapse_to_consensus(seqrecords, strict=False, do_iron=True): """Opposite of realign_seqs. Input se...
def checkout(self, _hash: str) -> None: """ Checkout the repo at the speficied commit. BE CAREFUL: this will change the state of the repo, hence it should *not* be used with more than 1 thread. :param _hash: commit hash to checkout """ with self.lock: ...
Checkout the repo at the speficied commit. BE CAREFUL: this will change the state of the repo, hence it should *not* be used with more than 1 thread. :param _hash: commit hash to checkout
Below is the the instruction that describes the task: ### Input: Checkout the repo at the speficied commit. BE CAREFUL: this will change the state of the repo, hence it should *not* be used with more than 1 thread. :param _hash: commit hash to checkout ### Response: def checkout(self, _has...
def weingarten_image_curvature(image, sigma=1.0, opt='mean'): """ Uses the weingarten map to estimate image mean or gaussian curvature ANTsR function: `weingartenImageCurvature` Arguments --------- image : ANTsImage image from which curvature is calculated sigma : scalar ...
Uses the weingarten map to estimate image mean or gaussian curvature ANTsR function: `weingartenImageCurvature` Arguments --------- image : ANTsImage image from which curvature is calculated sigma : scalar smoothing parameter opt : string mean by default, ...
Below is the the instruction that describes the task: ### Input: Uses the weingarten map to estimate image mean or gaussian curvature ANTsR function: `weingartenImageCurvature` Arguments --------- image : ANTsImage image from which curvature is calculated sigma : scalar ...
def cursor_before(self): """Return the cursor before the current item. You must pass a QueryOptions object with produce_cursors=True for this to work. If there is no cursor or no current item, raise BadArgumentError. Before next() has returned there is no cursor. Once the loop is exhausted, t...
Return the cursor before the current item. You must pass a QueryOptions object with produce_cursors=True for this to work. If there is no cursor or no current item, raise BadArgumentError. Before next() has returned there is no cursor. Once the loop is exhausted, this returns the cursor after the...
Below is the the instruction that describes the task: ### Input: Return the cursor before the current item. You must pass a QueryOptions object with produce_cursors=True for this to work. If there is no cursor or no current item, raise BadArgumentError. Before next() has returned there is no curso...
def marginal_distribution(self, variables, inplace=True): """ Returns the marginal distribution over variables. Parameters ---------- variables: string, list, tuple, set, dict Variable or list of variables over which marginal distribution needs to...
Returns the marginal distribution over variables. Parameters ---------- variables: string, list, tuple, set, dict Variable or list of variables over which marginal distribution needs to be calculated inplace: Boolean (default True) If Fals...
Below is the the instruction that describes the task: ### Input: Returns the marginal distribution over variables. Parameters ---------- variables: string, list, tuple, set, dict Variable or list of variables over which marginal distribution needs to be calcu...
def _render_headers(self, sheet): """ Write the headers row :param obj sheet: an odswriter Sheet object """ headers = getattr(self, 'headers', ()) labels = [header['label'] for header in headers] extra_headers = getattr(self, "extra_headers", ()) labels.e...
Write the headers row :param obj sheet: an odswriter Sheet object
Below is the the instruction that describes the task: ### Input: Write the headers row :param obj sheet: an odswriter Sheet object ### Response: def _render_headers(self, sheet): """ Write the headers row :param obj sheet: an odswriter Sheet object """ headers = ge...