code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def add_callback(self, method): """ Attaches a mehtod that will be called when the future finishes. :param method: A callable from an actor that will be called when the future completes. The only argument for that method must be the future itself from wich you can get th...
Attaches a mehtod that will be called when the future finishes. :param method: A callable from an actor that will be called when the future completes. The only argument for that method must be the future itself from wich you can get the result though `future.:meth:`result()`...
Below is the the instruction that describes the task: ### Input: Attaches a mehtod that will be called when the future finishes. :param method: A callable from an actor that will be called when the future completes. The only argument for that method must be the future itself from wi...
def _file_num_records_cached(filename): """Return the number of TFRecords in a file.""" # Cache the result, as this is expensive to compute if filename in _file_num_records_cache: return _file_num_records_cache[filename] ret = 0 for _ in tf.python_io.tf_record_iterator(filename): ret += 1 _file_num_...
Return the number of TFRecords in a file.
Below is the the instruction that describes the task: ### Input: Return the number of TFRecords in a file. ### Response: def _file_num_records_cached(filename): """Return the number of TFRecords in a file.""" # Cache the result, as this is expensive to compute if filename in _file_num_records_cache: retu...
def _PreParse(self, key, value): """Executed against each field of each row read from index table.""" if key == "Command": return re.sub(r"(\[\[.+?\]\])", self._Completion, value) else: return value
Executed against each field of each row read from index table.
Below is the the instruction that describes the task: ### Input: Executed against each field of each row read from index table. ### Response: def _PreParse(self, key, value): """Executed against each field of each row read from index table.""" if key == "Command": return re.sub(r"(\[\[....
def power(a,b): ''' power(a,b) is equivalent to a**b except that, like the neuropythy.util.times function, it threads over the earliest dimension possible rather than the latest, as numpy's power function and ** syntax do. The power() function also works with sparse arrays; though it must reify ...
power(a,b) is equivalent to a**b except that, like the neuropythy.util.times function, it threads over the earliest dimension possible rather than the latest, as numpy's power function and ** syntax do. The power() function also works with sparse arrays; though it must reify them during the process.
Below is the the instruction that describes the task: ### Input: power(a,b) is equivalent to a**b except that, like the neuropythy.util.times function, it threads over the earliest dimension possible rather than the latest, as numpy's power function and ** syntax do. The power() function also works with...
def create(self, equipments): """ Method to create equipments :param equipments: List containing equipments desired to be created on database :return: None """ data = {'equipments': equipments} return super(ApiEquipment, self).post('api/v3/equipment/', data)
Method to create equipments :param equipments: List containing equipments desired to be created on database :return: None
Below is the the instruction that describes the task: ### Input: Method to create equipments :param equipments: List containing equipments desired to be created on database :return: None ### Response: def create(self, equipments): """ Method to create equipments :param equ...
def transform(self, job_name, model_name, strategy, max_concurrent_transforms, max_payload, env, input_config, output_config, resource_config, tags): """Create an Amazon SageMaker transform job. Args: job_name (str): Name of the transform job being created. mod...
Create an Amazon SageMaker transform job. Args: job_name (str): Name of the transform job being created. model_name (str): Name of the SageMaker model being used for the transform job. strategy (str): The strategy used to decide how to batch records in a single request. ...
Below is the the instruction that describes the task: ### Input: Create an Amazon SageMaker transform job. Args: job_name (str): Name of the transform job being created. model_name (str): Name of the SageMaker model being used for the transform job. strategy (str): The s...
def get_queryset(self): """ This method is repeated because some managers that don't use super() or alter queryset class may return queryset that is not subclass of MultilingualQuerySet. """ qs = super(MultilingualManager, self).get_queryset() if isinstance(qs, Multilingu...
This method is repeated because some managers that don't use super() or alter queryset class may return queryset that is not subclass of MultilingualQuerySet.
Below is the the instruction that describes the task: ### Input: This method is repeated because some managers that don't use super() or alter queryset class may return queryset that is not subclass of MultilingualQuerySet. ### Response: def get_queryset(self): """ This method is repeated b...
def _create_file(): """ Returns a file handle which is used to record audio """ f = wave.open('audio.wav', mode='wb') f.setnchannels(2) p = pyaudio.PyAudio() f.setsampwidth(p.get_sample_size(pyaudio.paInt16)) f.setframerate(p.get_default_input_device_info()['defaultSampleRate']) try:...
Returns a file handle which is used to record audio
Below is the the instruction that describes the task: ### Input: Returns a file handle which is used to record audio ### Response: def _create_file(): """ Returns a file handle which is used to record audio """ f = wave.open('audio.wav', mode='wb') f.setnchannels(2) p = pyaudio.PyAudio() ...
def compute_payments(self, precision=None): ''' Returns the total amount of payments made to this invoice. @param precision:int Number of decimal places @return: Decimal ''' return quantize(sum([payment.amount for payment in self.__payments]), prec...
Returns the total amount of payments made to this invoice. @param precision:int Number of decimal places @return: Decimal
Below is the the instruction that describes the task: ### Input: Returns the total amount of payments made to this invoice. @param precision:int Number of decimal places @return: Decimal ### Response: def compute_payments(self, precision=None): ''' Returns the total amount of paymen...
def write_smet(filename, data, metadata, nodata_value=-999, mode='h', check_nan=True): """writes smet files Parameters ---- filename : filename/loction of output data : data to write as pandas df metadata: header to write input as dict nodata_value: Nodata Value to write/use ...
writes smet files Parameters ---- filename : filename/loction of output data : data to write as pandas df metadata: header to write input as dict nodata_value: Nodata Value to write/use mode: defines if to write daily ("d") or continuos data (default 'h') check_nan...
Below is the the instruction that describes the task: ### Input: writes smet files Parameters ---- filename : filename/loction of output data : data to write as pandas df metadata: header to write input as dict nodata_value: Nodata Value to write/use mode: defines ...
def remove_colormap(self, removal_type): """Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_* """ with _LeptonicaErrorTrap(): return Pix( lept.pixRemoveColormapGeneral(self._cdata, ...
Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_*
Below is the the instruction that describes the task: ### Input: Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_* ### Response: def remove_colormap(self, removal_type): """Remove a palette (colormap); if no colormap, ret...
def get_aws_s3_handle(config_map): """Convenience function for getting AWS S3 objects Added by cjshaw@mit.edu, Jan 9, 2015 Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and added support for Configuration May 25, 2017: Switch to boto3 """ url = 'https://' + config_map['s3_b...
Convenience function for getting AWS S3 objects Added by cjshaw@mit.edu, Jan 9, 2015 Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and added support for Configuration May 25, 2017: Switch to boto3
Below is the the instruction that describes the task: ### Input: Convenience function for getting AWS S3 objects Added by cjshaw@mit.edu, Jan 9, 2015 Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and added support for Configuration May 25, 2017: Switch to boto3 ### Response: def ge...
def process_insert_get_id(self, query, sql, values, sequence=None): """ Process an "insert get ID" query. :param query: A QueryBuilder instance :type query: QueryBuilder :param sql: The sql query to execute :type sql: str :param values: The value bindings ...
Process an "insert get ID" query. :param query: A QueryBuilder instance :type query: QueryBuilder :param sql: The sql query to execute :type sql: str :param values: The value bindings :type values: list :param sequence: The ids sequence :type sequence:...
Below is the the instruction that describes the task: ### Input: Process an "insert get ID" query. :param query: A QueryBuilder instance :type query: QueryBuilder :param sql: The sql query to execute :type sql: str :param values: The value bindings :type values: li...
def diff_prettyHtml(self, diffs): """Convert a diff array into a pretty HTML report. Args: diffs: Array of diff tuples. Returns: HTML representation. """ html = [] for (op, data) in diffs: text = (data.replace("&", "&amp;").replace("<", "&lt;") .replace(">", ...
Convert a diff array into a pretty HTML report. Args: diffs: Array of diff tuples. Returns: HTML representation.
Below is the the instruction that describes the task: ### Input: Convert a diff array into a pretty HTML report. Args: diffs: Array of diff tuples. Returns: HTML representation. ### Response: def diff_prettyHtml(self, diffs): """Convert a diff array into a pretty HTML report. Args: ...
def get_config(context): """ Return the formatted javascript for any disqus config variables. """ conf_vars = ['disqus_developer', 'disqus_identifier', 'disqus_url', 'disqus_title', 'disqus_category_id' ] js = '\t...
Return the formatted javascript for any disqus config variables.
Below is the the instruction that describes the task: ### Input: Return the formatted javascript for any disqus config variables. ### Response: def get_config(context): """ Return the formatted javascript for any disqus config variables. """ conf_vars = ['disqus_developer', 'disqu...
def point_rotate(pt, ax, theta): """ Rotate a 3-D point around a 3-D axis through the origin. Handedness is a counter-clockwise rotation when viewing the rotation axis as pointing at the observer. Thus, in a right-handed x-y-z frame, a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point...
Rotate a 3-D point around a 3-D axis through the origin. Handedness is a counter-clockwise rotation when viewing the rotation axis as pointing at the observer. Thus, in a right-handed x-y-z frame, a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point at (0,1,0). .. todo:: Complete ...
Below is the the instruction that describes the task: ### Input: Rotate a 3-D point around a 3-D axis through the origin. Handedness is a counter-clockwise rotation when viewing the rotation axis as pointing at the observer. Thus, in a right-handed x-y-z frame, a 90deg rotation of (1,0,0) around the z...
def _request_devices(self, url, _type): """Request list of devices.""" res = self._request(url) return res.get(_type) if res else {}
Request list of devices.
Below is the the instruction that describes the task: ### Input: Request list of devices. ### Response: def _request_devices(self, url, _type): """Request list of devices.""" res = self._request(url) return res.get(_type) if res else {}
def set_spectator_mode(self, mode=True): """ When the flow is in spectator_mode, we have to disable signals, pickle dump and possible callbacks A spectator can still operate on the flow but the new status of the flow won't be saved in the pickle file. Usually the flow is in spectator mod...
When the flow is in spectator_mode, we have to disable signals, pickle dump and possible callbacks A spectator can still operate on the flow but the new status of the flow won't be saved in the pickle file. Usually the flow is in spectator mode when we are already running it via the scheduler or...
Below is the the instruction that describes the task: ### Input: When the flow is in spectator_mode, we have to disable signals, pickle dump and possible callbacks A spectator can still operate on the flow but the new status of the flow won't be saved in the pickle file. Usually the flow is in spect...
def save(self): """Save the changes to the instance and any related objects.""" # first call save with commit=False for all Forms for form in self._forms: if isinstance(form, BaseForm): form.save(commit=False) # call save on the instance self.instanc...
Save the changes to the instance and any related objects.
Below is the the instruction that describes the task: ### Input: Save the changes to the instance and any related objects. ### Response: def save(self): """Save the changes to the instance and any related objects.""" # first call save with commit=False for all Forms for form in self._forms...
def sort_func(self, key): """Logic for sorting keys in a `Spectrum` relative to one another.""" if key == self._KEYS.TIME: return 'aaa' if key == self._KEYS.DATA: return 'zzy' if key == self._KEYS.SOURCE: return 'zzz' return key
Logic for sorting keys in a `Spectrum` relative to one another.
Below is the the instruction that describes the task: ### Input: Logic for sorting keys in a `Spectrum` relative to one another. ### Response: def sort_func(self, key): """Logic for sorting keys in a `Spectrum` relative to one another.""" if key == self._KEYS.TIME: return 'aaa' ...
def mask_cmp_op(x, y, op, allowed_types): """ Apply the function `op` to only non-null points in x and y. Parameters ---------- x : array-like y : array-like op : binary operation allowed_types : class or tuple of classes Returns ------- result : ndarray[bool] """ #...
Apply the function `op` to only non-null points in x and y. Parameters ---------- x : array-like y : array-like op : binary operation allowed_types : class or tuple of classes Returns ------- result : ndarray[bool]
Below is the the instruction that describes the task: ### Input: Apply the function `op` to only non-null points in x and y. Parameters ---------- x : array-like y : array-like op : binary operation allowed_types : class or tuple of classes Returns ------- result : ndarray[bool...
def north_arrow_path(feature, parent): """Retrieve the full path of default north arrow logo.""" _ = feature, parent # NOQA north_arrow_file = setting(inasafe_north_arrow_path['setting_key']) if os.path.exists(north_arrow_file): return north_arrow_file else: LOGGER.info( ...
Retrieve the full path of default north arrow logo.
Below is the the instruction that describes the task: ### Input: Retrieve the full path of default north arrow logo. ### Response: def north_arrow_path(feature, parent): """Retrieve the full path of default north arrow logo.""" _ = feature, parent # NOQA north_arrow_file = setting(inasafe_north_arrow...
def select_dtypes(self, include=None, exclude=None): """ Return a subset of the DataFrame's columns based on the column dtypes. Parameters ---------- include, exclude : scalar or list-like A selection of dtypes or strings to be included/excluded. At least ...
Return a subset of the DataFrame's columns based on the column dtypes. Parameters ---------- include, exclude : scalar or list-like A selection of dtypes or strings to be included/excluded. At least one of these parameters must be supplied. Returns -----...
Below is the the instruction that describes the task: ### Input: Return a subset of the DataFrame's columns based on the column dtypes. Parameters ---------- include, exclude : scalar or list-like A selection of dtypes or strings to be included/excluded. At least one...
def _parse(root): """Recursively convert an Element into python data types""" if root.tag == "nil-classes": return [] elif root.get("type") == "array": return [_parse(child) for child in root] d = {} for child in root: type = child.get("type") or "string" if child.g...
Recursively convert an Element into python data types
Below is the the instruction that describes the task: ### Input: Recursively convert an Element into python data types ### Response: def _parse(root): """Recursively convert an Element into python data types""" if root.tag == "nil-classes": return [] elif root.get("type") == "array": re...
def _get_parser_call_method(self, parser_to_method): """Return the parser special method 'call' that handles sub-command calling. Args: parser_to_method: mapping of the parser registered name to the method it is linked to """ def inner_call(args=None,...
Return the parser special method 'call' that handles sub-command calling. Args: parser_to_method: mapping of the parser registered name to the method it is linked to
Below is the the instruction that describes the task: ### Input: Return the parser special method 'call' that handles sub-command calling. Args: parser_to_method: mapping of the parser registered name to the method it is linked to ### Response: def _get_parser_call_meth...
def describe_root(record, root, indent=0, suppress_values=False): """ Args: record (Evtx.Record): indent (int): """ def format_node(n, extra=None, indent=0): """ Depends on closure over `record` and `suppress_values`. Args: n (Evtx.Nodes.BXmlNode): ...
Args: record (Evtx.Record): indent (int):
Below is the the instruction that describes the task: ### Input: Args: record (Evtx.Record): indent (int): ### Response: def describe_root(record, root, indent=0, suppress_values=False): """ Args: record (Evtx.Record): indent (int): """ def format_node(n, extra=None, indent=...
def remove_member_from(self, leaderboard_name, member): ''' Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. ''' pipeline = self.redis_connection.pip...
Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name.
Below is the the instruction that describes the task: ### Input: Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. ### Response: def remove_member_from(self, leaderboard_name, m...
def get_region(): """Use the environment to get the current region""" global _REGION if _REGION is None: region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1" region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")} if region_name not in region_dict: r...
Use the environment to get the current region
Below is the the instruction that describes the task: ### Input: Use the environment to get the current region ### Response: def get_region(): """Use the environment to get the current region""" global _REGION if _REGION is None: region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1" ...
def parse(self, method, endpoint, body): ''' calls parse on list or detail ''' if isinstance(body, dict): # request body was already parsed return body if endpoint == 'list': return self.parse_list(body) return self.parse_detail(body)
calls parse on list or detail
Below is the the instruction that describes the task: ### Input: calls parse on list or detail ### Response: def parse(self, method, endpoint, body): ''' calls parse on list or detail ''' if isinstance(body, dict): # request body was already parsed return body if endpoint == 'l...
def infile_path(self) -> Optional[PurePath]: """ Read-only property. :return: A ``pathlib.PurePath`` object or ``None``. """ if not self.__infile_path: return Path(self.__infile_path).expanduser() return None
Read-only property. :return: A ``pathlib.PurePath`` object or ``None``.
Below is the the instruction that describes the task: ### Input: Read-only property. :return: A ``pathlib.PurePath`` object or ``None``. ### Response: def infile_path(self) -> Optional[PurePath]: """ Read-only property. :return: A ``pathlib.PurePath`` object or ``None``. "...
def when_value_edited(self, *args, **kargs): """ Overrided to prevent user from selecting too many instances """ if len(self.value) > self.instance_num: self.value.pop(-2) self.display()
Overrided to prevent user from selecting too many instances
Below is the the instruction that describes the task: ### Input: Overrided to prevent user from selecting too many instances ### Response: def when_value_edited(self, *args, **kargs): """ Overrided to prevent user from selecting too many instances """ if len(self.value) > self.instance_num: ...
def linefeed(self): """Perform an index and, if :data:`~pyte.modes.LNM` is set, a carriage return. """ self.index() if mo.LNM in self.mode: self.carriage_return()
Perform an index and, if :data:`~pyte.modes.LNM` is set, a carriage return.
Below is the the instruction that describes the task: ### Input: Perform an index and, if :data:`~pyte.modes.LNM` is set, a carriage return. ### Response: def linefeed(self): """Perform an index and, if :data:`~pyte.modes.LNM` is set, a carriage return. """ self.index() ...
def receive_nak_requesting(self, pkt): """Receive NAK in REQUESTING state.""" logger.debug("C3.1. Received NAK?, in REQUESTING state.") if self.process_received_nak(pkt): logger.debug("C3.1: T. Received NAK, in REQUESTING state, " "raise INIT.") r...
Receive NAK in REQUESTING state.
Below is the the instruction that describes the task: ### Input: Receive NAK in REQUESTING state. ### Response: def receive_nak_requesting(self, pkt): """Receive NAK in REQUESTING state.""" logger.debug("C3.1. Received NAK?, in REQUESTING state.") if self.process_received_nak(pkt): ...
def clear_all(tgt=None, tgt_type='glob'): ''' .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Clear the cached pillar, grains, and mine data of the targeted minions CLI Example: .. code-block:: bash...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Clear the cached pillar, grains, and mine data of the targeted minions CLI Example: .. code-block:: bash salt-run cache.clear_all
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``. Clear the cached pillar, grains, and mine data of the targeted minions CLI Example: .. co...
def load_graphml(filename, folder=None, node_type=int): """ Load a GraphML file from disk and convert the node/edge attributes to correct data types. Parameters ---------- filename : string the name of the graphml file (including file extension) folder : string the folder co...
Load a GraphML file from disk and convert the node/edge attributes to correct data types. Parameters ---------- filename : string the name of the graphml file (including file extension) folder : string the folder containing the file, if None, use default data folder node_type : ...
Below is the the instruction that describes the task: ### Input: Load a GraphML file from disk and convert the node/edge attributes to correct data types. Parameters ---------- filename : string the name of the graphml file (including file extension) folder : string the folder c...
def _resizeColumnToContents(self, header, data, col, limit_ms): """Resize a column by its contents.""" hdr_width = self._sizeHintForColumn(header, col, limit_ms) data_width = self._sizeHintForColumn(data, col, limit_ms) if data_width > hdr_width: width = min(self.max_wid...
Resize a column by its contents.
Below is the the instruction that describes the task: ### Input: Resize a column by its contents. ### Response: def _resizeColumnToContents(self, header, data, col, limit_ms): """Resize a column by its contents.""" hdr_width = self._sizeHintForColumn(header, col, limit_ms) data_width = s...
def file_path(self, request, response=None, info=None): """ 抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息 """ return json.dumps(self._extract_key_info(request))
抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息
Below is the the instruction that describes the task: ### Input: 抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息 ### Response: def file_path(self, request, response=None, info=None): """ 抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息 """ return jso...
def invoke(self, results): """ Handles invocation of the component. The default implementation invokes it with positional arguments based on order of dependency declaration. """ args = [results.get(d) for d in self.deps] return self.component(*args)
Handles invocation of the component. The default implementation invokes it with positional arguments based on order of dependency declaration.
Below is the the instruction that describes the task: ### Input: Handles invocation of the component. The default implementation invokes it with positional arguments based on order of dependency declaration. ### Response: def invoke(self, results): """ Handles invocation of the component. T...
def get_device_model(self, cat, sub_cat, key=''): """Return the model name given cat/subcat or product key""" if cat + ':' + sub_cat in self.device_models: return self.device_models[cat + ':' + sub_cat] else: for i_key, i_val in self.device_models.items(): ...
Return the model name given cat/subcat or product key
Below is the the instruction that describes the task: ### Input: Return the model name given cat/subcat or product key ### Response: def get_device_model(self, cat, sub_cat, key=''): """Return the model name given cat/subcat or product key""" if cat + ':' + sub_cat in self.device_models: ...
def chi_eff(self): """Returns the effective spin.""" return conversions.chi_eff(self.mass1, self.mass2, self.spin1z, self.spin2z)
Returns the effective spin.
Below is the the instruction that describes the task: ### Input: Returns the effective spin. ### Response: def chi_eff(self): """Returns the effective spin.""" return conversions.chi_eff(self.mass1, self.mass2, self.spin1z, self.spin2z)
def get(self, name): """ Returns the struct, enum, or interface with the given name, or raises RpcException if no elements match that name. :Parameters: name Name of struct/enum/interface to return """ if self.structs.has_key(name): retu...
Returns the struct, enum, or interface with the given name, or raises RpcException if no elements match that name. :Parameters: name Name of struct/enum/interface to return
Below is the the instruction that describes the task: ### Input: Returns the struct, enum, or interface with the given name, or raises RpcException if no elements match that name. :Parameters: name Name of struct/enum/interface to return ### Response: def get(self, name): ...
def AddShapePointObjectUnsorted(self, shapepoint, problems): """Insert a point into a correct position by sequence. """ if (len(self.sequence) == 0 or shapepoint.shape_pt_sequence >= self.sequence[-1]): index = len(self.sequence) elif shapepoint.shape_pt_sequence <= self.sequence[0]: ind...
Insert a point into a correct position by sequence.
Below is the the instruction that describes the task: ### Input: Insert a point into a correct position by sequence. ### Response: def AddShapePointObjectUnsorted(self, shapepoint, problems): """Insert a point into a correct position by sequence. """ if (len(self.sequence) == 0 or shapepoint.shape_...
def hgetall(key, host=None, port=None, db=None, password=None): ''' Get all fields and values from a redis hash, returns dict CLI Example: .. code-block:: bash salt '*' redis.hgetall foo_hash ''' server = _connect(host, port, db, password) return server.hgetall(key)
Get all fields and values from a redis hash, returns dict CLI Example: .. code-block:: bash salt '*' redis.hgetall foo_hash
Below is the the instruction that describes the task: ### Input: Get all fields and values from a redis hash, returns dict CLI Example: .. code-block:: bash salt '*' redis.hgetall foo_hash ### Response: def hgetall(key, host=None, port=None, db=None, password=None): ''' Get all fields an...
def connection_delay(self): """ Return the number of milliseconds to wait, based on the connection state, before attempting to send data. When disconnected, this respects the reconnect backoff time. When connecting, returns 0 to allow non-blocking connect to finish. When connecte...
Return the number of milliseconds to wait, based on the connection state, before attempting to send data. When disconnected, this respects the reconnect backoff time. When connecting, returns 0 to allow non-blocking connect to finish. When connected, returns a very large number to handle...
Below is the the instruction that describes the task: ### Input: Return the number of milliseconds to wait, based on the connection state, before attempting to send data. When disconnected, this respects the reconnect backoff time. When connecting, returns 0 to allow non-blocking connect to ...
def merge_dicts(*dicts, **copy_check): ''' Combines dictionaries into a single dictionary. If the 'copy' keyword is passed then the first dictionary is copied before update. merge_dicts({'a': 1, 'c': 1}, {'a': 2, 'b': 1}) # => {'a': 2, 'b': 1, 'c': 1} ''' merged = {} if not dic...
Combines dictionaries into a single dictionary. If the 'copy' keyword is passed then the first dictionary is copied before update. merge_dicts({'a': 1, 'c': 1}, {'a': 2, 'b': 1}) # => {'a': 2, 'b': 1, 'c': 1}
Below is the the instruction that describes the task: ### Input: Combines dictionaries into a single dictionary. If the 'copy' keyword is passed then the first dictionary is copied before update. merge_dicts({'a': 1, 'c': 1}, {'a': 2, 'b': 1}) # => {'a': 2, 'b': 1, 'c': 1} ### Response: def merge_...
def replace(self, photo_file, **kwds): """ Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace this photo. """ result = self._client.photo.replace(self, photo_file, **kwds) self._replace_fields(result.get_fields())
Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace this photo.
Below is the the instruction that describes the task: ### Input: Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace this photo. ### Response: def replace(self, photo_file, **kwds): """ Endpoint: /photo/<id>/replace.json Uploads the specified photo file ...
def _recurse_config_to_dict(t_data): ''' helper function to recurse through a vim object and attempt to return all child objects ''' if not isinstance(t_data, type(None)): if isinstance(t_data, list): t_list = [] for i in t_data: t_list.append(_recurse_con...
helper function to recurse through a vim object and attempt to return all child objects
Below is the the instruction that describes the task: ### Input: helper function to recurse through a vim object and attempt to return all child objects ### Response: def _recurse_config_to_dict(t_data): ''' helper function to recurse through a vim object and attempt to return all child objects ''' ...
def get_signing_key(self, key_type="", owner="", kid=None, **kwargs): """ Shortcut to use for signing keys only. :param key_type: Type of key (rsa, ec, oct, ..) :param owner: Who is the owner of the keys, "" == me (default) :param kid: A Key Identifier :param kwargs: Ext...
Shortcut to use for signing keys only. :param key_type: Type of key (rsa, ec, oct, ..) :param owner: Who is the owner of the keys, "" == me (default) :param kid: A Key Identifier :param kwargs: Extra key word arguments :return: A possibly empty list of keys
Below is the the instruction that describes the task: ### Input: Shortcut to use for signing keys only. :param key_type: Type of key (rsa, ec, oct, ..) :param owner: Who is the owner of the keys, "" == me (default) :param kid: A Key Identifier :param kwargs: Extra key word arguments...
def _outfp_write_with_check(self, outfp, data, enable_overwrite_check=True): # type: (BinaryIO, bytes, bool) -> None ''' Internal method to write data out to the output file descriptor, ensuring that it doesn't go beyond the bounds of the ISO. Parameters: outfp - The fi...
Internal method to write data out to the output file descriptor, ensuring that it doesn't go beyond the bounds of the ISO. Parameters: outfp - The file object to write to. data - The actual data to write. enable_overwrite_check - Whether to do overwrite checking if it is enab...
Below is the the instruction that describes the task: ### Input: Internal method to write data out to the output file descriptor, ensuring that it doesn't go beyond the bounds of the ISO. Parameters: outfp - The file object to write to. data - The actual data to write. en...
def add_activation_summary(x, types=None, name=None, collections=None): """ Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope. This function is a no-op if not calling from main training tower. Args: x (tf.Tensor): the tensor to summary. types (list[str]): su...
Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope. This function is a no-op if not calling from main training tower. Args: x (tf.Tensor): the tensor to summary. types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``. name (str): i...
Below is the the instruction that describes the task: ### Input: Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope. This function is a no-op if not calling from main training tower. Args: x (tf.Tensor): the tensor to summary. types (list[str]): summary types, de...
def switch_axis_limits(ax, which_axis): ''' Switch the axis limits of either x or y. Or both! ''' for a in which_axis: assert a in ('x', 'y') ax_limits = ax.axis() if a == 'x': ax.set_xlim(ax_limits[1], ax_limits[0]) else: ax.set_ylim(ax_limits[3],...
Switch the axis limits of either x or y. Or both!
Below is the the instruction that describes the task: ### Input: Switch the axis limits of either x or y. Or both! ### Response: def switch_axis_limits(ax, which_axis): ''' Switch the axis limits of either x or y. Or both! ''' for a in which_axis: assert a in ('x', 'y') ax_limits = ...
def remove_all_network_profiles(self, obj): """Remove all the AP profiles.""" profile_name_list = self.network_profile_name_list(obj) for profile_name in profile_name_list: self._logger.debug("delete profile: %s", profile_name) str_buf = create_unicode_buffer(profile_na...
Remove all the AP profiles.
Below is the the instruction that describes the task: ### Input: Remove all the AP profiles. ### Response: def remove_all_network_profiles(self, obj): """Remove all the AP profiles.""" profile_name_list = self.network_profile_name_list(obj) for profile_name in profile_name_list: ...
def handle_exception(self, exc_info=None, state=None, tags=None, return_feedback_urls=False, dry_run=False): """ Call this method from within a try/except clause to generate a call to Stack Sentinel. :param exc_info: Return value of sys.exc_info(). If you pass None, han...
Call this method from within a try/except clause to generate a call to Stack Sentinel. :param exc_info: Return value of sys.exc_info(). If you pass None, handle_exception will call sys.exc_info() itself :param state: Dictionary of state information associated with the error. This could be form data, co...
Below is the the instruction that describes the task: ### Input: Call this method from within a try/except clause to generate a call to Stack Sentinel. :param exc_info: Return value of sys.exc_info(). If you pass None, handle_exception will call sys.exc_info() itself :param state: Dictionary of sta...
def tokenize_math(text): r"""Prevents math from being tokenized. :param Buffer text: iterator over line, with current position >>> b = Buffer(r'$\min_x$ \command') >>> tokenize_math(b) '$' >>> b = Buffer(r'$$\min_x$$ \command') >>> tokenize_math(b) '$$' """ if text.startswith('...
r"""Prevents math from being tokenized. :param Buffer text: iterator over line, with current position >>> b = Buffer(r'$\min_x$ \command') >>> tokenize_math(b) '$' >>> b = Buffer(r'$$\min_x$$ \command') >>> tokenize_math(b) '$$'
Below is the the instruction that describes the task: ### Input: r"""Prevents math from being tokenized. :param Buffer text: iterator over line, with current position >>> b = Buffer(r'$\min_x$ \command') >>> tokenize_math(b) '$' >>> b = Buffer(r'$$\min_x$$ \command') >>> tokenize_math(b) ...
def parseFullScan(self, i, modifications=False): """ parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml """ scanObj = PeptideObject() peptide = str(i[1]) pid=i[2] scanObj.acc = self.protein_map.get(i...
parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml
Below is the the instruction that describes the task: ### Input: parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml ### Response: def parseFullScan(self, i, modifications=False): """ parses scan info for giving a Spectrum Obj for plot...
def valueFromString(self, value, context=None): """ Converts the inputted string text to a value that matches the type from this column type. :param value | <str> """ if value in ('today', 'now'): return datetime.date.utcnow() try: r...
Converts the inputted string text to a value that matches the type from this column type. :param value | <str>
Below is the the instruction that describes the task: ### Input: Converts the inputted string text to a value that matches the type from this column type. :param value | <str> ### Response: def valueFromString(self, value, context=None): """ Converts the inputted string text t...
def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs): '''Outputs to a stream (like a file or request)''' if formatted: to.write(self.start_tag) to.write('\n') if not self.tag_self_closes: for blok in self.blox: ...
Outputs to a stream (like a file or request)
Below is the the instruction that describes the task: ### Input: Outputs to a stream (like a file or request) ### Response: def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs): '''Outputs to a stream (like a file or request)''' if formatted: to.write(...
def update_listener(self, lbaas_listener, body=None): """Updates a lbaas_listener.""" return self.put(self.lbaas_listener_path % (lbaas_listener), body=body)
Updates a lbaas_listener.
Below is the the instruction that describes the task: ### Input: Updates a lbaas_listener. ### Response: def update_listener(self, lbaas_listener, body=None): """Updates a lbaas_listener.""" return self.put(self.lbaas_listener_path % (lbaas_listener), body=body)
def directions(self, features, profile='mapbox/driving', alternatives=None, geometries=None, overview=None, steps=None, continue_straight=None, waypoint_snapping=None, annotations=None, language=None, **kwargs): """Request directions for waypoints encoded...
Request directions for waypoints encoded as GeoJSON features. Parameters ---------- features : iterable An collection of GeoJSON features profile : str Name of a Mapbox profile such as 'mapbox.driving' alternatives : bool Whether to try to ret...
Below is the the instruction that describes the task: ### Input: Request directions for waypoints encoded as GeoJSON features. Parameters ---------- features : iterable An collection of GeoJSON features profile : str Name of a Mapbox profile such as 'mapbox.d...
def from_json(cls, data, result=None): """ Create new Way element from JSON data :param data: Element data from JSON :type data: Dict :param result: The result this element belongs to :type result: overpy.Result :return: New instance of Way :rtype: overpy...
Create new Way element from JSON data :param data: Element data from JSON :type data: Dict :param result: The result this element belongs to :type result: overpy.Result :return: New instance of Way :rtype: overpy.Way :raises overpy.exception.ElementDataWrongType:...
Below is the the instruction that describes the task: ### Input: Create new Way element from JSON data :param data: Element data from JSON :type data: Dict :param result: The result this element belongs to :type result: overpy.Result :return: New instance of Way :rty...
def _from_dict(cls, _dict): """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" args = {} if 'consumption_preference_category_id' in _dict: args['consumption_preference_category_id'] = _dict.get( 'consumption_preference_category_id') ...
Initialize a ConsumptionPreferencesCategory object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a ConsumptionPreferencesCategory object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" args = {} if 'consumption_pr...
def load_from_path(path, filetype=None, has_filetype=True): """ load file content from a file specified as dot-separated The file is located according to logic in normalize_path, and the contents are returned. (See Note 1) Parameters: (see normalize_path) path - dot-sep...
load file content from a file specified as dot-separated The file is located according to logic in normalize_path, and the contents are returned. (See Note 1) Parameters: (see normalize_path) path - dot-separated path filetype - optional filetype ...
Below is the the instruction that describes the task: ### Input: load file content from a file specified as dot-separated The file is located according to logic in normalize_path, and the contents are returned. (See Note 1) Parameters: (see normalize_path) path - dot-se...
def get_ISSNs(self): """ Get list of VALID ISSNs (``022a``). Returns: list: List with *valid* ISSN strings. """ invalid_issns = set(self.get_invalid_ISSNs()) return [ self._clean_isbn(issn) for issn in self["022a"] if self...
Get list of VALID ISSNs (``022a``). Returns: list: List with *valid* ISSN strings.
Below is the the instruction that describes the task: ### Input: Get list of VALID ISSNs (``022a``). Returns: list: List with *valid* ISSN strings. ### Response: def get_ISSNs(self): """ Get list of VALID ISSNs (``022a``). Returns: list: List with *valid* I...
def _set_fcoe(self, v, load=False): """ Setter method for fcoe, mapped from YANG variable /interface/fcoe (list) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe is considered as a private method. Backends looking to populate this variable should do so via ca...
Setter method for fcoe, mapped from YANG variable /interface/fcoe (list) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_fcoe() directly. YANG De...
Below is the the instruction that describes the task: ### Input: Setter method for fcoe, mapped from YANG variable /interface/fcoe (list) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe is considered as a private method. Backends looking to populate this variable sh...
def get_build_logs_zip(self, project, build_id, **kwargs): """GetBuildLogsZip. Gets the logs for a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :rtype: object """ route_values = {} if project is not None: ...
GetBuildLogsZip. Gets the logs for a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :rtype: object
Below is the the instruction that describes the task: ### Input: GetBuildLogsZip. Gets the logs for a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :rtype: object ### Response: def get_build_logs_zip(self, project, build_id, **kwargs...
def avatar(self, blogname, size=64): """ Retrieves the url of the blog's avatar :param blogname: a string, the blog you want the avatar for :returns: A dict created from the JSON response """ url = "/v2/blog/{}/avatar/{}".format(blogname, size) return self.send_...
Retrieves the url of the blog's avatar :param blogname: a string, the blog you want the avatar for :returns: A dict created from the JSON response
Below is the the instruction that describes the task: ### Input: Retrieves the url of the blog's avatar :param blogname: a string, the blog you want the avatar for :returns: A dict created from the JSON response ### Response: def avatar(self, blogname, size=64): """ Retrieves the ...
def plot_calibration_purchases_vs_holdout_purchases( model, calibration_holdout_matrix, kind="frequency_cal", n=7, **kwargs ): """ Plot calibration purchases vs holdout. This currently relies too much on the lifetimes.util calibration_and_holdout_data function. Parameters ---------- model:...
Plot calibration purchases vs holdout. This currently relies too much on the lifetimes.util calibration_and_holdout_data function. Parameters ---------- model: lifetimes model A fitted lifetimes model. calibration_holdout_matrix: pandas DataFrame DataFrame from calibration_and_hold...
Below is the the instruction that describes the task: ### Input: Plot calibration purchases vs holdout. This currently relies too much on the lifetimes.util calibration_and_holdout_data function. Parameters ---------- model: lifetimes model A fitted lifetimes model. calibration_holdout...
def _is_admin(user_id): """ Is the specified user an admin """ user = get_session().query(User).filter(User.id==user_id).one() if user.is_admin(): return True else: return False
Is the specified user an admin
Below is the the instruction that describes the task: ### Input: Is the specified user an admin ### Response: def _is_admin(user_id): """ Is the specified user an admin """ user = get_session().query(User).filter(User.id==user_id).one() if user.is_admin(): return True else: ...
def FlagsIntoString(self): """Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/...
Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/p/google-gflags Returns: ...
Below is the the instruction that describes the task: ### Input: Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoStri...
async def dispatch(self, *args, **kwargs): ''' This method handles the actual request to the resource. It performs all the neccesary checks and then executes the relevant member method which is mapped to the method name. Handles authentication and de-serialization before calling the requ...
This method handles the actual request to the resource. It performs all the neccesary checks and then executes the relevant member method which is mapped to the method name. Handles authentication and de-serialization before calling the required method. Handles the serialization of the response
Below is the the instruction that describes the task: ### Input: This method handles the actual request to the resource. It performs all the neccesary checks and then executes the relevant member method which is mapped to the method name. Handles authentication and de-serialization before calling th...
def _get_trailing_whitespace(marker, s): """Return the whitespace content trailing the given 'marker' in string 's', up to and including a newline. """ suffix = '' start = s.index(marker) + len(marker) i = start while i < len(s): if s[i] in ' \t': suffix += s[i] e...
Return the whitespace content trailing the given 'marker' in string 's', up to and including a newline.
Below is the the instruction that describes the task: ### Input: Return the whitespace content trailing the given 'marker' in string 's', up to and including a newline. ### Response: def _get_trailing_whitespace(marker, s): """Return the whitespace content trailing the given 'marker' in string 's', up ...
def set_itunes_element(self): """Set each of the itunes elements.""" self.set_itunes_author_name() self.set_itunes_block() self.set_itunes_closed_captioned() self.set_itunes_duration() self.set_itunes_explicit() self.set_itune_image() self.set_itunes_order...
Set each of the itunes elements.
Below is the the instruction that describes the task: ### Input: Set each of the itunes elements. ### Response: def set_itunes_element(self): """Set each of the itunes elements.""" self.set_itunes_author_name() self.set_itunes_block() self.set_itunes_closed_captioned() self....
def select_postponed_date(self): """ The time intervals at which the workflow is to be extended are determined. .. code-block:: python # request: { 'task_inv_key': string, } """ _form = forms.Jso...
The time intervals at which the workflow is to be extended are determined. .. code-block:: python # request: { 'task_inv_key': string, }
Below is the the instruction that describes the task: ### Input: The time intervals at which the workflow is to be extended are determined. .. code-block:: python # request: { 'task_inv_key': string, } ### Response: def select_p...
def powerUp(self, powerup, interface=None, priority=0): """ Installs a powerup (e.g. plugin) on an item or store. Powerups will be returned in an iterator when queried for using the 'powerupsFor' method. Normally they will be returned in order of installation [this may change i...
Installs a powerup (e.g. plugin) on an item or store. Powerups will be returned in an iterator when queried for using the 'powerupsFor' method. Normally they will be returned in order of installation [this may change in future versions, so please don't depend on it]. Higher priorities...
Below is the the instruction that describes the task: ### Input: Installs a powerup (e.g. plugin) on an item or store. Powerups will be returned in an iterator when queried for using the 'powerupsFor' method. Normally they will be returned in order of installation [this may change in futur...
def start_gen(port, ser='msgpack', version='2.2', detector='AGIPD', raw=False, nsources=1, datagen='random', *, debug=True): """"Karabo bridge server simulation. Simulate a Karabo Bridge server and send random data from a detector, either AGIPD or LPD. Parameters ------...
Karabo bridge server simulation. Simulate a Karabo Bridge server and send random data from a detector, either AGIPD or LPD. Parameters ---------- port: str The port to on which the server is bound. ser: str, optional The serialization algorithm, default is msgpack. version:...
Below is the the instruction that describes the task: ### Input: Karabo bridge server simulation. Simulate a Karabo Bridge server and send random data from a detector, either AGIPD or LPD. Parameters ---------- port: str The port to on which the server is bound. ser: str, optional ...
def rank(self): """ Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers()) """ rank = ctypes.c_int() check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank))) retur...
Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers())
Below is the the instruction that describes the task: ### Input: Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers()) ### Response: def rank(self): """ Returns the rank of this worker node. ...
def state_args(id_, state, high): ''' Return a set of the arguments passed to the named state ''' args = set() if id_ not in high: return args if state not in high[id_]: return args for item in high[id_][state]: if not isinstance(item, dict): continue ...
Return a set of the arguments passed to the named state
Below is the the instruction that describes the task: ### Input: Return a set of the arguments passed to the named state ### Response: def state_args(id_, state, high): ''' Return a set of the arguments passed to the named state ''' args = set() if id_ not in high: return args if st...
def edit_config_input_target_config_target_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") edit_config = ET.Element("edit_config") config = edit_config input = ET.SubElement(edit_config, "input") target = ET.SubElement...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def edit_config_input_target_config_target_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") edit_config = ET.Element("edit_config") ...
def initialize_state(self): """ Call this to initialize the state of the UI after everything has been connected. """ if self.__hardware_source: self.__data_item_states_changed_event_listener = self.__hardware_source.data_item_states_changed_event.listen(self.__data_item_states_changed) ...
Call this to initialize the state of the UI after everything has been connected.
Below is the the instruction that describes the task: ### Input: Call this to initialize the state of the UI after everything has been connected. ### Response: def initialize_state(self): """ Call this to initialize the state of the UI after everything has been connected. """ if self.__hardware_sou...
def weekday_to_str( weekday: Union[int, str], *, inverse: bool = False ) -> Union[int, str]: """ Given a weekday number (integer in the range 0, 1, ..., 6), return its corresponding weekday name as a lowercase string. Here 0 -> 'monday', 1 -> 'tuesday', and so on. If ``inverse``, then perform th...
Given a weekday number (integer in the range 0, 1, ..., 6), return its corresponding weekday name as a lowercase string. Here 0 -> 'monday', 1 -> 'tuesday', and so on. If ``inverse``, then perform the inverse operation.
Below is the the instruction that describes the task: ### Input: Given a weekday number (integer in the range 0, 1, ..., 6), return its corresponding weekday name as a lowercase string. Here 0 -> 'monday', 1 -> 'tuesday', and so on. If ``inverse``, then perform the inverse operation. ### Response: def ...
def selector_production(self, tokens): """Production for a full selector.""" validators = [] # the following productions should return predicate functions. if self.peek(tokens, 'type'): type_ = self.match(tokens, 'type') validators.append(self.type_production(ty...
Production for a full selector.
Below is the the instruction that describes the task: ### Input: Production for a full selector. ### Response: def selector_production(self, tokens): """Production for a full selector.""" validators = [] # the following productions should return predicate functions. if self.peek(t...
def write_file(filename, contents): """Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it. """ contents = "\n".join(contents) # assuming the contents has been vetted for utf-8 encoding contents = contents.encode("utf-8") with o...
Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it.
Below is the the instruction that describes the task: ### Input: Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it. ### Response: def write_file(filename, contents): """Create a file with the specified name and write 'contents' (a sequence...
def get_top_edge_depth(self): """ Return minimum depth of surface's top edge. :returns: Float value, the vertical distance between the earth surface and the shallowest point in surface's top edge in km. """ top_edge = self.mesh[0:1] if top_edge.de...
Return minimum depth of surface's top edge. :returns: Float value, the vertical distance between the earth surface and the shallowest point in surface's top edge in km.
Below is the the instruction that describes the task: ### Input: Return minimum depth of surface's top edge. :returns: Float value, the vertical distance between the earth surface and the shallowest point in surface's top edge in km. ### Response: def get_top_edge_depth(self): ...
def measure_all(self, *qubit_reg_pairs): """ Measures many qubits into their specified classical bits, in the order they were entered. If no qubit/register pairs are provided, measure all qubits present in the program into classical addresses of the same index. :param Tuple qubi...
Measures many qubits into their specified classical bits, in the order they were entered. If no qubit/register pairs are provided, measure all qubits present in the program into classical addresses of the same index. :param Tuple qubit_reg_pairs: Tuples of qubit indices paired with classical bi...
Below is the the instruction that describes the task: ### Input: Measures many qubits into their specified classical bits, in the order they were entered. If no qubit/register pairs are provided, measure all qubits present in the program into classical addresses of the same index. :param Tu...
async def update_template_context(self, context: dict) -> None: """Update the provided template context. This adds additional context from the various template context processors. Arguments: context: The context to update (mutate). """ processors = self.temp...
Update the provided template context. This adds additional context from the various template context processors. Arguments: context: The context to update (mutate).
Below is the the instruction that describes the task: ### Input: Update the provided template context. This adds additional context from the various template context processors. Arguments: context: The context to update (mutate). ### Response: async def update_template_context...
def getoptT(X, W, Y, Z, S, M_E, E, m0, rho): ''' Perform line search ''' iter_max = 20 norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2 f = np.zeros(iter_max + 1) f[0] = F_t(X, Y, S, M_E, E, m0, rho) t = -1e-1 for i in range(iter_max): f[i + ...
Perform line search
Below is the the instruction that describes the task: ### Input: Perform line search ### Response: def getoptT(X, W, Y, Z, S, M_E, E, m0, rho): ''' Perform line search ''' iter_max = 20 norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2 f = np.zeros(iter_max + 1) ...
def liftover(args): """ %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa LiftOver CODIS/Y-STR markers. """ p = OptionParser(liftover.__doc__) p.add_option("--checkvalid", default=False, action="store_true", help="Check minscore, period and length") opts, args = p.pars...
%prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa LiftOver CODIS/Y-STR markers.
Below is the the instruction that describes the task: ### Input: %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa LiftOver CODIS/Y-STR markers. ### Response: def liftover(args): """ %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa LiftOver CODIS/Y-STR markers. """ p = Option...
def actors(context): """Display a list of actors""" fritz = context.obj fritz.login() for actor in fritz.get_actors(): click.echo("{} ({} {}; AIN {} )".format( actor.name, actor.manufacturer, actor.productname, actor.actor_id, )) i...
Display a list of actors
Below is the the instruction that describes the task: ### Input: Display a list of actors ### Response: def actors(context): """Display a list of actors""" fritz = context.obj fritz.login() for actor in fritz.get_actors(): click.echo("{} ({} {}; AIN {} )".format( actor.name, ...
def insert_volume(self, metadata, attachments=[]): '''Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute ...
Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute "key2" : "value2", ... ...
Below is the the instruction that describes the task: ### Input: Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attr...
def add_left_child(self, n, parent, **attrs): ''' API: add_left_child(self, n, parent, **attrs) Description: Adds left child n to node parent. Pre: Left child of parent should not exist. Input: n: Node name. parent: Parent node name...
API: add_left_child(self, n, parent, **attrs) Description: Adds left child n to node parent. Pre: Left child of parent should not exist. Input: n: Node name. parent: Parent node name. attrs: Attributes of node n.
Below is the the instruction that describes the task: ### Input: API: add_left_child(self, n, parent, **attrs) Description: Adds left child n to node parent. Pre: Left child of parent should not exist. Input: n: Node name. parent: Parent node n...
def sum_of_gaussian_factory(N): """Return a model of the sum of N Gaussians and a constant background.""" name = "SumNGauss%d" % N attr = {} # parameters for i in range(N): key = "amplitude_%d" % i attr[key] = Parameter(key) key = "center_%d" % i attr[key] = Paramet...
Return a model of the sum of N Gaussians and a constant background.
Below is the the instruction that describes the task: ### Input: Return a model of the sum of N Gaussians and a constant background. ### Response: def sum_of_gaussian_factory(N): """Return a model of the sum of N Gaussians and a constant background.""" name = "SumNGauss%d" % N attr = {} # paramet...
def present(name, value, config=None): ''' Ensure that the named sysctl value is set in memory and persisted to the named configuration file. The default sysctl configuration file is /etc/sysctl.conf name The name of the sysctl value to edit value The sysctl value to apply ...
Ensure that the named sysctl value is set in memory and persisted to the named configuration file. The default sysctl configuration file is /etc/sysctl.conf name The name of the sysctl value to edit value The sysctl value to apply config The location of the sysctl configur...
Below is the the instruction that describes the task: ### Input: Ensure that the named sysctl value is set in memory and persisted to the named configuration file. The default sysctl configuration file is /etc/sysctl.conf name The name of the sysctl value to edit value The sysctl v...
def tagAttributes_while(fdef_master_list,root): '''Tag each node under root with the appropriate depth. ''' depth = 0 current = root untagged_nodes = [root] while untagged_nodes: current = untagged_nodes.pop() for x in fdef_master_list: if jsName(x.path,x.name) == current...
Tag each node under root with the appropriate depth.
Below is the the instruction that describes the task: ### Input: Tag each node under root with the appropriate depth. ### Response: def tagAttributes_while(fdef_master_list,root): '''Tag each node under root with the appropriate depth. ''' depth = 0 current = root untagged_nodes = [root] while ...
def kill(self, exit_code: Any = None): """ Stops the behaviour Args: exit_code (object, optional): the exit code of the behaviour (Default value = None) """ self._force_kill.set() if exit_code is not None: self._exit_code = exit_code logger...
Stops the behaviour Args: exit_code (object, optional): the exit code of the behaviour (Default value = None)
Below is the the instruction that describes the task: ### Input: Stops the behaviour Args: exit_code (object, optional): the exit code of the behaviour (Default value = None) ### Response: def kill(self, exit_code: Any = None): """ Stops the behaviour Args: exi...
def get_supported_binary_ops(): ''' Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol. ''' binary_ops = {} binary_ops[np.add.__name__] = '+' binary_ops[np.subtract.__name__] = '-' binary_ops[np.multiply.__name__] = '*' binary_ops[np.divide.__name_...
Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol.
Below is the the instruction that describes the task: ### Input: Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol. ### Response: def get_supported_binary_ops(): ''' Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol. ''' ...
def process_post_categories(self, bulk_mode, api_post, post_categories): """ Create or update Categories related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_post: the API data for the post :param post_categories: a mappin...
Create or update Categories related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_post: the API data for the post :param post_categories: a mapping of Categories keyed by post ID :return: None
Below is the the instruction that describes the task: ### Input: Create or update Categories related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_post: the API data for the post :param post_categories: a mapping of Categories keyed by...
def _extract_centerdistance(image, mask = slice(None), voxelspacing = None): """ Internal, single-image version of `centerdistance`. """ image = numpy.array(image, copy=False) if None == voxelspacing: voxelspacing = [1.] * image.ndim # get image center and an array holding ...
Internal, single-image version of `centerdistance`.
Below is the the instruction that describes the task: ### Input: Internal, single-image version of `centerdistance`. ### Response: def _extract_centerdistance(image, mask = slice(None), voxelspacing = None): """ Internal, single-image version of `centerdistance`. """ image = numpy.array(image, copy...
def create_scalar_summary(name, v): """ Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v. """ assert isinstance(name, six.string_types), type(name) v = float(v) s = tf.Summary() s.value.add(tag=...
Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v.
Below is the the instruction that describes the task: ### Input: Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v. ### Response: def create_scalar_summary(name, v): """ Args: name (str): v (flo...
def geotiff_tags(self): """Return consolidated metadata from GeoTIFF tags as dict.""" if not self.is_geotiff: return None tags = self.tags gkd = tags['GeoKeyDirectoryTag'].value if gkd[0] != 1: log.warning('GeoTIFF tags: invalid GeoKeyDirectoryTag') ...
Return consolidated metadata from GeoTIFF tags as dict.
Below is the the instruction that describes the task: ### Input: Return consolidated metadata from GeoTIFF tags as dict. ### Response: def geotiff_tags(self): """Return consolidated metadata from GeoTIFF tags as dict.""" if not self.is_geotiff: return None tags = self.tags ...
def clean_path_middleware(environ, start_response=None): '''Clean url from double slashes and redirect if needed.''' path = environ['PATH_INFO'] if path and '//' in path: url = re.sub("/+", '/', path) if not url.startswith('/'): url = '/%s' % url qs = environ['QUERY_STRIN...
Clean url from double slashes and redirect if needed.
Below is the the instruction that describes the task: ### Input: Clean url from double slashes and redirect if needed. ### Response: def clean_path_middleware(environ, start_response=None): '''Clean url from double slashes and redirect if needed.''' path = environ['PATH_INFO'] if path and '//' in path:...