code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=None, subresource_path=''): """Helps to build a URI with resource path and its sub resource path. Args: resoure_id_or_uri: ID/URI of the main resource. subresource_id__or_uri: ID/URI of the sub resour...
Helps to build a URI with resource path and its sub resource path. Args: resoure_id_or_uri: ID/URI of the main resource. subresource_id__or_uri: ID/URI of the sub resource. subresource_path: Sub resource path to be added with the URI. Returns: Returns UR...
Below is the the instruction that describes the task: ### Input: Helps to build a URI with resource path and its sub resource path. Args: resoure_id_or_uri: ID/URI of the main resource. subresource_id__or_uri: ID/URI of the sub resource. subresource_path: Sub resource pa...
def _pick_colours(self, palette_name, selected=False): """ Pick the rendering colour for a widget based on the current state. :param palette_name: The stem name for the widget - e.g. "button". :param selected: Whether this item is selected or not. :returns: A colour tuple (fg, a...
Pick the rendering colour for a widget based on the current state. :param palette_name: The stem name for the widget - e.g. "button". :param selected: Whether this item is selected or not. :returns: A colour tuple (fg, attr, bg) to be used.
Below is the the instruction that describes the task: ### Input: Pick the rendering colour for a widget based on the current state. :param palette_name: The stem name for the widget - e.g. "button". :param selected: Whether this item is selected or not. :returns: A colour tuple (fg, attr, b...
def html(text, extensions=0, render_flags=0): """ Convert markdown text to HTML. ``extensions`` can be a list or tuple of extensions (e.g. ``('fenced-code', 'footnotes', 'strikethrough')``) or an integer (e.g. ``EXT_FENCED_CODE | EXT_FOOTNOTES | EXT_STRIKETHROUGH``). ``render_flags`` can be a ...
Convert markdown text to HTML. ``extensions`` can be a list or tuple of extensions (e.g. ``('fenced-code', 'footnotes', 'strikethrough')``) or an integer (e.g. ``EXT_FENCED_CODE | EXT_FOOTNOTES | EXT_STRIKETHROUGH``). ``render_flags`` can be a list or tuple of flags (e.g. ``('skip-html', 'hard-wra...
Below is the the instruction that describes the task: ### Input: Convert markdown text to HTML. ``extensions`` can be a list or tuple of extensions (e.g. ``('fenced-code', 'footnotes', 'strikethrough')``) or an integer (e.g. ``EXT_FENCED_CODE | EXT_FOOTNOTES | EXT_STRIKETHROUGH``). ``render_flags`...
def add_occurrences(events, count): """ Adds an occurrence key to the event object w/ a list of occurrences and adds a popover (for use with twitter bootstrap). The occurrence is added so that each event can be aware of what day(s) it occurs in the month. """ for day in count: for it...
Adds an occurrence key to the event object w/ a list of occurrences and adds a popover (for use with twitter bootstrap). The occurrence is added so that each event can be aware of what day(s) it occurs in the month.
Below is the the instruction that describes the task: ### Input: Adds an occurrence key to the event object w/ a list of occurrences and adds a popover (for use with twitter bootstrap). The occurrence is added so that each event can be aware of what day(s) it occurs in the month. ### Response: def add_...
def make_ifar_plot(workflow, trigger_file, out_dir, tags=None, hierarchical_level=None): """ Creates a node in the workflow for plotting cumulative histogram of IFAR values. """ if hierarchical_level is not None and tags: tags = [("HIERARCHICAL_LEVEL_{:02d}".format( ...
Creates a node in the workflow for plotting cumulative histogram of IFAR values.
Below is the the instruction that describes the task: ### Input: Creates a node in the workflow for plotting cumulative histogram of IFAR values. ### Response: def make_ifar_plot(workflow, trigger_file, out_dir, tags=None, hierarchical_level=None): """ Creates a node in the workflow for ...
def deref(o, timeout_s=None, timeout_val=None): """Dereference a Deref object and return its contents. If o is an object implementing IBlockingDeref and timeout_s and timeout_val are supplied, deref will wait at most timeout_s seconds, returning timeout_val if timeout_s seconds elapse and o has not ...
Dereference a Deref object and return its contents. If o is an object implementing IBlockingDeref and timeout_s and timeout_val are supplied, deref will wait at most timeout_s seconds, returning timeout_val if timeout_s seconds elapse and o has not returned.
Below is the the instruction that describes the task: ### Input: Dereference a Deref object and return its contents. If o is an object implementing IBlockingDeref and timeout_s and timeout_val are supplied, deref will wait at most timeout_s seconds, returning timeout_val if timeout_s seconds elapse and...
def container_setting(name, container, settings=None): ''' Set the value of the setting for an IIS container. :param str name: The name of the IIS container. :param str container: The type of IIS container. The container types are: AppPools, Sites, SslBindings :param str settings: A diction...
Set the value of the setting for an IIS container. :param str name: The name of the IIS container. :param str container: The type of IIS container. The container types are: AppPools, Sites, SslBindings :param str settings: A dictionary of the setting names and their values. Example of usage...
Below is the the instruction that describes the task: ### Input: Set the value of the setting for an IIS container. :param str name: The name of the IIS container. :param str container: The type of IIS container. The container types are: AppPools, Sites, SslBindings :param str settings: A dicti...
def generate_encodeable_characters(characters: Iterable[str], encodings: Iterable[str]) -> Iterable[str]: """Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encod...
Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encodings: The encodings to check against e.g. ['cp1252', 'iso-8859-5']. Returns: The subset of 'characters' that can be encoded using one o...
Below is the the instruction that describes the task: ### Input: Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encodings: The encodings to check against e.g. ['cp1252', 'iso-8859-5']. Return...
def load(name, path=None, ext="dat", silent=False): """ Loads an object from file with given name and extension. Optionally the path can be specified as well. """ filename = __get_filename(path, name, ext) if not os.path.exists(filename): if not silent: raise ValueException(...
Loads an object from file with given name and extension. Optionally the path can be specified as well.
Below is the the instruction that describes the task: ### Input: Loads an object from file with given name and extension. Optionally the path can be specified as well. ### Response: def load(name, path=None, ext="dat", silent=False): """ Loads an object from file with given name and extension. Opti...
def unconsume(self, seq): '''Subtracts all k-mers in sequence.''' for kmer in iter_kmers(seq, self.k, canonical=self.canonical): self._decr(kmer)
Subtracts all k-mers in sequence.
Below is the the instruction that describes the task: ### Input: Subtracts all k-mers in sequence. ### Response: def unconsume(self, seq): '''Subtracts all k-mers in sequence.''' for kmer in iter_kmers(seq, self.k, canonical=self.canonical): self._decr(kmer)
def StartCli(args, adb_commands, extra=None, **device_kwargs): """Starts a common CLI interface for this usb path and protocol.""" try: dev = adb_commands() dev.ConnectDevice(port_path=args.port_path, serial=args.serial, default_timeout_ms=args.timeout_ms, **device_kwar...
Starts a common CLI interface for this usb path and protocol.
Below is the the instruction that describes the task: ### Input: Starts a common CLI interface for this usb path and protocol. ### Response: def StartCli(args, adb_commands, extra=None, **device_kwargs): """Starts a common CLI interface for this usb path and protocol.""" try: dev = adb_commands() ...
def setColor(self, color): '''Sets Card's color and escape code.''' if color == 'blue': self.color = 'blue' self.colorCode = self.colors['blue'] self.colorCodeDark = self.colors['dblue'] elif color == 'red': self.color = 'red' self.colo...
Sets Card's color and escape code.
Below is the the instruction that describes the task: ### Input: Sets Card's color and escape code. ### Response: def setColor(self, color): '''Sets Card's color and escape code.''' if color == 'blue': self.color = 'blue' self.colorCode = self.colors['blue'] self...
def create_base_storage(self, logical_size, variant): """Starts creating a hard disk storage unit (fixed/dynamic, according to the variant flags) in the background. The previous storage unit created for this object, if any, must first be deleted using :py:func:`delete_storage` , otherwis...
Starts creating a hard disk storage unit (fixed/dynamic, according to the variant flags) in the background. The previous storage unit created for this object, if any, must first be deleted using :py:func:`delete_storage` , otherwise the operation will fail. Before the operation ...
Below is the the instruction that describes the task: ### Input: Starts creating a hard disk storage unit (fixed/dynamic, according to the variant flags) in the background. The previous storage unit created for this object, if any, must first be deleted using :py:func:`delete_storage` , othe...
def has_scope(context=None): ''' Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205. ''' if not booted(context): return False _sd_version = version(context) if _sd_version is None: re...
Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205.
Below is the the instruction that describes the task: ### Input: Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205. ### Response: def has_scope(context=None): ''' Scopes were introduced in systemd 205, this fu...
def docker_start(develop=True): """ Start docker container """ curr_dir = os.path.dirname(os.path.realpath(__file__)) local('docker run --rm --name pynb -d -ti -p 127.0.0.1:8889:8888 -v {}:/code -t pynb'.format(curr_dir)) if develop: # Install package in develop mode: the code in /code...
Start docker container
Below is the the instruction that describes the task: ### Input: Start docker container ### Response: def docker_start(develop=True): """ Start docker container """ curr_dir = os.path.dirname(os.path.realpath(__file__)) local('docker run --rm --name pynb -d -ti -p 127.0.0.1:8889:8888 -v {}:/co...
def choices(klass): """ Decorator to set `CHOICES` and other attributes """ _choices = [] for attr in user_attributes(klass.Meta): val = getattr(klass.Meta, attr) setattr(klass, attr, val[0]) _choices.append((val[0], val[1])) setattr(klass, 'CHOICES', tuple(_choices)) ...
Decorator to set `CHOICES` and other attributes
Below is the the instruction that describes the task: ### Input: Decorator to set `CHOICES` and other attributes ### Response: def choices(klass): """ Decorator to set `CHOICES` and other attributes """ _choices = [] for attr in user_attributes(klass.Meta): val = getattr(klass.Meta, att...
def oridam_generate_patterns(word_in,cm,ed=1,level=0,pos=0,candidates=None): """ ed = 1 by default, pos - internal variable for algorithm """ alternates = cm.get(word_in[pos],[]) if not candidates: candidates = [] assert ed <= len(word_in), 'edit distance has to be comparable to word size [ins/d...
ed = 1 by default, pos - internal variable for algorithm
Below is the the instruction that describes the task: ### Input: ed = 1 by default, pos - internal variable for algorithm ### Response: def oridam_generate_patterns(word_in,cm,ed=1,level=0,pos=0,candidates=None): """ ed = 1 by default, pos - internal variable for algorithm """ alternates = cm.get(word_in[p...
def receive_loop_with_callback(self, queue_name, callback): """ Process incoming messages with callback until close is called. :param queue_name: str: name of the queue to poll :param callback: func(ch, method, properties, body) called with data when data arrives :return: ...
Process incoming messages with callback until close is called. :param queue_name: str: name of the queue to poll :param callback: func(ch, method, properties, body) called with data when data arrives :return:
Below is the the instruction that describes the task: ### Input: Process incoming messages with callback until close is called. :param queue_name: str: name of the queue to poll :param callback: func(ch, method, properties, body) called with data when data arrives :return: ### Response: def...
def _get_all_resource_attributes(network_id, template_id=None): """ Get all the attributes for the nodes, links and groups of a network. Return these attributes as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link. """ base_qry = db.DBSession.query( ...
Get all the attributes for the nodes, links and groups of a network. Return these attributes as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link.
Below is the the instruction that describes the task: ### Input: Get all the attributes for the nodes, links and groups of a network. Return these attributes as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link. ### Response: def _get_all_resource_attributes(network_id,...
def rerun(client, revision, roots, siblings, inputs, paths): """Recreate files generated by a sequence of ``run`` commands.""" graph = Graph(client) outputs = graph.build(paths=paths, revision=revision) # Check or extend siblings of outputs. outputs = siblings(graph, outputs) output_paths = {no...
Recreate files generated by a sequence of ``run`` commands.
Below is the the instruction that describes the task: ### Input: Recreate files generated by a sequence of ``run`` commands. ### Response: def rerun(client, revision, roots, siblings, inputs, paths): """Recreate files generated by a sequence of ``run`` commands.""" graph = Graph(client) outputs = graph...
def get_track_by_mbid(self, mbid): """Looks up a track by its MusicBrainz ID""" params = {"mbid": mbid} doc = _Request(self, "track.getInfo", params).execute(True) return Track(_extract(doc, "name", 1), _extract(doc, "name"), self)
Looks up a track by its MusicBrainz ID
Below is the the instruction that describes the task: ### Input: Looks up a track by its MusicBrainz ID ### Response: def get_track_by_mbid(self, mbid): """Looks up a track by its MusicBrainz ID""" params = {"mbid": mbid} doc = _Request(self, "track.getInfo", params).execute(True) ...
def ds2json(ds, u_var, v_var, lat_dim='latitude', lon_dim='longitude', units=None): """ Assumes that the velocity components are given on a regular grid (fixed spacing in latitude and longitude). Parameters ---------- u_var : str Name of the U-component (zonal) variable. v_var : str...
Assumes that the velocity components are given on a regular grid (fixed spacing in latitude and longitude). Parameters ---------- u_var : str Name of the U-component (zonal) variable. v_var : str Name of the V-component (meridional) variable. lat_dim : str, optional Name...
Below is the the instruction that describes the task: ### Input: Assumes that the velocity components are given on a regular grid (fixed spacing in latitude and longitude). Parameters ---------- u_var : str Name of the U-component (zonal) variable. v_var : str Name of the V-comp...
def is_executable(path): '''is the given path executable?''' return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE] or stat.S_IXGRP & os.stat(path)[stat.ST_MODE] or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
is the given path executable?
Below is the the instruction that describes the task: ### Input: is the given path executable? ### Response: def is_executable(path): '''is the given path executable?''' return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE] or stat.S_IXGRP & os.stat(path)[stat.ST_MODE] or stat.S_IXOTH ...
def run(self): """ Fonctionnement du thread """ if self.debug: print("Starting " + self.name) # Lancement du programme du thread if isinstance(self.function, str): globals()[self.function](*self.args, **self.kwargs) else: self.function(*self.args, **self.kwargs) if self.debug: print("Exiting "...
Fonctionnement du thread
Below is the the instruction that describes the task: ### Input: Fonctionnement du thread ### Response: def run(self): """ Fonctionnement du thread """ if self.debug: print("Starting " + self.name) # Lancement du programme du thread if isinstance(self.function, str): globals()[self.function](*self.a...
def smooth(x, rho, penalty, axis=0, newshape=None): """ Applies a smoothing operator along one dimension currently only accepts a matrix as input Parameters ---------- penalty : float axis : int, optional Axis along which to apply the smoothing (Default: 0) newshape : tuple, ...
Applies a smoothing operator along one dimension currently only accepts a matrix as input Parameters ---------- penalty : float axis : int, optional Axis along which to apply the smoothing (Default: 0) newshape : tuple, optional Desired shape of the parameters to apply the nu...
Below is the the instruction that describes the task: ### Input: Applies a smoothing operator along one dimension currently only accepts a matrix as input Parameters ---------- penalty : float axis : int, optional Axis along which to apply the smoothing (Default: 0) newshape : tu...
def _output(self, file_like_object, path=None): """Display or save file like object.""" if not path: self._output_to_display(file_like_object) else: self._output_to_file(file_like_object, path)
Display or save file like object.
Below is the the instruction that describes the task: ### Input: Display or save file like object. ### Response: def _output(self, file_like_object, path=None): """Display or save file like object.""" if not path: self._output_to_display(file_like_object) else: self....
def device(dev, stats=False, config=False, internals=False, superblock=False): ''' Check the state of a single bcache device CLI example: .. code-block:: bash salt '*' bcache.device bcache0 salt '*' bcache.device /dev/sdc stats=True :param stats: include statistics :param set...
Check the state of a single bcache device CLI example: .. code-block:: bash salt '*' bcache.device bcache0 salt '*' bcache.device /dev/sdc stats=True :param stats: include statistics :param settings: include all settings :param internals: include all internals :param superblo...
Below is the the instruction that describes the task: ### Input: Check the state of a single bcache device CLI example: .. code-block:: bash salt '*' bcache.device bcache0 salt '*' bcache.device /dev/sdc stats=True :param stats: include statistics :param settings: include all set...
def _is_not_pickle_safe_gl_model_class(obj_class): """ Check if a Turi create model is pickle safe. The function does it by checking that _CustomModel is the base class. Parameters ---------- obj_class : Class to be checked. Returns ---------- True if the GLC class is a model a...
Check if a Turi create model is pickle safe. The function does it by checking that _CustomModel is the base class. Parameters ---------- obj_class : Class to be checked. Returns ---------- True if the GLC class is a model and is pickle safe.
Below is the the instruction that describes the task: ### Input: Check if a Turi create model is pickle safe. The function does it by checking that _CustomModel is the base class. Parameters ---------- obj_class : Class to be checked. Returns ---------- True if the GLC class is a m...
def build_clnsig(clnsig_info): """docstring for build_clnsig""" clnsig_obj = dict( value = clnsig_info['value'], accession = clnsig_info.get('accession'), revstat = clnsig_info.get('revstat') ) return clnsig_obj
docstring for build_clnsig
Below is the the instruction that describes the task: ### Input: docstring for build_clnsig ### Response: def build_clnsig(clnsig_info): """docstring for build_clnsig""" clnsig_obj = dict( value = clnsig_info['value'], accession = clnsig_info.get('accession'), revstat = clnsig_info....
def get_method_info(self, obj): """Returns the info for a Method """ info = self.get_base_info(obj) info.update({}) return info
Returns the info for a Method
Below is the the instruction that describes the task: ### Input: Returns the info for a Method ### Response: def get_method_info(self, obj): """Returns the info for a Method """ info = self.get_base_info(obj) info.update({}) return info
def lines(n_traces=5,n=100,columns=None,dateIndex=True,mode=None): """ Returns a DataFrame with the required format for a scatter (lines) plot Parameters: ----------- n_traces : int Number of traces n : int Number of points for each trace columns : [str] List of column names dateIndex : bool ...
Returns a DataFrame with the required format for a scatter (lines) plot Parameters: ----------- n_traces : int Number of traces n : int Number of points for each trace columns : [str] List of column names dateIndex : bool If True it will return a datetime index if False it will return a enu...
Below is the the instruction that describes the task: ### Input: Returns a DataFrame with the required format for a scatter (lines) plot Parameters: ----------- n_traces : int Number of traces n : int Number of points for each trace columns : [str] List of column names dateIndex : bool If ...
def server(description=None, **kwargs): '''Create the :class:`.WSGIServer` running :func:`hello`.''' description = description or 'Pulsar Hello World Application' return wsgi.WSGIServer(hello, description=description, **kwargs)
Create the :class:`.WSGIServer` running :func:`hello`.
Below is the the instruction that describes the task: ### Input: Create the :class:`.WSGIServer` running :func:`hello`. ### Response: def server(description=None, **kwargs): '''Create the :class:`.WSGIServer` running :func:`hello`.''' description = description or 'Pulsar Hello World Application' return...
def execute_async(self, output_options=None, sampling=None, context=None, query_params=None): """ Initiate the query and return a QueryJob. Args: output_options: a QueryOutput object describing how to execute the query sampling: sampling function to use. No sampling is done if None. See bigquery.Sa...
Initiate the query and return a QueryJob. Args: output_options: a QueryOutput object describing how to execute the query sampling: sampling function to use. No sampling is done if None. See bigquery.Sampling context: an optional Context object providing project_id and credentials. If a specific ...
Below is the the instruction that describes the task: ### Input: Initiate the query and return a QueryJob. Args: output_options: a QueryOutput object describing how to execute the query sampling: sampling function to use. No sampling is done if None. See bigquery.Sampling context: an optional...
def som_get_capture_objects(som_pointer): """! @brief Returns list of indexes of captured objects by each neuron. @param[in] som_pointer (c_pointer): pointer to object of self-organized map. """ ccore = ccore_library.get() ccore.som_get_capture_objects.restype = POI...
! @brief Returns list of indexes of captured objects by each neuron. @param[in] som_pointer (c_pointer): pointer to object of self-organized map.
Below is the the instruction that describes the task: ### Input: ! @brief Returns list of indexes of captured objects by each neuron. @param[in] som_pointer (c_pointer): pointer to object of self-organized map. ### Response: def som_get_capture_objects(som_pointer): """! @brief Returns li...
def get_current_stats(self, names=None): """Return one or more of the current stats as a tuple. This function does no computation. It only returns what has already been calculated. If a stat hasn't been calculated, it will be returned as ``numpy.nan``. Parameters ------...
Return one or more of the current stats as a tuple. This function does no computation. It only returns what has already been calculated. If a stat hasn't been calculated, it will be returned as ``numpy.nan``. Parameters ---------- names : list of str, optional ...
Below is the the instruction that describes the task: ### Input: Return one or more of the current stats as a tuple. This function does no computation. It only returns what has already been calculated. If a stat hasn't been calculated, it will be returned as ``numpy.nan``. Paramete...
def detrended_price_oscillator(data, period): """ Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1]) """ catch_errors.check_for_period_error(data, period) period = int(period) dop = [data[idx] - np.mean(data[idx+1-(int(period/2)+1):idx+1]) for idx in range(peri...
Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1])
Below is the the instruction that describes the task: ### Input: Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1]) ### Response: def detrended_price_oscillator(data, period): """ Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1]) ""...
def ReadCronJobs(self, cronjob_ids=None): """Reads a cronjob from the database.""" if cronjob_ids is None: res = [job.Copy() for job in itervalues(self.cronjobs)] else: res = [] for job_id in cronjob_ids: try: res.append(self.cronjobs[job_id].Copy()) except KeyEr...
Reads a cronjob from the database.
Below is the the instruction that describes the task: ### Input: Reads a cronjob from the database. ### Response: def ReadCronJobs(self, cronjob_ids=None): """Reads a cronjob from the database.""" if cronjob_ids is None: res = [job.Copy() for job in itervalues(self.cronjobs)] else: res = [...
def evaluate(self, data): """Evaluate the code needed to compute a given Data object.""" expression_engine = data.process.requirements.get('expression-engine', None) if expression_engine is not None: expression_engine = self.get_expression_engine(expression_engine) # Parse s...
Evaluate the code needed to compute a given Data object.
Below is the the instruction that describes the task: ### Input: Evaluate the code needed to compute a given Data object. ### Response: def evaluate(self, data): """Evaluate the code needed to compute a given Data object.""" expression_engine = data.process.requirements.get('expression-engine', Non...
def document(self, document): """ Associate a :class:`~elasticsearch_dsl.Document` subclass with an index. This means that, when this index is created, it will contain the mappings for the ``Document``. If the ``Document`` class doesn't have a default index yet (by defining ``cla...
Associate a :class:`~elasticsearch_dsl.Document` subclass with an index. This means that, when this index is created, it will contain the mappings for the ``Document``. If the ``Document`` class doesn't have a default index yet (by defining ``class Index``), this instance will be used. C...
Below is the the instruction that describes the task: ### Input: Associate a :class:`~elasticsearch_dsl.Document` subclass with an index. This means that, when this index is created, it will contain the mappings for the ``Document``. If the ``Document`` class doesn't have a default index yet...
def get_cso_dataframe(self): """ get a dataframe of composite observation sensitivity, as returned by PEST in the seo file. Note that this formulation deviates slightly from the PEST documentation in that the values are divided by (npar-1) rather than by (npar). The equ...
get a dataframe of composite observation sensitivity, as returned by PEST in the seo file. Note that this formulation deviates slightly from the PEST documentation in that the values are divided by (npar-1) rather than by (npar). The equation is cso_j = ((Q^1/2*J*J^T*Q^1/2)^1/2)_jj/(NP...
Below is the the instruction that describes the task: ### Input: get a dataframe of composite observation sensitivity, as returned by PEST in the seo file. Note that this formulation deviates slightly from the PEST documentation in that the values are divided by (npar-1) rather than by (npa...
def watch(value, spectator_type=Spectator): """Register a :class:`Specatator` to a :class:`Watchable` and return it. In order to register callbacks to an eventful object, you need to create a Spectator that will watch it for you. A :class:`Specatator` is a relatively simple object that has methods for ...
Register a :class:`Specatator` to a :class:`Watchable` and return it. In order to register callbacks to an eventful object, you need to create a Spectator that will watch it for you. A :class:`Specatator` is a relatively simple object that has methods for adding, deleting, and triggering callbacks. To ...
Below is the the instruction that describes the task: ### Input: Register a :class:`Specatator` to a :class:`Watchable` and return it. In order to register callbacks to an eventful object, you need to create a Spectator that will watch it for you. A :class:`Specatator` is a relatively simple object tha...
def create(host, port): """ Prepare server to execute :return: Modules to execute, cmd line function :rtype: list[WrapperServer], callable | None """ wrapper = WrapperEchoServer({ 'server': None }) d = { 'listen_port': port, 'changer': wrapper } if host: ...
Prepare server to execute :return: Modules to execute, cmd line function :rtype: list[WrapperServer], callable | None
Below is the the instruction that describes the task: ### Input: Prepare server to execute :return: Modules to execute, cmd line function :rtype: list[WrapperServer], callable | None ### Response: def create(host, port): """ Prepare server to execute :return: Modules to execute, cmd line func...
def dallinger(): """Dallinger command-line utility.""" from logging.config import fileConfig fileConfig( os.path.join(os.path.dirname(__file__), "logging.ini"), disable_existing_loggers=False, )
Dallinger command-line utility.
Below is the the instruction that describes the task: ### Input: Dallinger command-line utility. ### Response: def dallinger(): """Dallinger command-line utility.""" from logging.config import fileConfig fileConfig( os.path.join(os.path.dirname(__file__), "logging.ini"), disable_existi...
def disable(name, lbn, target, profile='default', tgt_type='glob'): ''' .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Disable the named worker from the lbn load balancers at the targeted minions. The wo...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Disable the named worker from the lbn load balancers at the targeted minions. The worker will get traffic only for current sessions and won't get new ones. ...
Below is the the instruction that describes the task: ### Input: .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Disable the named worker from the lbn load balancers at the targeted minions. The worker will g...
def add_group(self, group_attribs=None, parent=None): """Add an empty group element to the SVG.""" if parent is None: parent = self.tree.getroot() elif not self.contains_group(parent): warnings.warn('The requested group {0} does not belong to ' '...
Add an empty group element to the SVG.
Below is the the instruction that describes the task: ### Input: Add an empty group element to the SVG. ### Response: def add_group(self, group_attribs=None, parent=None): """Add an empty group element to the SVG.""" if parent is None: parent = self.tree.getroot() elif not self....
def list_observatories(self): """ Get the IDs of all observatories with have stored observations on this server. :return: a sequence of strings containing observatories IDs """ response = requests.get(self.base_url + '/obstories').text return safe_load(response)
Get the IDs of all observatories with have stored observations on this server. :return: a sequence of strings containing observatories IDs
Below is the the instruction that describes the task: ### Input: Get the IDs of all observatories with have stored observations on this server. :return: a sequence of strings containing observatories IDs ### Response: def list_observatories(self): """ Get the IDs of all observatories with ...
def do_with_ruby(ruby, cmdline, runas=None): ''' Execute a ruby command with rbenv's shims using a specific ruby version CLI Example: .. code-block:: bash salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy '...
Execute a ruby command with rbenv's shims using a specific ruby version CLI Example: .. code-block:: bash salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
Below is the the instruction that describes the task: ### Input: Execute a ruby command with rbenv's shims using a specific ruby version CLI Example: .. code-block:: bash salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=...
def make_tarball(base_name, base_dir, compress='gzip', verbose=False, dry_run=False): """Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' ...
Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip' and 'bzip2' the internal tarfile module will be used. For 'comp...
Below is the the instruction that describes the task: ### Input: Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip...
def read(self, size = -1): """ Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment """ if size < -1: raise Exception('You shouldnt be doing this') if size == -1: t = self.current_segment.remaining_len(self.current_position) ...
Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment
Below is the the instruction that describes the task: ### Input: Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment ### Response: def read(self, size = -1): """ Returns data bytes of size size from the current segment. If size is ...
def _count_vocab(self, analyzed_docs): """Create sparse feature matrix, and vocabulary where fixed_vocab=False """ vocabulary = self.vocabulary_ j_indices = _make_int_array() indptr = _make_int_array() indptr.append(0) for doc in analyzed_docs: for fea...
Create sparse feature matrix, and vocabulary where fixed_vocab=False
Below is the the instruction that describes the task: ### Input: Create sparse feature matrix, and vocabulary where fixed_vocab=False ### Response: def _count_vocab(self, analyzed_docs): """Create sparse feature matrix, and vocabulary where fixed_vocab=False """ vocabulary = self.vocabulary...
def _first_step_to_match(match_step): """Transform the very first MATCH step into a MATCH query string.""" parts = [] if match_step.root_block is not None: if not isinstance(match_step.root_block, QueryRoot): raise AssertionError(u'Expected None or QueryRoot root block, received: ' ...
Transform the very first MATCH step into a MATCH query string.
Below is the the instruction that describes the task: ### Input: Transform the very first MATCH step into a MATCH query string. ### Response: def _first_step_to_match(match_step): """Transform the very first MATCH step into a MATCH query string.""" parts = [] if match_step.root_block is not None: ...
def _create_translation_file(feature_folder, dataset_name, translation, formula_id2index): """ Write a loop-up file that contains the direct (record-wise) lookup information. Parameters ---------- feature_fol...
Write a loop-up file that contains the direct (record-wise) lookup information. Parameters ---------- feature_folder : Path to the feature files. dataset_name : 'traindata', 'validdata' or 'testdata'. translation : list of triples (raw data id, formula in latex, formula ...
Below is the the instruction that describes the task: ### Input: Write a loop-up file that contains the direct (record-wise) lookup information. Parameters ---------- feature_folder : Path to the feature files. dataset_name : 'traindata', 'validdata' or 'testdata'. translati...
def tabulate(d, transpose=False, thousands=True, key_fun=None, sep=',', align=True): """ d is a dictionary, keyed by tuple(A, B). Goal is to put A in rows, B in columns, report data in table form. >>> d = {(1,'a'):3, (1,'b'):4, (2,'a'):5, (2,'b'):0} >>> print tabulate(d) =========== o a ...
d is a dictionary, keyed by tuple(A, B). Goal is to put A in rows, B in columns, report data in table form. >>> d = {(1,'a'):3, (1,'b'):4, (2,'a'):5, (2,'b'):0} >>> print tabulate(d) =========== o a b ----------- 1 3 4 2 5 0 ----------- >>> print tabulate(d, tr...
Below is the the instruction that describes the task: ### Input: d is a dictionary, keyed by tuple(A, B). Goal is to put A in rows, B in columns, report data in table form. >>> d = {(1,'a'):3, (1,'b'):4, (2,'a'):5, (2,'b'):0} >>> print tabulate(d) =========== o a b ----------- 1 ...
def CLJP(S, color=False): """Compute a C/F splitting using the parallel CLJP algorithm. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) color : bool use the CLJP coloring approach Returns ------...
Compute a C/F splitting using the parallel CLJP algorithm. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) color : bool use the CLJP coloring approach Returns ------- splitting : array A...
Below is the the instruction that describes the task: ### Input: Compute a C/F splitting using the parallel CLJP algorithm. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) color : bool use the CLJP color...
def get_git_home(path='.'): """Get Git path from the current context.""" ctx = click.get_current_context(silent=True) if ctx and GIT_KEY in ctx.meta: return ctx.meta[GIT_KEY] from git import Repo return Repo(path, search_parent_directories=True).working_dir
Get Git path from the current context.
Below is the the instruction that describes the task: ### Input: Get Git path from the current context. ### Response: def get_git_home(path='.'): """Get Git path from the current context.""" ctx = click.get_current_context(silent=True) if ctx and GIT_KEY in ctx.meta: return ctx.meta[GIT_KEY] ...
def crc8(data): """ Perform the 1-Wire CRC check on the provided data. :param bytearray data: 8 byte array representing 64 bit ROM code """ crc = 0 for byte in data: crc ^= byte for _ in range(8): if crc & 0x01: ...
Perform the 1-Wire CRC check on the provided data. :param bytearray data: 8 byte array representing 64 bit ROM code
Below is the the instruction that describes the task: ### Input: Perform the 1-Wire CRC check on the provided data. :param bytearray data: 8 byte array representing 64 bit ROM code ### Response: def crc8(data): """ Perform the 1-Wire CRC check on the provided data. :param bytearra...
def _set_fc_port(self, v, load=False): """ Setter method for fc_port, mapped from YANG variable /interface/fc_port (list) If this variable is read-only (config: false) in the source YANG file, then _set_fc_port is considered as a private method. Backends looking to populate this variable should ...
Setter method for fc_port, mapped from YANG variable /interface/fc_port (list) If this variable is read-only (config: false) in the source YANG file, then _set_fc_port is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_fc_port() directly. ...
Below is the the instruction that describes the task: ### Input: Setter method for fc_port, mapped from YANG variable /interface/fc_port (list) If this variable is read-only (config: false) in the source YANG file, then _set_fc_port is considered as a private method. Backends looking to populate this va...
def stat(self, follow_symlinks=True): """Return a stat_result object for this entry. Args: follow_symlinks: If False and the entry is a symlink, return the result for the symlink, otherwise for the object it points to. """ if follow_symlinks: if s...
Return a stat_result object for this entry. Args: follow_symlinks: If False and the entry is a symlink, return the result for the symlink, otherwise for the object it points to.
Below is the the instruction that describes the task: ### Input: Return a stat_result object for this entry. Args: follow_symlinks: If False and the entry is a symlink, return the result for the symlink, otherwise for the object it points to. ### Response: def stat(self, follow...
def close_filenos(preserve): """ Close unprotected file descriptors Close all open file descriptors that are not in preserve. If ulimit -nofile is "unlimited", all is defined filenos <= 4096, else all is <= the output of resource.getrlimit(). :param preserve: set with protected files :type pr...
Close unprotected file descriptors Close all open file descriptors that are not in preserve. If ulimit -nofile is "unlimited", all is defined filenos <= 4096, else all is <= the output of resource.getrlimit(). :param preserve: set with protected files :type preserve: set :return: None
Below is the the instruction that describes the task: ### Input: Close unprotected file descriptors Close all open file descriptors that are not in preserve. If ulimit -nofile is "unlimited", all is defined filenos <= 4096, else all is <= the output of resource.getrlimit(). :param preserve: set w...
def update_ssh_public_key( self, name, ssh_public_key, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an SSH public key and returns the profile inf...
Updates an SSH public key and returns the profile information. This method supports patch semantics. Example: >>> from google.cloud import oslogin_v1 >>> >>> client = oslogin_v1.OsLoginServiceClient() >>> >>> name = client.fingerprint_path('[U...
Below is the the instruction that describes the task: ### Input: Updates an SSH public key and returns the profile information. This method supports patch semantics. Example: >>> from google.cloud import oslogin_v1 >>> >>> client = oslogin_v1.OsLoginServiceClient...
def bear(a1, b1, a2, b2): """Find bearing/position angle between two points on a unit sphere. Parameters ---------- a1, b1 : float Longitude-like and latitude-like angles defining the first point. Both are in radians. a2, b2 : float Longitude-like and latitude-like angles d...
Find bearing/position angle between two points on a unit sphere. Parameters ---------- a1, b1 : float Longitude-like and latitude-like angles defining the first point. Both are in radians. a2, b2 : float Longitude-like and latitude-like angles defining the second point....
Below is the the instruction that describes the task: ### Input: Find bearing/position angle between two points on a unit sphere. Parameters ---------- a1, b1 : float Longitude-like and latitude-like angles defining the first point. Both are in radians. a2, b2 : float Longi...
def get_template_loader(self, subdir='templates'): '''App-specific function to get the current app's template loader''' if self.request is None: raise ValueError("this method can only be called after the view middleware is run. Check that `django_mako_plus.middleware` is in MIDDLEWARE.") ...
App-specific function to get the current app's template loader
Below is the the instruction that describes the task: ### Input: App-specific function to get the current app's template loader ### Response: def get_template_loader(self, subdir='templates'): '''App-specific function to get the current app's template loader''' if self.request is None: ...
def getLoggingLocation(self): """Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go.""" if sys.platform == "win32": modulePath = os.path.realpath(__file__) modulePath = modulePath[:modulePath.rfind("/")] return modulePath ...
Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go.
Below is the the instruction that describes the task: ### Input: Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go. ### Response: def getLoggingLocation(self): """Return the path for the calcpkg.log file - at the moment, only us...
def c_if(self, classical, val): """Add classical control register to all instructions.""" for gate in self.instructions: gate.c_if(classical, val) return self
Add classical control register to all instructions.
Below is the the instruction that describes the task: ### Input: Add classical control register to all instructions. ### Response: def c_if(self, classical, val): """Add classical control register to all instructions.""" for gate in self.instructions: gate.c_if(classical, val) r...
def terminate(self): """Signal runner to stop and join thread.""" self.toggle_scan(False) self.keep_going = False self.join()
Signal runner to stop and join thread.
Below is the the instruction that describes the task: ### Input: Signal runner to stop and join thread. ### Response: def terminate(self): """Signal runner to stop and join thread.""" self.toggle_scan(False) self.keep_going = False self.join()
def create_hosting_device_resources(self, context, complementary_id, tenant_id, mgmt_context, max_hosted): """Create resources for a hosting device in a plugin specific way.""" mgmt_port = None if mgmt_context and mgmt_context.get('mgmt_nw_id') and tenant_...
Create resources for a hosting device in a plugin specific way.
Below is the the instruction that describes the task: ### Input: Create resources for a hosting device in a plugin specific way. ### Response: def create_hosting_device_resources(self, context, complementary_id, tenant_id, mgmt_context, max_hosted): """Create resourc...
def updateFile(self, logical_file_name=[], is_file_valid=1, lost=0, dataset=''): """ API to update file status :param logical_file_name: logical_file_name to update (optional), but must have either a fln or a dataset :type logical_file_name: str :param is_file_valid: va...
API to update file status :param logical_file_name: logical_file_name to update (optional), but must have either a fln or a dataset :type logical_file_name: str :param is_file_valid: valid=1, invalid=0 (Required) :type is_file_valid: bool :param lost: default lost=0 (op...
Below is the the instruction that describes the task: ### Input: API to update file status :param logical_file_name: logical_file_name to update (optional), but must have either a fln or a dataset :type logical_file_name: str :param is_file_valid: valid=1, invalid=0 (Required) ...
def commit(self, changeset_id: uuid.UUID) -> None: """ Commits a given changeset. This merges the given changeset and all subsequent changesets into the previous changeset giving precidence to later changesets in case of any conflicting keys. If this is the base changeset then a...
Commits a given changeset. This merges the given changeset and all subsequent changesets into the previous changeset giving precidence to later changesets in case of any conflicting keys. If this is the base changeset then all changes will be written to the underlying database and the J...
Below is the the instruction that describes the task: ### Input: Commits a given changeset. This merges the given changeset and all subsequent changesets into the previous changeset giving precidence to later changesets in case of any conflicting keys. If this is the base changeset then all...
def load_data(self, mode="train", format="csv"): """ Load data from flat data files containing total track information and information about each timestep. The two sets are combined using merge operations on the Track IDs. Additional member information is gathered from the appropriate me...
Load data from flat data files containing total track information and information about each timestep. The two sets are combined using merge operations on the Track IDs. Additional member information is gathered from the appropriate member file. Args: mode: "train" or "forecast" ...
Below is the the instruction that describes the task: ### Input: Load data from flat data files containing total track information and information about each timestep. The two sets are combined using merge operations on the Track IDs. Additional member information is gathered from the appropriate me...
def post_event(self, event): """ Posts a single event to the Keen IO API. The write key must be set first. :param event: an Event to upload """ url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url, self.api_version, ...
Posts a single event to the Keen IO API. The write key must be set first. :param event: an Event to upload
Below is the the instruction that describes the task: ### Input: Posts a single event to the Keen IO API. The write key must be set first. :param event: an Event to upload ### Response: def post_event(self, event): """ Posts a single event to the Keen IO API. The write key must be set firs...
def num_to_var_int(x): """ (bitcoin-specific): convert an integer into a variable-length integer """ x = int(x) if x < 253: return from_int_to_byte(x) elif x < 65536: return from_int_to_byte(253) + encode(x, 256, 2)[::-1] elif x < 4294967296: return from_int_to_byte...
(bitcoin-specific): convert an integer into a variable-length integer
Below is the the instruction that describes the task: ### Input: (bitcoin-specific): convert an integer into a variable-length integer ### Response: def num_to_var_int(x): """ (bitcoin-specific): convert an integer into a variable-length integer """ x = int(x) if x < 253: return from_in...
def Scatter(y, win=13, remove_outliers=False): ''' Return the scatter in ppm based on the median running standard deviation for a window size of :py:obj:`win` = 13 cadences (for K2, this is ~6.5 hours, as in VJ14). :param ndarray y: The array whose CDPP is to be computed :param int win: The win...
Return the scatter in ppm based on the median running standard deviation for a window size of :py:obj:`win` = 13 cadences (for K2, this is ~6.5 hours, as in VJ14). :param ndarray y: The array whose CDPP is to be computed :param int win: The window size in cadences. Default `13` :param bool remove_o...
Below is the the instruction that describes the task: ### Input: Return the scatter in ppm based on the median running standard deviation for a window size of :py:obj:`win` = 13 cadences (for K2, this is ~6.5 hours, as in VJ14). :param ndarray y: The array whose CDPP is to be computed :param int wi...
def _check_samples_line(klass, arr): """Peform additional check on samples line""" if len(arr) <= len(REQUIRE_NO_SAMPLE_HEADER): if tuple(arr) != REQUIRE_NO_SAMPLE_HEADER: raise exceptions.IncorrectVCFFormat( "Sample header line indicates no sample but doe...
Peform additional check on samples line
Below is the the instruction that describes the task: ### Input: Peform additional check on samples line ### Response: def _check_samples_line(klass, arr): """Peform additional check on samples line""" if len(arr) <= len(REQUIRE_NO_SAMPLE_HEADER): if tuple(arr) != REQUIRE_NO_SAMPLE_HEAD...
def ListClientsForKeywords(self, keywords, start_time=None): """Lists the clients associated with keywords.""" res = {kw: [] for kw in keywords} for kw in keywords: for client_id, timestamp in iteritems(self.keywords.get(kw, {})): if start_time is not None and timestamp < start_time: ...
Lists the clients associated with keywords.
Below is the the instruction that describes the task: ### Input: Lists the clients associated with keywords. ### Response: def ListClientsForKeywords(self, keywords, start_time=None): """Lists the clients associated with keywords.""" res = {kw: [] for kw in keywords} for kw in keywords: for clien...
def getFrontmostApp(cls): """Get the current frontmost application. Raise a ValueError exception if no GUI applications are found. """ # Refresh the runningApplications list apps = cls._getRunningApps() for app in apps: pid = app.processIdentifier() ...
Get the current frontmost application. Raise a ValueError exception if no GUI applications are found.
Below is the the instruction that describes the task: ### Input: Get the current frontmost application. Raise a ValueError exception if no GUI applications are found. ### Response: def getFrontmostApp(cls): """Get the current frontmost application. Raise a ValueError exception if no GUI a...
def validate(self, columns=None): """ Validates the current record object to make sure it is ok to commit to the database. If the optional override dictionary is passed in, then it will use the given values vs. the one stored with this record object which can be useful to check to see i...
Validates the current record object to make sure it is ok to commit to the database. If the optional override dictionary is passed in, then it will use the given values vs. the one stored with this record object which can be useful to check to see if the record will be valid before it is commit...
Below is the the instruction that describes the task: ### Input: Validates the current record object to make sure it is ok to commit to the database. If the optional override dictionary is passed in, then it will use the given values vs. the one stored with this record object which can be useful to...
def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', ...
Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return:
Below is the the instruction that describes the task: ### Input: Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ### Response: def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from ...
def _filter_defs_at_call_sites(self, defs): """ If we are not tracing into the function that are called in a real execution, we should properly filter the defs to account for the behavior of the skipped function at this call site. This function is a WIP. See TODOs inside. :para...
If we are not tracing into the function that are called in a real execution, we should properly filter the defs to account for the behavior of the skipped function at this call site. This function is a WIP. See TODOs inside. :param defs: :return:
Below is the the instruction that describes the task: ### Input: If we are not tracing into the function that are called in a real execution, we should properly filter the defs to account for the behavior of the skipped function at this call site. This function is a WIP. See TODOs inside. ...
def build_attrs(self, *args, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(*args, **kwargs) return self.attrs
Helper function for building an attribute dictionary.
Below is the the instruction that describes the task: ### Input: Helper function for building an attribute dictionary. ### Response: def build_attrs(self, *args, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(*args, **kwargs) return s...
def amari_alpha(logu, alpha=1., self_normalized=False, name=None): """The Amari-alpha Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` When `self_normalized = True`, the Amari-alpha Csiszar-function is: ```none f(u) = { -log(u) + (u - 1), ...
The Amari-alpha Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` When `self_normalized = True`, the Amari-alpha Csiszar-function is: ```none f(u) = { -log(u) + (u - 1), alpha = 0 { u log(u) - (u - 1), alpha = 1 { [(u*...
Below is the the instruction that describes the task: ### Input: The Amari-alpha Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` When `self_normalized = True`, the Amari-alpha Csiszar-function is: ```none f(u) = { -log(u) + (u - 1), ...
def get_job(self, job_resource_name: str) -> Dict: """Returns metadata about a previously created job. See get_job_result if you want the results of the job and not just metadata about the job. Params: job_resource_name: A string of the form `projects/projec...
Returns metadata about a previously created job. See get_job_result if you want the results of the job and not just metadata about the job. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. Returns: ...
Below is the the instruction that describes the task: ### Input: Returns metadata about a previously created job. See get_job_result if you want the results of the job and not just metadata about the job. Params: job_resource_name: A string of the form `projects...
def register_plugin(self): """Register plugin in Spyder's main window""" self.breakpoints.edit_goto.connect(self.main.editor.load) #self.redirect_stdio.connect(self.main.redirect_internalshell_stdio) self.breakpoints.clear_all_breakpoints.connect( ...
Register plugin in Spyder's main window
Below is the the instruction that describes the task: ### Input: Register plugin in Spyder's main window ### Response: def register_plugin(self): """Register plugin in Spyder's main window""" self.breakpoints.edit_goto.connect(self.main.editor.load) #self.redirect_stdio.connect(self.main...
def _squeeze(x, axis): """A version of squeeze that works with dynamic axis.""" x = tf.convert_to_tensor(value=x, name='x') if axis is None: return tf.squeeze(x, axis=None) axis = tf.convert_to_tensor(value=axis, name='axis', dtype=tf.int32) axis += tf.zeros([1], dtype=axis.dtype) # Make axis at least 1d...
A version of squeeze that works with dynamic axis.
Below is the the instruction that describes the task: ### Input: A version of squeeze that works with dynamic axis. ### Response: def _squeeze(x, axis): """A version of squeeze that works with dynamic axis.""" x = tf.convert_to_tensor(value=x, name='x') if axis is None: return tf.squeeze(x, axis=None) ...
def imports(modules, forgive=False): """ Should be used as a decorator to *attach* import statments to function definitions. These imports are added to the global (i.e. module-level of the decorated function) namespace. Two forms of import statements are supported (in the following example...
Should be used as a decorator to *attach* import statments to function definitions. These imports are added to the global (i.e. module-level of the decorated function) namespace. Two forms of import statements are supported (in the following examples ``foo``, ``bar``, ``oof, and ``rab`` are mo...
Below is the the instruction that describes the task: ### Input: Should be used as a decorator to *attach* import statments to function definitions. These imports are added to the global (i.e. module-level of the decorated function) namespace. Two forms of import statements are supported (in t...
def generate_set_partitions(set_): """Generate all of the partitions of a set. This is a helper function that utilizes the restricted growth strings from :py:func:`generate_set_partition_strings`. The partitions are returned in lexicographic order. Parameters ---------- set_ : :py:...
Generate all of the partitions of a set. This is a helper function that utilizes the restricted growth strings from :py:func:`generate_set_partition_strings`. The partitions are returned in lexicographic order. Parameters ---------- set_ : :py:class:`Array` or other Array-like, (`m`,) ...
Below is the the instruction that describes the task: ### Input: Generate all of the partitions of a set. This is a helper function that utilizes the restricted growth strings from :py:func:`generate_set_partition_strings`. The partitions are returned in lexicographic order. Parameters ...
def pair(seeders, delegator_factory, *args, **kwargs): """ The basic pair producer. :return: a (seeder, delegator_factory(\*args, \*\*kwargs)) tuple. :param seeders: If it is a seeder function or a list of one seeder function, it is returned as the final seeder. If it is a list...
The basic pair producer. :return: a (seeder, delegator_factory(\*args, \*\*kwargs)) tuple. :param seeders: If it is a seeder function or a list of one seeder function, it is returned as the final seeder. If it is a list of more than one seeder function, they are chained togethe...
Below is the the instruction that describes the task: ### Input: The basic pair producer. :return: a (seeder, delegator_factory(\*args, \*\*kwargs)) tuple. :param seeders: If it is a seeder function or a list of one seeder function, it is returned as the final seeder. If it is a li...
def iter(context, resource, **kwargs): """List all resources""" data = utils.sanitize_kwargs(**kwargs) id = data.pop('id', None) subresource = data.pop('subresource', None) data['limit'] = data.get('limit', 20) if subresource: uri = '%s/%s/%s/%s' % (context.dci_cs_api, resource, id, sub...
List all resources
Below is the the instruction that describes the task: ### Input: List all resources ### Response: def iter(context, resource, **kwargs): """List all resources""" data = utils.sanitize_kwargs(**kwargs) id = data.pop('id', None) subresource = data.pop('subresource', None) data['limit'] = data.get...
def init_connection_file(self): """find the connection file, and load the info if found. The current working directory and the current profile's security directory will be searched for the file if it is not given by absolute path. When attempting to connect to a...
find the connection file, and load the info if found. The current working directory and the current profile's security directory will be searched for the file if it is not given by absolute path. When attempting to connect to an existing kernel and the `--existing` ...
Below is the the instruction that describes the task: ### Input: find the connection file, and load the info if found. The current working directory and the current profile's security directory will be searched for the file if it is not given by absolute path. When ...
def _validate_forbidden(self, forbidden_values, field, value): """ {'type': 'list'} """ if isinstance(value, _str_type): if value in forbidden_values: self._error(field, errors.FORBIDDEN_VALUE, value) elif isinstance(value, Sequence): forbidden = set(value...
{'type': 'list'}
Below is the the instruction that describes the task: ### Input: {'type': 'list'} ### Response: def _validate_forbidden(self, forbidden_values, field, value): """ {'type': 'list'} """ if isinstance(value, _str_type): if value in forbidden_values: self._error(field, error...
def _calc_footprint(self): """Return rectangle in world coordinates, as GeoVector.""" corners = [self.corner(corner) for corner in self.corner_types()] coords = [] for corner in corners: shape = corner.get_shape(corner.crs) coords.append([shape.x, shape.y]) ...
Return rectangle in world coordinates, as GeoVector.
Below is the the instruction that describes the task: ### Input: Return rectangle in world coordinates, as GeoVector. ### Response: def _calc_footprint(self): """Return rectangle in world coordinates, as GeoVector.""" corners = [self.corner(corner) for corner in self.corner_types()] coords ...
def t0_ref_supconj(b, orbit, solve_for=None, **kwargs): """ Create a constraint for t0_ref in an orbit - allowing translating between t0_ref and t0_supconj. :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit in which this constraint should ...
Create a constraint for t0_ref in an orbit - allowing translating between t0_ref and t0_supconj. :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit in which this constraint should be built :parameter str solve_for: if 't0_ref' should not be th...
Below is the the instruction that describes the task: ### Input: Create a constraint for t0_ref in an orbit - allowing translating between t0_ref and t0_supconj. :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit in which this constraint should...
def pushback(self) -> None: """Push one character back onto the stream, allowing it to be read again.""" if abs(self._idx - 1) > self._pushback_depth: raise IndexError("Exceeded pushback depth") self._idx -= 1
Push one character back onto the stream, allowing it to be read again.
Below is the the instruction that describes the task: ### Input: Push one character back onto the stream, allowing it to be read again. ### Response: def pushback(self) -> None: """Push one character back onto the stream, allowing it to be read again.""" if abs(self._idx - 1) > self...
def _str_to_int(self, string): """Check for the hex """ string = string.lower() if string.endswith("l"): string = string[:-1] if string.lower().startswith("0x"): # should always match match = re.match(r'0[xX]([a-fA-F0-9]+)', string) ...
Check for the hex
Below is the the instruction that describes the task: ### Input: Check for the hex ### Response: def _str_to_int(self, string): """Check for the hex """ string = string.lower() if string.endswith("l"): string = string[:-1] if string.lower().startswith("0x"): ...
def containerIsRunning(container_name): """ Checks whether the container is running or not. :param container_name: Name of the container being checked. :returns: True if status is 'running', False if status is anything else, and None if the container does not exist. """ client = docker.from_...
Checks whether the container is running or not. :param container_name: Name of the container being checked. :returns: True if status is 'running', False if status is anything else, and None if the container does not exist.
Below is the the instruction that describes the task: ### Input: Checks whether the container is running or not. :param container_name: Name of the container being checked. :returns: True if status is 'running', False if status is anything else, and None if the container does not exist. ### Response: d...
def get_jids(): ''' Return a list of all job ids ''' serv = _get_serv(ret=None) jids = _get_list(serv, 'jids') loads = serv.get_multi(jids) # {jid: load, jid: load, ...} ret = {} for jid, load in six.iteritems(loads): ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils...
Return a list of all job ids
Below is the the instruction that describes the task: ### Input: Return a list of all job ids ### Response: def get_jids(): ''' Return a list of all job ids ''' serv = _get_serv(ret=None) jids = _get_list(serv, 'jids') loads = serv.get_multi(jids) # {jid: load, jid: load, ...} ret = {}...
def source_absent(name): ''' Ensure an image source is absent on the computenode name : string source url ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if name not in __salt__['imgadm.sources'](): # source is absent ...
Ensure an image source is absent on the computenode name : string source url
Below is the the instruction that describes the task: ### Input: Ensure an image source is absent on the computenode name : string source url ### Response: def source_absent(name): ''' Ensure an image source is absent on the computenode name : string source url ''' ret = {...
def lazy_result(f): """Decorate function to return LazyProxy.""" @wraps(f) def decorated(ctx, param, value): return LocalProxy(lambda: f(ctx, param, value)) return decorated
Decorate function to return LazyProxy.
Below is the the instruction that describes the task: ### Input: Decorate function to return LazyProxy. ### Response: def lazy_result(f): """Decorate function to return LazyProxy.""" @wraps(f) def decorated(ctx, param, value): return LocalProxy(lambda: f(ctx, param, value)) return decorated
def filter(args): """ %prog filter test.blast Produce a new blast file and filter based on: - score: >= cutoff - pctid: >= cutoff - hitlen: >= cutoff - evalue: <= cutoff - ids: valid ids Use --inverse to obtain the complementary records for the criteria above. - noself: remove...
%prog filter test.blast Produce a new blast file and filter based on: - score: >= cutoff - pctid: >= cutoff - hitlen: >= cutoff - evalue: <= cutoff - ids: valid ids Use --inverse to obtain the complementary records for the criteria above. - noself: remove self-self hits
Below is the the instruction that describes the task: ### Input: %prog filter test.blast Produce a new blast file and filter based on: - score: >= cutoff - pctid: >= cutoff - hitlen: >= cutoff - evalue: <= cutoff - ids: valid ids Use --inverse to obtain the complementary records for th...
def setup(config, minconn=5, maxconn=10, adapter='mysql', key='default', slave=False): """Setup database :param config dict: is the db adapter config :param key string: the key to identify dabtabase :param adapter string: the dabtabase adapter current support mysql only :param minconn int: the mi...
Setup database :param config dict: is the db adapter config :param key string: the key to identify dabtabase :param adapter string: the dabtabase adapter current support mysql only :param minconn int: the min connection for connection pool :param maxconn int: the max connection for connection pool ...
Below is the the instruction that describes the task: ### Input: Setup database :param config dict: is the db adapter config :param key string: the key to identify dabtabase :param adapter string: the dabtabase adapter current support mysql only :param minconn int: the min connection for connection...
def matched_filter(template, data, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None, sigmasq=None): """ Return the complex snr. Return the complex snr, along with its associated normalization of the template, matched filtered against the data. Parameters ----------...
Return the complex snr. Return the complex snr, along with its associated normalization of the template, matched filtered against the data. Parameters ---------- template : TimeSeries or FrequencySeries The template waveform data : TimeSeries or FrequencySeries The strain data ...
Below is the the instruction that describes the task: ### Input: Return the complex snr. Return the complex snr, along with its associated normalization of the template, matched filtered against the data. Parameters ---------- template : TimeSeries or FrequencySeries The template wavef...