code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _load_version(cls, unpickler, version): """ An function to load an object with a specific version of the class. Parameters ---------- pickler : file A GLUnpickler file handle. version : int A version number as maintained by the class writer. ...
An function to load an object with a specific version of the class. Parameters ---------- pickler : file A GLUnpickler file handle. version : int A version number as maintained by the class writer.
Below is the the instruction that describes the task: ### Input: An function to load an object with a specific version of the class. Parameters ---------- pickler : file A GLUnpickler file handle. version : int A version number as maintained by the class wri...
def del_param(self, param, header='content-type', requote=True): """Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional he...
Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header.
Below is the the instruction that describes the task: ### Input: Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header sp...
def update_container(self, container, metadata, **kwargs): """Update container metadata :param container: container name (Container is equivalent to Bucket term in Amazon). :param metadata(dict): additional metadata to include in the request. :param **kwargs(di...
Update container metadata :param container: container name (Container is equivalent to Bucket term in Amazon). :param metadata(dict): additional metadata to include in the request. :param **kwargs(dict): extend args for specific driver.
Below is the the instruction that describes the task: ### Input: Update container metadata :param container: container name (Container is equivalent to Bucket term in Amazon). :param metadata(dict): additional metadata to include in the request. :param **kwargs(dic...
def add_rows(self, list_of_rows): """Add a list of rows to the DataFrameCache class""" for row in list_of_rows: self.row_deque.append(row) self.time_deque.append(time.time()) # Update the data structure self.update()
Add a list of rows to the DataFrameCache class
Below is the the instruction that describes the task: ### Input: Add a list of rows to the DataFrameCache class ### Response: def add_rows(self, list_of_rows): """Add a list of rows to the DataFrameCache class""" for row in list_of_rows: self.row_deque.append(row) self.time_...
def getBitmap(self): """ Captures screen area of this region, at least the part that is on the screen Returns image as numpy array """ return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h)
Captures screen area of this region, at least the part that is on the screen Returns image as numpy array
Below is the the instruction that describes the task: ### Input: Captures screen area of this region, at least the part that is on the screen Returns image as numpy array ### Response: def getBitmap(self): """ Captures screen area of this region, at least the part that is on the screen Re...
def eoq(I,F,h,d,w,W,a0,aK,K): """eoq -- multi-item capacitated economic ordering quantity model Parameters: - I: set of items - F[i]: ordering cost for item i - h[i]: holding cost for item i - d[i]: demand for item i - w[i]: unit weight for item i - W: capacity (...
eoq -- multi-item capacitated economic ordering quantity model Parameters: - I: set of items - F[i]: ordering cost for item i - h[i]: holding cost for item i - d[i]: demand for item i - w[i]: unit weight for item i - W: capacity (limit on order quantity) - a0...
Below is the the instruction that describes the task: ### Input: eoq -- multi-item capacitated economic ordering quantity model Parameters: - I: set of items - F[i]: ordering cost for item i - h[i]: holding cost for item i - d[i]: demand for item i - w[i]: unit weight fo...
def create_user_task(sender=None, body=None, **kwargs): # pylint: disable=unused-argument """ Create a :py:class:`UserTaskStatus` record for each :py:class:`UserTaskMixin`. Also creates a :py:class:`UserTaskStatus` for each chain, chord, or group containing the new :py:class:`UserTaskMixin`. """ ...
Create a :py:class:`UserTaskStatus` record for each :py:class:`UserTaskMixin`. Also creates a :py:class:`UserTaskStatus` for each chain, chord, or group containing the new :py:class:`UserTaskMixin`.
Below is the the instruction that describes the task: ### Input: Create a :py:class:`UserTaskStatus` record for each :py:class:`UserTaskMixin`. Also creates a :py:class:`UserTaskStatus` for each chain, chord, or group containing the new :py:class:`UserTaskMixin`. ### Response: def create_user_task(sender=...
def display_weyl(decomps): """Construct and display 3D plot of canonical coordinates""" tx, ty, tz = list(zip(*decomps)) rcParams['axes.labelsize'] = 24 rcParams['font.family'] = 'serif' rcParams['font.serif'] = ['Computer Modern Roman'] rcParams['text.usetex'] = True fig = pyplot.figure() ...
Construct and display 3D plot of canonical coordinates
Below is the the instruction that describes the task: ### Input: Construct and display 3D plot of canonical coordinates ### Response: def display_weyl(decomps): """Construct and display 3D plot of canonical coordinates""" tx, ty, tz = list(zip(*decomps)) rcParams['axes.labelsize'] = 24 rcParams['f...
def parse_arguments(argv): """Parse the command line arguments.""" parser = argparse.ArgumentParser( description=('Train a regression or classification model. Note that if ' 'using a DNN model, --layer-size1=NUM, --layer-size2=NUM, ' 'should be used. ')) # I/O file par...
Parse the command line arguments.
Below is the the instruction that describes the task: ### Input: Parse the command line arguments. ### Response: def parse_arguments(argv): """Parse the command line arguments.""" parser = argparse.ArgumentParser( description=('Train a regression or classification model. Note that if ' ...
def plot_phens_circles(phen_grid, **kwargs): """ Plots phenotypes represented as concentric circles. Each circle represents one task that the phenotype can perform, with larger circles representing more complex tasks. Arguments: phen_grid - a 2D array of strings representing binary numbers kwa...
Plots phenotypes represented as concentric circles. Each circle represents one task that the phenotype can perform, with larger circles representing more complex tasks. Arguments: phen_grid - a 2D array of strings representing binary numbers kwargs: palette - a seaborn palette (list of ...
Below is the the instruction that describes the task: ### Input: Plots phenotypes represented as concentric circles. Each circle represents one task that the phenotype can perform, with larger circles representing more complex tasks. Arguments: phen_grid - a 2D array of strings representing binary numb...
def _encode_timestamp(name, value, dummy0, dummy1): """Encode bson.timestamp.Timestamp.""" return b"\x11" + name + _PACK_TIMESTAMP(value.inc, value.time)
Encode bson.timestamp.Timestamp.
Below is the the instruction that describes the task: ### Input: Encode bson.timestamp.Timestamp. ### Response: def _encode_timestamp(name, value, dummy0, dummy1): """Encode bson.timestamp.Timestamp.""" return b"\x11" + name + _PACK_TIMESTAMP(value.inc, value.time)
def OnRangeSelected(self, event): """Event handler for grid selection""" # If grid editing is disabled then pyspread is in selection mode if not self.grid.IsEditable(): selection = self.grid.selection row, col, __ = self.grid.sel_mode_cursor if (row, col) in ...
Event handler for grid selection
Below is the the instruction that describes the task: ### Input: Event handler for grid selection ### Response: def OnRangeSelected(self, event): """Event handler for grid selection""" # If grid editing is disabled then pyspread is in selection mode if not self.grid.IsEditable(): ...
def _settings(self) -> Settings: """ Return the actual settings object, or create it if missing. """ if self.__dict__['__settings'] is None: self.__dict__['__settings'] = Settings() for file_path in self._get_files(): if file_path: ...
Return the actual settings object, or create it if missing.
Below is the the instruction that describes the task: ### Input: Return the actual settings object, or create it if missing. ### Response: def _settings(self) -> Settings: """ Return the actual settings object, or create it if missing. """ if self.__dict__['__settings'] is None: ...
def _get_veths(net_data): ''' Parse the nic setup inside lxc conf tuples back to a dictionary indexed by network interface ''' if isinstance(net_data, dict): net_data = list(net_data.items()) nics = salt.utils.odict.OrderedDict() current_nic = salt.utils.odict.OrderedDict() no_na...
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by network interface
Below is the the instruction that describes the task: ### Input: Parse the nic setup inside lxc conf tuples back to a dictionary indexed by network interface ### Response: def _get_veths(net_data): ''' Parse the nic setup inside lxc conf tuples back to a dictionary indexed by network interface ...
def exec_(argv): # never returns """Wrapper to os.execv which shows the command and runs any atexit handlers (for coverage's sake). Like os.execv, this function never returns. """ # info('EXEC' + colorize(argv)) # TODO: debug logging by environment variable # in python3, sys.exitfunc has gone awa...
Wrapper to os.execv which shows the command and runs any atexit handlers (for coverage's sake). Like os.execv, this function never returns.
Below is the the instruction that describes the task: ### Input: Wrapper to os.execv which shows the command and runs any atexit handlers (for coverage's sake). Like os.execv, this function never returns. ### Response: def exec_(argv): # never returns """Wrapper to os.execv which shows the command and run...
def _to_autoassign(self): """Save :class:`~nmrstarlib.plsimulator.PeakList` into AutoAssign-formatted string. :return: Peak list representation in AutoAssign format. :rtype: :py:class:`str` """ autoassign_str = "#Index\t\t{}\t\tIntensity\t\tWorkbook\n".format( "\t\t"...
Save :class:`~nmrstarlib.plsimulator.PeakList` into AutoAssign-formatted string. :return: Peak list representation in AutoAssign format. :rtype: :py:class:`str`
Below is the the instruction that describes the task: ### Input: Save :class:`~nmrstarlib.plsimulator.PeakList` into AutoAssign-formatted string. :return: Peak list representation in AutoAssign format. :rtype: :py:class:`str` ### Response: def _to_autoassign(self): """Save :class:`~nmrstar...
def set(self, val): """Set the value""" import time now = time.time() expected_value = [] new_val = {} new_val['timestamp'] = now if self._value != None: new_val['last_value'] = self._value expected_value = ['current_value', str(self._value...
Set the value
Below is the the instruction that describes the task: ### Input: Set the value ### Response: def set(self, val): """Set the value""" import time now = time.time() expected_value = [] new_val = {} new_val['timestamp'] = now if self._value != None: ...
def first_plugin_context(self): """Returns the context is associated with the first app this plugin was registered on""" # Note, because registrations are stored in a set, its not _really_ # the first one, but whichever one it sees first in the set. first_spf_reg = next(iter(sel...
Returns the context is associated with the first app this plugin was registered on
Below is the the instruction that describes the task: ### Input: Returns the context is associated with the first app this plugin was registered on ### Response: def first_plugin_context(self): """Returns the context is associated with the first app this plugin was registered on""" ...
def duration(label, stop_it=True, stop_at=None): """Returns duration in seconds for label""" if label not in labels: return None if "duration" in labels[label]: return Duration(labels[label]["duration"]) if stop_it: return stop(label, at=stop_at) else: return None
Returns duration in seconds for label
Below is the the instruction that describes the task: ### Input: Returns duration in seconds for label ### Response: def duration(label, stop_it=True, stop_at=None): """Returns duration in seconds for label""" if label not in labels: return None if "duration" in labels[label]: return ...
def save(filename, rsrc): "Save the resource to the source file" s = pprint.pformat(rsrc) ## s = s.encode("utf8") open(filename, "w").write(s)
Save the resource to the source file
Below is the the instruction that describes the task: ### Input: Save the resource to the source file ### Response: def save(filename, rsrc): "Save the resource to the source file" s = pprint.pformat(rsrc) ## s = s.encode("utf8") open(filename, "w").write(s)
def _compute_gridspec(self, layout): """ Computes the tallest and widest cell for each row and column by examining the Layouts in the GridSpace. The GridSpec is then instantiated and the LayoutPlots are configured with the appropriate embedded layout_types. The first element of t...
Computes the tallest and widest cell for each row and column by examining the Layouts in the GridSpace. The GridSpec is then instantiated and the LayoutPlots are configured with the appropriate embedded layout_types. The first element of the returned tuple is a dictionary of all the Layo...
Below is the the instruction that describes the task: ### Input: Computes the tallest and widest cell for each row and column by examining the Layouts in the GridSpace. The GridSpec is then instantiated and the LayoutPlots are configured with the appropriate embedded layout_types. The first ...
def get_under_bridge(self): """Return element closest to the adsorbate in the subsurface layer""" C0 = self.B[-1:] * (3, 3, 1) ads_pos = C0.positions[4] C = self.get_subsurface_layer() * (3, 3, 1) dis = self.B.cell[0][0] * 2 ret = None for ele in C: ...
Return element closest to the adsorbate in the subsurface layer
Below is the the instruction that describes the task: ### Input: Return element closest to the adsorbate in the subsurface layer ### Response: def get_under_bridge(self): """Return element closest to the adsorbate in the subsurface layer""" C0 = self.B[-1:] * (3, 3, 1) ads_pos = C0.position...
def addAttachment(self, filepath): """Upload attachment to a workitem :param filepath: the attachment file path :return: the :class:`rtcclient.models.Attachment` object :rtype: rtcclient.models.Attachment """ proj_id = self.contextId fa = self.rtc_obj.getFiledA...
Upload attachment to a workitem :param filepath: the attachment file path :return: the :class:`rtcclient.models.Attachment` object :rtype: rtcclient.models.Attachment
Below is the the instruction that describes the task: ### Input: Upload attachment to a workitem :param filepath: the attachment file path :return: the :class:`rtcclient.models.Attachment` object :rtype: rtcclient.models.Attachment ### Response: def addAttachment(self, filepath): "...
def _singleton_method(name): """Return a function to the `name` method on a singleton `coverage` object. The singleton object is created the first time one of these functions is called. """ # Disable pylint msg W0612, because a bunch of variables look unused, but # they're accessed via locals(...
Return a function to the `name` method on a singleton `coverage` object. The singleton object is created the first time one of these functions is called.
Below is the the instruction that describes the task: ### Input: Return a function to the `name` method on a singleton `coverage` object. The singleton object is created the first time one of these functions is called. ### Response: def _singleton_method(name): """Return a function to the `name` metho...
def _find_files(dl_paths, publisher, url_dict): """Find files corresponding to urls.""" if publisher == 'cnn': top_dir = os.path.join(dl_paths['cnn_stories'], 'cnn', 'stories') elif publisher == 'dm': top_dir = os.path.join(dl_paths['dm_stories'], 'dailymail', 'stories') else: logging.fatal('Unsuppo...
Find files corresponding to urls.
Below is the the instruction that describes the task: ### Input: Find files corresponding to urls. ### Response: def _find_files(dl_paths, publisher, url_dict): """Find files corresponding to urls.""" if publisher == 'cnn': top_dir = os.path.join(dl_paths['cnn_stories'], 'cnn', 'stories') elif publisher ...
def render(self, data, accepted_media_type=None, renderer_context=None): """ Render the HTML for the browsable API representation. """ self.accepted_media_type = accepted_media_type or '' self.renderer_context = renderer_context or {} template = loader.get_template(self....
Render the HTML for the browsable API representation.
Below is the the instruction that describes the task: ### Input: Render the HTML for the browsable API representation. ### Response: def render(self, data, accepted_media_type=None, renderer_context=None): """ Render the HTML for the browsable API representation. """ self.accepted_m...
def get_mongoadmins(self): """ Returns a list of all mongoadmin implementations for the site """ apps = [] for app_name in settings.INSTALLED_APPS: mongoadmin = "{0}.mongoadmin".format(app_name) try: module = import_module(mongoadmin) except Im...
Returns a list of all mongoadmin implementations for the site
Below is the the instruction that describes the task: ### Input: Returns a list of all mongoadmin implementations for the site ### Response: def get_mongoadmins(self): """ Returns a list of all mongoadmin implementations for the site """ apps = [] for app_name in settings.INSTALLED_APPS: ...
def do_quit(self, arg): """ quit - close the debugging session q - close the debugging session """ if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.confirm_quit: count ...
quit - close the debugging session q - close the debugging session
Below is the the instruction that describes the task: ### Input: quit - close the debugging session q - close the debugging session ### Response: def do_quit(self, arg): """ quit - close the debugging session q - close the debugging session """ if self.cmdprefix: ...
def get_variable_value_for_variation(self, variable, variation): """ Get the variable value for the given variation. Args: variable: The Variable for which we are getting the value. variation: The Variation for which we are getting the variable value. Returns: The variable value or None ...
Get the variable value for the given variation. Args: variable: The Variable for which we are getting the value. variation: The Variation for which we are getting the variable value. Returns: The variable value or None if any of the inputs are invalid.
Below is the the instruction that describes the task: ### Input: Get the variable value for the given variation. Args: variable: The Variable for which we are getting the value. variation: The Variation for which we are getting the variable value. Returns: The variable value or None if a...
def config_reader(self, config_level=None): """ :return: GitConfigParser allowing to read the full git configuration, but not to write it The configuration will include values from the system, user and repository configuration files. :param config_level: ...
:return: GitConfigParser allowing to read the full git configuration, but not to write it The configuration will include values from the system, user and repository configuration files. :param config_level: For possible values, see config_writer method ...
Below is the the instruction that describes the task: ### Input: :return: GitConfigParser allowing to read the full git configuration, but not to write it The configuration will include values from the system, user and repository configuration files. :param config_level...
def _readPermutationsFile(self, filename, modelDescription): """ Read the permutations file and initialize the following member variables: _predictedField: field name of the field we are trying to predict _permutations: Dict containing the full permutations dictionary. _flatten...
Read the permutations file and initialize the following member variables: _predictedField: field name of the field we are trying to predict _permutations: Dict containing the full permutations dictionary. _flattenedPermutations: Dict containing the flattened version of _permu...
Below is the the instruction that describes the task: ### Input: Read the permutations file and initialize the following member variables: _predictedField: field name of the field we are trying to predict _permutations: Dict containing the full permutations dictionary. _flattenedPe...
def load_grid(self, alpha): '''Load grid and calculate alpha values from the coverage/2.5. ''' grid = CRGrid.crt_grid(self.dirs[0] + '/grid/elem.dat', self.dirs[0] + '/grid/elec.dat') self.plotman = CRPlot.plotManager(grid=grid) name = self.dirs[0]...
Load grid and calculate alpha values from the coverage/2.5.
Below is the the instruction that describes the task: ### Input: Load grid and calculate alpha values from the coverage/2.5. ### Response: def load_grid(self, alpha): '''Load grid and calculate alpha values from the coverage/2.5. ''' grid = CRGrid.crt_grid(self.dirs[0] + '/grid/elem.dat', ...
def b6_verifier(entries, line=None): """Raises error if invalid B6/M8 format detected Args: entries (list): A list of B6Entry instances line (int): Line number of first entry Raises: FormatError: Error when B6/M8 format incorrect with descriptive message Example: >>> ...
Raises error if invalid B6/M8 format detected Args: entries (list): A list of B6Entry instances line (int): Line number of first entry Raises: FormatError: Error when B6/M8 format incorrect with descriptive message Example: >>> from bio_utils.iterators import b6_iter ...
Below is the the instruction that describes the task: ### Input: Raises error if invalid B6/M8 format detected Args: entries (list): A list of B6Entry instances line (int): Line number of first entry Raises: FormatError: Error when B6/M8 format incorrect with descriptive message ...
def move_dirty_lock_file(dirty_lock_file, sm_path): """ Move the dirt_lock file to the sm_path and thereby is not found by auto recovery of backup anymore """ if dirty_lock_file is not None \ and not dirty_lock_file == os.path.join(sm_path, dirty_lock_file.split(os.sep)[-1]): logger.debug("M...
Move the dirt_lock file to the sm_path and thereby is not found by auto recovery of backup anymore
Below is the the instruction that describes the task: ### Input: Move the dirt_lock file to the sm_path and thereby is not found by auto recovery of backup anymore ### Response: def move_dirty_lock_file(dirty_lock_file, sm_path): """ Move the dirt_lock file to the sm_path and thereby is not found by auto recov...
def kernel_shap_1000_meanref(model, data): """ Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid """ return lambda X: KernelExplainer(model.predict, kmeans(data, 1)).shap_values(X, nsamples=1000, l1_reg=0)
Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid
Below is the the instruction that describes the task: ### Input: Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid ### Response: def kernel_shap_1000_meanref(model, data): """ Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid """ return la...
def reductions(fn, seq, acc=None): """Return the intermediate values of a reduction :param fn: a function :param seq: a sequence :param acc: the accumulator :returns: a list >>> reductions(lambda x, y: x + y, [1, 2, 3]) [1, 3, 6] >>> reductions(lambda x, y: x + y, [1, 2, 3], 10) [...
Return the intermediate values of a reduction :param fn: a function :param seq: a sequence :param acc: the accumulator :returns: a list >>> reductions(lambda x, y: x + y, [1, 2, 3]) [1, 3, 6] >>> reductions(lambda x, y: x + y, [1, 2, 3], 10) [11, 13, 16]
Below is the the instruction that describes the task: ### Input: Return the intermediate values of a reduction :param fn: a function :param seq: a sequence :param acc: the accumulator :returns: a list >>> reductions(lambda x, y: x + y, [1, 2, 3]) [1, 3, 6] >>> reductions(lambda x, y: ...
def construct_kde(samples_array, use_kombine=False): """Constructs a KDE from the given samples. """ if use_kombine: try: import kombine except ImportError: raise ImportError("kombine is not installed.") # construct the kde if use_kombine: kde = kombin...
Constructs a KDE from the given samples.
Below is the the instruction that describes the task: ### Input: Constructs a KDE from the given samples. ### Response: def construct_kde(samples_array, use_kombine=False): """Constructs a KDE from the given samples. """ if use_kombine: try: import kombine except ImportError...
def hybrid_forward(self, F, words1, words2, words3): # pylint: disable=arguments-differ, unused-argument """Compute analogies for given question words. Parameters ---------- words1 : Symbol or NDArray Word indices of first question words. Shape (batch_size, ). words...
Compute analogies for given question words. Parameters ---------- words1 : Symbol or NDArray Word indices of first question words. Shape (batch_size, ). words2 : Symbol or NDArray Word indices of second question words. Shape (batch_size, ). words3 : Symbo...
Below is the the instruction that describes the task: ### Input: Compute analogies for given question words. Parameters ---------- words1 : Symbol or NDArray Word indices of first question words. Shape (batch_size, ). words2 : Symbol or NDArray Word indices o...
def process_once(self, timeout=0.01): """ Handles an event and calls it's handler Optional arguments: * timeout=0.01 - Wait for an event until the timeout is reached. """ try: event = self.recv(timeout) if event: event_t = event[0] ...
Handles an event and calls it's handler Optional arguments: * timeout=0.01 - Wait for an event until the timeout is reached.
Below is the the instruction that describes the task: ### Input: Handles an event and calls it's handler Optional arguments: * timeout=0.01 - Wait for an event until the timeout is reached. ### Response: def process_once(self, timeout=0.01): """ Handles an event and calls it's handl...
def _start_actions(self): """ Start all the actions for the recipes """ Global.LOGGER.info("starting actions") for recipe in Global.CONFIG_MANAGER.recipes: Global.CONFIG_MANAGER.read_recipe(recipe) list(map(lambda section: self._start_action_for_section( ...
Start all the actions for the recipes
Below is the the instruction that describes the task: ### Input: Start all the actions for the recipes ### Response: def _start_actions(self): """ Start all the actions for the recipes """ Global.LOGGER.info("starting actions") for recipe in Global.CONFIG_MANAGER.recipes: ...
def from_graphtool(cls, graph, weight='weight'): r"""Import a graph from graph-tool. Edge weights are retrieved as an edge property, under the name specified by the ``weight`` parameter. Signals are retrieved from node properties, and stored in the :attr:`signals` dictionary un...
r"""Import a graph from graph-tool. Edge weights are retrieved as an edge property, under the name specified by the ``weight`` parameter. Signals are retrieved from node properties, and stored in the :attr:`signals` dictionary under the property name. `N`-dimensional signals th...
Below is the the instruction that describes the task: ### Input: r"""Import a graph from graph-tool. Edge weights are retrieved as an edge property, under the name specified by the ``weight`` parameter. Signals are retrieved from node properties, and stored in the :attr:`signals` d...
def root(self, value): """Set new XML tree""" self._xml = t2s(value) self._root = value
Set new XML tree
Below is the the instruction that describes the task: ### Input: Set new XML tree ### Response: def root(self, value): """Set new XML tree""" self._xml = t2s(value) self._root = value
def update_metadata(self, key, value): """Set *key* in the metadata to *value*. Returns the previous value of *key*, or None if the key was not previously set. """ old_value = self.contents['metadata'].get(key) self.contents['metadata'][key] = value self._log('Up...
Set *key* in the metadata to *value*. Returns the previous value of *key*, or None if the key was not previously set.
Below is the the instruction that describes the task: ### Input: Set *key* in the metadata to *value*. Returns the previous value of *key*, or None if the key was not previously set. ### Response: def update_metadata(self, key, value): """Set *key* in the metadata to *value*. Retu...
def hash(filepath, method='sha1', buffer_size=65536): """ Calculate a hash of a local file. Parameters ---------- filepath : str method : {'sha1', 'md5'} buffer_size : int, optional (default: 65536 byte = 64 KiB) in byte Returns ------- hash : str """ if method ...
Calculate a hash of a local file. Parameters ---------- filepath : str method : {'sha1', 'md5'} buffer_size : int, optional (default: 65536 byte = 64 KiB) in byte Returns ------- hash : str
Below is the the instruction that describes the task: ### Input: Calculate a hash of a local file. Parameters ---------- filepath : str method : {'sha1', 'md5'} buffer_size : int, optional (default: 65536 byte = 64 KiB) in byte Returns ------- hash : str ### Response: def ...
def get_stats_snmp(self, bulk=False, snmp_oid=None): """Update stats using SNMP. If bulk=True, use a bulk request instead of a get request. """ snmp_oid = snmp_oid or {} from glances.snmp import GlancesSNMPClient # Init the SNMP request clientsnmp = GlancesSNMP...
Update stats using SNMP. If bulk=True, use a bulk request instead of a get request.
Below is the the instruction that describes the task: ### Input: Update stats using SNMP. If bulk=True, use a bulk request instead of a get request. ### Response: def get_stats_snmp(self, bulk=False, snmp_oid=None): """Update stats using SNMP. If bulk=True, use a bulk request instead of a...
def _get_default_language(self): """ If a default language has been set, and is still available in `self.available_languages`, return it and remove it from the list. If not, simply pop the first available language. """ assert hasattr(self, 'available_languages'), \ ...
If a default language has been set, and is still available in `self.available_languages`, return it and remove it from the list. If not, simply pop the first available language.
Below is the the instruction that describes the task: ### Input: If a default language has been set, and is still available in `self.available_languages`, return it and remove it from the list. If not, simply pop the first available language. ### Response: def _get_default_language(self): ...
def default_field_resolver(source, info, **args): """Default field resolver. If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns the result of...
Default field resolver. If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function while passing along args and c...
Below is the the instruction that describes the task: ### Input: Default field resolver. If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns t...
def pop_all(self): """ Preserve the context stack by transferring it to a new instance """ ret = ExitStack() ret._context_stack.append(self._context_stack.pop()) self._context_stack.append([])
Preserve the context stack by transferring it to a new instance
Below is the the instruction that describes the task: ### Input: Preserve the context stack by transferring it to a new instance ### Response: def pop_all(self): """ Preserve the context stack by transferring it to a new instance """ ret = ExitStack() ret._context_stack.append(self._context...
def _find_by(self, key): """Find devices.""" by_path = glob.glob('/dev/input/by-{key}/*-event-*'.format(key=key)) for device_path in by_path: self._parse_device_path(device_path)
Find devices.
Below is the the instruction that describes the task: ### Input: Find devices. ### Response: def _find_by(self, key): """Find devices.""" by_path = glob.glob('/dev/input/by-{key}/*-event-*'.format(key=key)) for device_path in by_path: self._parse_device_path(device_path)
def _export_with_html(self): # pragma: no cover "Computes substitutions before using nbconvert with preprocessors" self.export_success = False try: tstamp = time.strftime(self.timestamp_format, self._timestamp) substitutions = {} for (basena...
Computes substitutions before using nbconvert with preprocessors
Below is the the instruction that describes the task: ### Input: Computes substitutions before using nbconvert with preprocessors ### Response: def _export_with_html(self): # pragma: no cover "Computes substitutions before using nbconvert with preprocessors" self.export_success =...
def ls_(active=None, cache=True, path=None): ''' Return a list of the containers available on the minion path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 active If ``True``, return only active (i.e. running) containe...
Return a list of the containers available on the minion path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 active If ``True``, return only active (i.e. running) containers .. versionadded:: 2015.5.0 CLI Example: ...
Below is the the instruction that describes the task: ### Input: Return a list of the containers available on the minion path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 active If ``True``, return only active (i.e. runni...
def _interop_prop_to_py_ast( ctx: GeneratorContext, node: HostField, is_assigning: bool = False ) -> GeneratedPyAST: """Generate a Python AST node for Python interop property access.""" assert node.op == NodeOp.HOST_FIELD target_ast = gen_py_ast(ctx, node.target) return GeneratedPyAST( nod...
Generate a Python AST node for Python interop property access.
Below is the the instruction that describes the task: ### Input: Generate a Python AST node for Python interop property access. ### Response: def _interop_prop_to_py_ast( ctx: GeneratorContext, node: HostField, is_assigning: bool = False ) -> GeneratedPyAST: """Generate a Python AST node for Python interop...
def lxml(self) -> HtmlElement: """`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`. """ if self._lxml is None: try: self._lxml = soup_parse(self.html, features='html.parser') except ValueError: ...
`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`.
Below is the the instruction that describes the task: ### Input: `lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`HTML <HTML>`. ### Response: def lxml(self) -> HtmlElement: """`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :c...
def assoc(self, key, value): '''Returns a new ImmutableDict instance with value associated with key. The implicit parameter is not modified.''' copydict = ImmutableDict() copydict.tree = self.tree.assoc(hash(key), (key, value)) copydict._length = self._length + 1 return c...
Returns a new ImmutableDict instance with value associated with key. The implicit parameter is not modified.
Below is the the instruction that describes the task: ### Input: Returns a new ImmutableDict instance with value associated with key. The implicit parameter is not modified. ### Response: def assoc(self, key, value): '''Returns a new ImmutableDict instance with value associated with key. Th...
def generateFromNumbers(self, numbers): """ Generate a sequence from a list of numbers. Note: Any `None` in the list of numbers is considered a reset. @param numbers (list) List of numbers @return (list) Generated sequence """ sequence = [] for number in numbers: if number == N...
Generate a sequence from a list of numbers. Note: Any `None` in the list of numbers is considered a reset. @param numbers (list) List of numbers @return (list) Generated sequence
Below is the the instruction that describes the task: ### Input: Generate a sequence from a list of numbers. Note: Any `None` in the list of numbers is considered a reset. @param numbers (list) List of numbers @return (list) Generated sequence ### Response: def generateFromNumbers(self, numbers): ...
def format_throughput(available, used=None): """ Format the read/write throughput for display """ if used is None: return str(available) percent = float(used) / available return "{0:.0f}/{1:.0f} ({2:.0%})".format(used, available, percent)
Format the read/write throughput for display
Below is the the instruction that describes the task: ### Input: Format the read/write throughput for display ### Response: def format_throughput(available, used=None): """ Format the read/write throughput for display """ if used is None: return str(available) percent = float(used) / available ...
def _build_unicode_character_database(self): """ Function for parsing the Unicode character data from the Unicode Character Database (UCD) and generating a lookup table. For more info on the UCD, see the following website: https://www.unicode.org/ucd/ """ filename = "Uni...
Function for parsing the Unicode character data from the Unicode Character Database (UCD) and generating a lookup table. For more info on the UCD, see the following website: https://www.unicode.org/ucd/
Below is the the instruction that describes the task: ### Input: Function for parsing the Unicode character data from the Unicode Character Database (UCD) and generating a lookup table. For more info on the UCD, see the following website: https://www.unicode.org/ucd/ ### Response: def _build_unico...
def create_partition(analysis_request, request, analyses, sample_type=None, container=None, preservation=None, skip_fields=None, remove_primary_analyses=True): """ Creates a partition for the analysis_request (primary) passed in :param analysis_request: uid/brain/ob...
Creates a partition for the analysis_request (primary) passed in :param analysis_request: uid/brain/object of IAnalysisRequest type :param request: the current request object :param analyses: uids/brains/objects of IAnalysis type :param sampletype: uid/brain/object of SampleType :param container: ui...
Below is the the instruction that describes the task: ### Input: Creates a partition for the analysis_request (primary) passed in :param analysis_request: uid/brain/object of IAnalysisRequest type :param request: the current request object :param analyses: uids/brains/objects of IAnalysis type :para...
def _connect(self): ''' Connect to F5 ''' try: self.bigIP = f5.BIGIP(hostname=self.lb, username=self.username, password=self.password, fromurl=True, ...
Connect to F5
Below is the the instruction that describes the task: ### Input: Connect to F5 ### Response: def _connect(self): ''' Connect to F5 ''' try: self.bigIP = f5.BIGIP(hostname=self.lb, username=self.username, ...
def __multi_arity_fn_to_py_ast( # pylint: disable=too-many-locals ctx: GeneratorContext, node: Fn, methods: Collection[FnMethod], def_name: Optional[str] = None, meta_node: Optional[MetaNode] = None, ) -> GeneratedPyAST: """Return a Python AST node for a function with multiple arities.""" a...
Return a Python AST node for a function with multiple arities.
Below is the the instruction that describes the task: ### Input: Return a Python AST node for a function with multiple arities. ### Response: def __multi_arity_fn_to_py_ast( # pylint: disable=too-many-locals ctx: GeneratorContext, node: Fn, methods: Collection[FnMethod], def_name: Optional[str] = ...
def line_to_args(self, line): """This will convert the line passed into the do_xxx functions into an array of arguments and handle the Output Redirection Operator. """ # Note: using shlex.split causes quoted substrings to stay together. args = shlex.split(line) self.redir...
This will convert the line passed into the do_xxx functions into an array of arguments and handle the Output Redirection Operator.
Below is the the instruction that describes the task: ### Input: This will convert the line passed into the do_xxx functions into an array of arguments and handle the Output Redirection Operator. ### Response: def line_to_args(self, line): """This will convert the line passed into the do_xxx functi...
def step(self): """Do a single iteration over all cbpdn and ccmod steps. Those that are not coupled on the K axis are performed in parallel.""" # If the nproc parameter of __init__ is zero, just iterate # over the K consensus instances instead of using # multiprocessing to do th...
Do a single iteration over all cbpdn and ccmod steps. Those that are not coupled on the K axis are performed in parallel.
Below is the the instruction that describes the task: ### Input: Do a single iteration over all cbpdn and ccmod steps. Those that are not coupled on the K axis are performed in parallel. ### Response: def step(self): """Do a single iteration over all cbpdn and ccmod steps. Those that are no...
def _check_package(pkg_xml, zipfilename, zf): """ Helper for ``build_index()``: Perform some checks to make sure that the given package is consistent. """ # The filename must patch the id given in the XML file. uid = os.path.splitext(os.path.split(zipfilename)[1])[0] if pkg_xml.get('id') != uid: raise...
Helper for ``build_index()``: Perform some checks to make sure that the given package is consistent.
Below is the the instruction that describes the task: ### Input: Helper for ``build_index()``: Perform some checks to make sure that the given package is consistent. ### Response: def _check_package(pkg_xml, zipfilename, zf): """ Helper for ``build_index()``: Perform some checks to make sure that the given...
def run(self): """ Consume message from the Advanced Message Queuing Protocol (AMPQ) compliant broker as soon as they are queued, and call the instance method ``__on_message_received`` that the inheriting class must have implemented. """ self._setUp() nam...
Consume message from the Advanced Message Queuing Protocol (AMPQ) compliant broker as soon as they are queued, and call the instance method ``__on_message_received`` that the inheriting class must have implemented.
Below is the the instruction that describes the task: ### Input: Consume message from the Advanced Message Queuing Protocol (AMPQ) compliant broker as soon as they are queued, and call the instance method ``__on_message_received`` that the inheriting class must have implemented. ### Response...
def make_aliased_type(cls, other_base): """ Factory for making Aliased{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that names another {t}. Parameters ---------- term : {t} {{name}} """ ...
Factory for making Aliased{Filter,Factor,Classifier}.
Below is the the instruction that describes the task: ### Input: Factory for making Aliased{Filter,Factor,Classifier}. ### Response: def make_aliased_type(cls, other_base): """ Factory for making Aliased{Filter,Factor,Classifier}. """ docstring = dedent( """ ...
def _h2ab_s(s): """Define the saturated line boundary between Region 4 and 2a-2b, h=f(s) Parameters ---------- s : float Specific entropy, [kJ/kgK] Returns ------- h : float Specific enthalpy, [kJ/kg] Notes ------ Raise :class:`NotImplementedError` if input isn...
Define the saturated line boundary between Region 4 and 2a-2b, h=f(s) Parameters ---------- s : float Specific entropy, [kJ/kgK] Returns ------- h : float Specific enthalpy, [kJ/kg] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: *...
Below is the the instruction that describes the task: ### Input: Define the saturated line boundary between Region 4 and 2a-2b, h=f(s) Parameters ---------- s : float Specific entropy, [kJ/kgK] Returns ------- h : float Specific enthalpy, [kJ/kg] Notes ------ R...
def mean(self, start=None, end=None, mask=None): """This calculated the average value of the time series over the given time range from `start` to `end`, when `mask` is truthy. """ return self.distribution(start=start, end=end, mask=mask).mean()
This calculated the average value of the time series over the given time range from `start` to `end`, when `mask` is truthy.
Below is the the instruction that describes the task: ### Input: This calculated the average value of the time series over the given time range from `start` to `end`, when `mask` is truthy. ### Response: def mean(self, start=None, end=None, mask=None): """This calculated the average value of the ti...
def task_dropped(self): """ Track (if required) drop event and do the same job as :meth:`.WScheduleRecord.task_dropped` method do :return: None """ tracker = self.task().tracker_storage() if tracker is not None and self.track_drop() is True: details = self.task().event_details(WTrackerEvents.drop) tr...
Track (if required) drop event and do the same job as :meth:`.WScheduleRecord.task_dropped` method do :return: None
Below is the the instruction that describes the task: ### Input: Track (if required) drop event and do the same job as :meth:`.WScheduleRecord.task_dropped` method do :return: None ### Response: def task_dropped(self): """ Track (if required) drop event and do the same job as :meth:`.WScheduleRecord.task_dr...
def deepcopy(self): """ Create a deep copy of the segmentation map object. Returns ------- imgaug.SegmentationMapOnImage Deep copy. """ segmap = SegmentationMapOnImage(self.arr, shape=self.shape, nb_classes=self.nb_classes) segmap.input_was =...
Create a deep copy of the segmentation map object. Returns ------- imgaug.SegmentationMapOnImage Deep copy.
Below is the the instruction that describes the task: ### Input: Create a deep copy of the segmentation map object. Returns ------- imgaug.SegmentationMapOnImage Deep copy. ### Response: def deepcopy(self): """ Create a deep copy of the segmentation map object. ...
def parse_bookmark_json (data): """Parse complete JSON data for Chromium Bookmarks.""" for entry in data["roots"].values(): for url, name in parse_bookmark_node(entry): yield url, name
Parse complete JSON data for Chromium Bookmarks.
Below is the the instruction that describes the task: ### Input: Parse complete JSON data for Chromium Bookmarks. ### Response: def parse_bookmark_json (data): """Parse complete JSON data for Chromium Bookmarks.""" for entry in data["roots"].values(): for url, name in parse_bookmark_node(entry): ...
def resolve_sound(self, sound): """Function tries to identify a sound in the data. Notes ----- The function tries to resolve sounds to take a sound with less complex features in order to yield the next approximate sound class, if the transcription data are sound classes....
Function tries to identify a sound in the data. Notes ----- The function tries to resolve sounds to take a sound with less complex features in order to yield the next approximate sound class, if the transcription data are sound classes.
Below is the the instruction that describes the task: ### Input: Function tries to identify a sound in the data. Notes ----- The function tries to resolve sounds to take a sound with less complex features in order to yield the next approximate sound class, if the transcripti...
def get_DIR(self, WD=None): """ open dialog box for choosing a working directory """ if "-WD" in sys.argv and FIRST_RUN: ind = sys.argv.index('-WD') self.WD = sys.argv[ind + 1] elif not WD: # if no arg was passed in for WD, make a dialog to choose one ...
open dialog box for choosing a working directory
Below is the the instruction that describes the task: ### Input: open dialog box for choosing a working directory ### Response: def get_DIR(self, WD=None): """ open dialog box for choosing a working directory """ if "-WD" in sys.argv and FIRST_RUN: ind = sys.argv.index(...
def populate_translation_fields(sender, kwargs): """ When models are created or loaded from fixtures, replicates values provided for translatable fields to some / all empty translation fields, according to the current population mode. Population is performed only on keys (field names) present in kw...
When models are created or loaded from fixtures, replicates values provided for translatable fields to some / all empty translation fields, according to the current population mode. Population is performed only on keys (field names) present in kwargs. Nothing is returned, but passed kwargs dictionary i...
Below is the the instruction that describes the task: ### Input: When models are created or loaded from fixtures, replicates values provided for translatable fields to some / all empty translation fields, according to the current population mode. Population is performed only on keys (field names) prese...
def create_stream(self, seek=None, writeable=False, update_buffer=True): """Prepares the session for streaming of audio/video and returns a :class:`RTMPStream` object. :param seek: int, Attempt to seek to this position. :param writeable: bool, Make the stream writeable instead of rea...
Prepares the session for streaming of audio/video and returns a :class:`RTMPStream` object. :param seek: int, Attempt to seek to this position. :param writeable: bool, Make the stream writeable instead of readable. :param update_buffer: bool, When enabled will attempt to speed up ...
Below is the the instruction that describes the task: ### Input: Prepares the session for streaming of audio/video and returns a :class:`RTMPStream` object. :param seek: int, Attempt to seek to this position. :param writeable: bool, Make the stream writeable instead of readable. ...
def _ends_with(self, string_to_edit, end): # pylint: disable=no-self-use """ Check if string ends with characters in end, if not merge end to string. :param string_to_edit: string to check and edit. :param end: str :return: string_to_edit or string_to_edit + end """ ...
Check if string ends with characters in end, if not merge end to string. :param string_to_edit: string to check and edit. :param end: str :return: string_to_edit or string_to_edit + end
Below is the the instruction that describes the task: ### Input: Check if string ends with characters in end, if not merge end to string. :param string_to_edit: string to check and edit. :param end: str :return: string_to_edit or string_to_edit + end ### Response: def _ends_with(self, stri...
def roll_dice(self): # Roll dice with current roll """ Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results. """ roll = roll_dice(self.roll, floats=self.floats, functions=self.functions) self._last_roll = roll[0] self._las...
Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results.
Below is the the instruction that describes the task: ### Input: Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results. ### Response: def roll_dice(self): # Roll dice with current roll """ Rolls dicebag and sets last_roll and last_explanation to roll ...
def check_perms(self, perms='0600,0400'): """Check and enforce the permissions of the config file. Enforce permission on a provided configuration file. This will check and see if the permission are set based on the permission octet as set in the ``perms`` value. ``perms`` is a comma sep...
Check and enforce the permissions of the config file. Enforce permission on a provided configuration file. This will check and see if the permission are set based on the permission octet as set in the ``perms`` value. ``perms`` is a comma separated list of acceptable perms in octal form...
Below is the the instruction that describes the task: ### Input: Check and enforce the permissions of the config file. Enforce permission on a provided configuration file. This will check and see if the permission are set based on the permission octet as set in the ``perms`` value. ``perms`...
def installed(name, default=False, user=None): ''' Verify that the specified python is installed with pyenv. pyenv is installed if necessary. name The version of python to install default : False Whether to make this python the default. user: None The user to run pyenv...
Verify that the specified python is installed with pyenv. pyenv is installed if necessary. name The version of python to install default : False Whether to make this python the default. user: None The user to run pyenv as. .. versionadded:: 0.17.0 .. versionadded...
Below is the the instruction that describes the task: ### Input: Verify that the specified python is installed with pyenv. pyenv is installed if necessary. name The version of python to install default : False Whether to make this python the default. user: None The user to...
def get_scorer(scoring, compute=True): """Get a scorer from string Parameters ---------- scoring : str | callable scoring method as string. If callable it is returned as is. Returns ------- scorer : callable The scorer. """ # This is the same as sklearns, only we us...
Get a scorer from string Parameters ---------- scoring : str | callable scoring method as string. If callable it is returned as is. Returns ------- scorer : callable The scorer.
Below is the the instruction that describes the task: ### Input: Get a scorer from string Parameters ---------- scoring : str | callable scoring method as string. If callable it is returned as is. Returns ------- scorer : callable The scorer. ### Response: def get_scorer(s...
def openable(cls): """ A class decorator to fill in certain methods and properties to ensure a class can be used by :func:`.create_open`. These instance methods and property will be added, if not defined by the class: - ``open(self, initial_msg, seed)`` - ``on_message(self, msg)`` - ``...
A class decorator to fill in certain methods and properties to ensure a class can be used by :func:`.create_open`. These instance methods and property will be added, if not defined by the class: - ``open(self, initial_msg, seed)`` - ``on_message(self, msg)`` - ``on_close(self, ex)`` - ``cl...
Below is the the instruction that describes the task: ### Input: A class decorator to fill in certain methods and properties to ensure a class can be used by :func:`.create_open`. These instance methods and property will be added, if not defined by the class: - ``open(self, initial_msg, seed)`` ...
def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (ha...
Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( ...
Below is the the instruction that describes the task: ### Input: Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). ...
def automatic_slug_renaming(slug, is_slug_safe): """Helper to add numbers to slugs""" if not isinstance(is_slug_safe, collections.Callable): raise TypeError('is_slug_safe must be callable') if is_slug_safe(slug): return slug count = 2 new_slug = slug + "-" + str(count) while no...
Helper to add numbers to slugs
Below is the the instruction that describes the task: ### Input: Helper to add numbers to slugs ### Response: def automatic_slug_renaming(slug, is_slug_safe): """Helper to add numbers to slugs""" if not isinstance(is_slug_safe, collections.Callable): raise TypeError('is_slug_safe must be callable'...
def _to_utc(self, dt): """Takes a naive timezone with an localized value and return it formatted as utc.""" tz = self._get_tz() loc_dt = tz.localize(dt) return loc_dt.astimezone(pytz.utc)
Takes a naive timezone with an localized value and return it formatted as utc.
Below is the the instruction that describes the task: ### Input: Takes a naive timezone with an localized value and return it formatted as utc. ### Response: def _to_utc(self, dt): """Takes a naive timezone with an localized value and return it formatted as utc.""" tz = self._get_tz...
def setpathcost(self, port, cost): """ Set port path cost value for STP protocol. """ _runshell([brctlexe, 'setpathcost', self.name, port, str(cost)], "Could not set path cost in port %s in %s." % (port, self.name))
Set port path cost value for STP protocol.
Below is the the instruction that describes the task: ### Input: Set port path cost value for STP protocol. ### Response: def setpathcost(self, port, cost): """ Set port path cost value for STP protocol. """ _runshell([brctlexe, 'setpathcost', self.name, port, str(cost)], "Could not set...
def format_table(table, column_names=None, column_specs=None, max_col_width=32, report_dimensions=False): ''' Table pretty printer. Expects tables to be given as arrays of arrays. Example: print format_table([[1, "2"], [3, "456"]], column_names=['A', 'B']) ''' if len(tabl...
Table pretty printer. Expects tables to be given as arrays of arrays. Example: print format_table([[1, "2"], [3, "456"]], column_names=['A', 'B'])
Below is the the instruction that describes the task: ### Input: Table pretty printer. Expects tables to be given as arrays of arrays. Example: print format_table([[1, "2"], [3, "456"]], column_names=['A', 'B']) ### Response: def format_table(table, column_names=None, column_specs=None, max_col_w...
def __get_canonical_separate(self, input_separate): """! @brief Return unified representation of separation value. @details It represents list whose size is equal to amount of dynamics, where index of dynamic will show where it should be displayed. @param[in] inp...
! @brief Return unified representation of separation value. @details It represents list whose size is equal to amount of dynamics, where index of dynamic will show where it should be displayed. @param[in] input_separate (bool|list): Input separate representation that shou...
Below is the the instruction that describes the task: ### Input: ! @brief Return unified representation of separation value. @details It represents list whose size is equal to amount of dynamics, where index of dynamic will show where it should be displayed. @param[in...
def snmp_server_group_notify(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") group = ET.SubElement(snmp_server, "group") group_name_key = ET.SubElement(...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def snmp_server_group_notify(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:br...
def case(text, casingformat='sentence'): """ Change the casing of some text. :type text: string :param text: The text to change the casing of. :type casingformat: string :param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' or 'caterpillar'...
Change the casing of some text. :type text: string :param text: The text to change the casing of. :type casingformat: string :param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' or 'caterpillar'. :raises ValueError: Invalid text format specif...
Below is the the instruction that describes the task: ### Input: Change the casing of some text. :type text: string :param text: The text to change the casing of. :type casingformat: string :param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' ...
def find_duplicate_schedule_items(all_items): """Find talks / pages assigned to mulitple schedule items""" duplicates = [] seen_talks = {} for item in all_items: if item.talk and item.talk in seen_talks: duplicates.append(item) if seen_talks[item.talk] not in duplicates: ...
Find talks / pages assigned to mulitple schedule items
Below is the the instruction that describes the task: ### Input: Find talks / pages assigned to mulitple schedule items ### Response: def find_duplicate_schedule_items(all_items): """Find talks / pages assigned to mulitple schedule items""" duplicates = [] seen_talks = {} for item in all_items: ...
def calc_phase_space(self, freq, ConvFactor, PeakWidth=10000, FractionOfSampleFreq=1, timeStart=None, timeEnd =None, PointsOfPadding=500, ShowPSD=False): """ Calculates the position and velocity (in m) for use in plotting the phase space distribution. Parameters ---------- freq ...
Calculates the position and velocity (in m) for use in plotting the phase space distribution. Parameters ---------- freq : float The frequenecy of the peak (Trapping frequency of the dimension of interest) ConvFactor : float (or ufloat) The conversion factor betw...
Below is the the instruction that describes the task: ### Input: Calculates the position and velocity (in m) for use in plotting the phase space distribution. Parameters ---------- freq : float The frequenecy of the peak (Trapping frequency of the dimension of interest) ...
def prepare_search_body(self, should_terms=None, must_terms=None, must_not_terms=None, search_text='', start=None, end=None): """ Prepare body for elasticsearch query Search parameters ^^^^^^^^^^^^^^^^^ These parameters are dictionaries and have format: <term>: [<value 1>, <val...
Prepare body for elasticsearch query Search parameters ^^^^^^^^^^^^^^^^^ These parameters are dictionaries and have format: <term>: [<value 1>, <value 2> ...] should_terms: it resembles logical OR must_terms: it resembles logical AND must_not_terms: it resembles logical...
Below is the the instruction that describes the task: ### Input: Prepare body for elasticsearch query Search parameters ^^^^^^^^^^^^^^^^^ These parameters are dictionaries and have format: <term>: [<value 1>, <value 2> ...] should_terms: it resembles logical OR must_terms: ...
def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False): """ Wrap `query_disc` to use lon, lat, and radius in degrees. """ vec = ang2vec(lon,lat) return query_disc(nside,vec,radius,inclusive,fact,nest)
Wrap `query_disc` to use lon, lat, and radius in degrees.
Below is the the instruction that describes the task: ### Input: Wrap `query_disc` to use lon, lat, and radius in degrees. ### Response: def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False): """ Wrap `query_disc` to use lon, lat, and radius in degrees. """ vec = ang2vec(lon,la...
def set_value(self, key, field, value): """Add the state of the key and field""" self._db.hset(key, field, value)
Add the state of the key and field
Below is the the instruction that describes the task: ### Input: Add the state of the key and field ### Response: def set_value(self, key, field, value): """Add the state of the key and field""" self._db.hset(key, field, value)
def _load_version2(self,filename): """load a version 2 control file """ self.lcount = 0 self.comments = {} self.prior_information = self.null_prior assert os.path.exists(filename), "couldn't find control file {0}".format(filename) f = open(filename, 'r') ...
load a version 2 control file
Below is the the instruction that describes the task: ### Input: load a version 2 control file ### Response: def _load_version2(self,filename): """load a version 2 control file """ self.lcount = 0 self.comments = {} self.prior_information = self.null_prior assert...
def possible_completions(self, e): # (M-?) u"""List the possible completions of the text before point. """ completions = self._get_completions() self._display_completions(completions) self.finalize()
u"""List the possible completions of the text before point.
Below is the the instruction that describes the task: ### Input: u"""List the possible completions of the text before point. ### Response: def possible_completions(self, e): # (M-?) u"""List the possible completions of the text before point. """ completions = self._get_completions() self...
def hook_param(self, hook, p): """Parse a hook parameter""" hook.listparam.append(p.pair) return True
Parse a hook parameter
Below is the the instruction that describes the task: ### Input: Parse a hook parameter ### Response: def hook_param(self, hook, p): """Parse a hook parameter""" hook.listparam.append(p.pair) return True
async def prover_create_credential_req(wallet_handle: int, prover_did: str, cred_offer_json: str, cred_def_json: str, master_secret_id: str) -> (str, str): """ ...
Creates a clam request for the given credential offer. The method creates a blinded master secret for a master secret identified by a provided name. The master secret identified by the name must be already stored in the secure wallet (see prover_create_master_secret) The blinded master secret is a part of ...
Below is the the instruction that describes the task: ### Input: Creates a clam request for the given credential offer. The method creates a blinded master secret for a master secret identified by a provided name. The master secret identified by the name must be already stored in the secure wallet (see pro...
def threshold(self, scalars, vmin=None, vmax=None, useCells=False): """ Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: ...
Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of the scalar :param bool useCells: if `True`, assume array scalar...
Below is the the instruction that describes the task: ### Input: Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of th...
def dump_code(disassembly, pc = None, bLowercase = True, bits = None): """ Dump a disassembly. Optionally mark where the program counter is. ...
Dump a disassembly. Optionally mark where the program counter is. @type disassembly: list of tuple( int, int, str, str ) @param disassembly: Disassembly dump as returned by L{Process.disassemble} or L{Thread.disassemble_around_pc}. @type pc: int @param pc: (Optional) Prog...
Below is the the instruction that describes the task: ### Input: Dump a disassembly. Optionally mark where the program counter is. @type disassembly: list of tuple( int, int, str, str ) @param disassembly: Disassembly dump as returned by L{Process.disassemble} or L{Thread.disassemble_a...
def branchlist2branches(data, commdct, branchlist): """get branches from the branchlist""" objkey = 'BranchList'.upper() theobjects = data.dt[objkey] fieldlists = [] objnames = [obj[1] for obj in theobjects] for theobject in theobjects: fieldlists.append(list(range(2, len(theobject)))) ...
get branches from the branchlist
Below is the the instruction that describes the task: ### Input: get branches from the branchlist ### Response: def branchlist2branches(data, commdct, branchlist): """get branches from the branchlist""" objkey = 'BranchList'.upper() theobjects = data.dt[objkey] fieldlists = [] objnames = [obj[1...