code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def deleteObserver(self, observer): """Remove an observer.""" Observable.deleteObserver(self, observer) # If self.startOnDemand is True, the reader monitoring # thread is stopped when there are no more observers. if self.startOnDemand: if 0 == self.countObservers(): ...
Remove an observer.
Below is the the instruction that describes the task: ### Input: Remove an observer. ### Response: def deleteObserver(self, observer): """Remove an observer.""" Observable.deleteObserver(self, observer) # If self.startOnDemand is True, the reader monitoring # thread is stopped when ...
def s_res(self, components=None): """ Get resulting apparent power in kVA at line(s) and transformer(s). The apparent power at a line (or transformer) is determined from the maximum values of active power P and reactive power Q. .. math:: S = max(\sqrt{p_0^2 + q_0^...
Get resulting apparent power in kVA at line(s) and transformer(s). The apparent power at a line (or transformer) is determined from the maximum values of active power P and reactive power Q. .. math:: S = max(\sqrt{p_0^2 + q_0^2}, \sqrt{p_1^2 + q_1^2}) Parameters ...
Below is the the instruction that describes the task: ### Input: Get resulting apparent power in kVA at line(s) and transformer(s). The apparent power at a line (or transformer) is determined from the maximum values of active power P and reactive power Q. .. math:: S = max(\sq...
def _ready_gzip_fastq(in_files, data, require_bgzip=False): """Check if we have gzipped fastq and don't need format conversion or splitting. Avoid forcing bgzip if we don't need indexed files. """ all_gzipped = all([not x or x.endswith(".gz") for x in in_files]) if require_bgzip and all_gzipped: ...
Check if we have gzipped fastq and don't need format conversion or splitting. Avoid forcing bgzip if we don't need indexed files.
Below is the the instruction that describes the task: ### Input: Check if we have gzipped fastq and don't need format conversion or splitting. Avoid forcing bgzip if we don't need indexed files. ### Response: def _ready_gzip_fastq(in_files, data, require_bgzip=False): """Check if we have gzipped fastq and...
def sanity_check(self): "Check the underlying data in the training set can be properly loaded." final_message = "You can deactivate this warning by passing `no_check=True`." if not hasattr(self.train_ds, 'items') or len(self.train_ds.items) == 0 or not hasattr(self.train_dl, 'batch_sampler'): re...
Check the underlying data in the training set can be properly loaded.
Below is the the instruction that describes the task: ### Input: Check the underlying data in the training set can be properly loaded. ### Response: def sanity_check(self): "Check the underlying data in the training set can be properly loaded." final_message = "You can deactivate this warning by pa...
def __calculate_clusters(self, k): """! @brief Performs cluster analysis using specified K value. @param[in] k (uint): Amount of clusters that should be allocated. @return (array_like) Allocated clusters. """ initial_values = kmeans_plusplus_initializer(self._...
! @brief Performs cluster analysis using specified K value. @param[in] k (uint): Amount of clusters that should be allocated. @return (array_like) Allocated clusters.
Below is the the instruction that describes the task: ### Input: ! @brief Performs cluster analysis using specified K value. @param[in] k (uint): Amount of clusters that should be allocated. @return (array_like) Allocated clusters. ### Response: def __calculate_clusters(self, k): ...
def register_peer(self, connection_id, endpoint): """Registers a connected connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. endpoint (str): The publically reachable endpoint of the new ...
Registers a connected connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. endpoint (str): The publically reachable endpoint of the new peer
Below is the the instruction that describes the task: ### Input: Registers a connected connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. endpoint (str): The publically reachable endpoint of the ...
def _clear(cls): """This is only for testing pourposes, resets the DepotManager status This is to simplify writing test fixtures, resets the DepotManager global status and removes the informations related to the current configured depots and middleware. """ cls._default_...
This is only for testing pourposes, resets the DepotManager status This is to simplify writing test fixtures, resets the DepotManager global status and removes the informations related to the current configured depots and middleware.
Below is the the instruction that describes the task: ### Input: This is only for testing pourposes, resets the DepotManager status This is to simplify writing test fixtures, resets the DepotManager global status and removes the informations related to the current configured depots and midd...
def start_server(socket, projectname, xmlfilename: str) -> None: """Start the *HydPy* server using the given socket. The folder with the given `projectname` must be available within the current working directory. The XML configuration file must be placed within the project folder unless `xmlfilename` ...
Start the *HydPy* server using the given socket. The folder with the given `projectname` must be available within the current working directory. The XML configuration file must be placed within the project folder unless `xmlfilename` is an absolute file path. The XML configuration file must be valid c...
Below is the the instruction that describes the task: ### Input: Start the *HydPy* server using the given socket. The folder with the given `projectname` must be available within the current working directory. The XML configuration file must be placed within the project folder unless `xmlfilename` is ...
def scanResource(uri = None, listRegexp = None, verbosity=1, logFolder= "./logs"): ''' [Optionally] recursive method to scan the files in a given folder. :param uri: the URI to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :return: a dictionary where the key is the name of the fil...
[Optionally] recursive method to scan the files in a given folder. :param uri: the URI to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :return: a dictionary where the key is the name of the file.
Below is the the instruction that describes the task: ### Input: [Optionally] recursive method to scan the files in a given folder. :param uri: the URI to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :return: a dictionary where the key is the name of the file. ### Response: def ...
def _get_variables(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr): """ Implements @variables and @vars """ _rule = list(rule) _rule[CODESTR] = c_codestr _rule[PROPERTIES] = rule[CONTEXT] self.manage_children( ...
Implements @variables and @vars
Below is the the instruction that describes the task: ### Input: Implements @variables and @vars ### Response: def _get_variables(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr): """ Implements @variables and @vars """ _rule = list(rule...
def set_maximum(self, q_data, marked, center, bin_lower, foothills): """ Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordi...
Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordinates of the center pixel of the region being grown bin_lower: Intensity leve...
Below is the the instruction that describes the task: ### Input: Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordinates of the center ...
def getdebug(environ=os.environ, true_values=TRUE_VALUES): ''' Get if app is expected to be ran in debug mode looking at environment variables. :param environ: environment dict-like object :type environ: collections.abc.Mapping :returns: True if debug contains a true-like string, False otherwis...
Get if app is expected to be ran in debug mode looking at environment variables. :param environ: environment dict-like object :type environ: collections.abc.Mapping :returns: True if debug contains a true-like string, False otherwise :rtype: bool
Below is the the instruction that describes the task: ### Input: Get if app is expected to be ran in debug mode looking at environment variables. :param environ: environment dict-like object :type environ: collections.abc.Mapping :returns: True if debug contains a true-like string, False otherwise ...
def post_command(self, sender, name, result, args, kwargs): """ Call after we got the result of a redis command. By default, let the instance manage the post_modify signal """ return self._instance.post_command( sender=self, name=name, ...
Call after we got the result of a redis command. By default, let the instance manage the post_modify signal
Below is the the instruction that describes the task: ### Input: Call after we got the result of a redis command. By default, let the instance manage the post_modify signal ### Response: def post_command(self, sender, name, result, args, kwargs): """ Call after we got the result of a redis ...
def yaml_conf_as_dict(file_path, encoding=None): """ 读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量 :param: * file_path: (string) 需要读入的 yaml 配置文件长文件名 * encoding: (string) 文件编码 * msg: (string) 读取配置信息 :return: * flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False * d: (dict) 如果读取配置文件正...
读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量 :param: * file_path: (string) 需要读入的 yaml 配置文件长文件名 * encoding: (string) 文件编码 * msg: (string) 读取配置信息 :return: * flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False * d: (dict) 如果读取配置文件正确返回的包含配置文件内容的字典,字典内容顺序与配置文件顺序保持一致 举例如下:: print(...
Below is the the instruction that describes the task: ### Input: 读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量 :param: * file_path: (string) 需要读入的 yaml 配置文件长文件名 * encoding: (string) 文件编码 * msg: (string) 读取配置信息 :return: * flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False * d: (dict) 如...
def from_flag(cls, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError by providing flag name and values. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If th...
Create a DuplicateFlagError by providing flag name and values. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object wher...
Below is the the instruction that describes the task: ### Input: Create a DuplicateFlagError by providing flag name and values. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this ar...
def upload(self, f): """Upload a file to the Puush account. Parameters: * f: The file. Either a path to a file or a file-like object. """ if hasattr(f, 'read'): needs_closing = False else: f = open(f, 'rb') needs_closing = ...
Upload a file to the Puush account. Parameters: * f: The file. Either a path to a file or a file-like object.
Below is the the instruction that describes the task: ### Input: Upload a file to the Puush account. Parameters: * f: The file. Either a path to a file or a file-like object. ### Response: def upload(self, f): """Upload a file to the Puush account. Parameters: ...
def getnodes(fnods, up=None, verbose=False): """ Reads t.1.nodes, returns a list of nodes. Example: >>> self.getnodes("t.1.node", MyBar("nodes:")) [(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0), (0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4.0),...
Reads t.1.nodes, returns a list of nodes. Example: >>> self.getnodes("t.1.node", MyBar("nodes:")) [(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0), (0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4.0), (-2.0, 0.0, -2.0), (-2.0, 2.0, 0.0), (0.0, 2.0, -2.0), (...
Below is the the instruction that describes the task: ### Input: Reads t.1.nodes, returns a list of nodes. Example: >>> self.getnodes("t.1.node", MyBar("nodes:")) [(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0), (0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4...
def doi_exists(self, doi): """ This method retrieve a boolean according to the existence of a crossref DOI number. It returns False if the API results a 404 status code. args: Crossref DOI id (String) return: Boolean Example 1: >>> from crossref.restful imp...
This method retrieve a boolean according to the existence of a crossref DOI number. It returns False if the API results a 404 status code. args: Crossref DOI id (String) return: Boolean Example 1: >>> from crossref.restful import Works >>> works = Works() ...
Below is the the instruction that describes the task: ### Input: This method retrieve a boolean according to the existence of a crossref DOI number. It returns False if the API results a 404 status code. args: Crossref DOI id (String) return: Boolean Example 1: >>> fro...
def return_locals(func): '''Modifies decorated function to return its locals''' @functools.wraps(func) def wrap(*args, **kwargs): frames = [] def tracer(frame, event, arg): # pragma: no cover # coverage does not work in this function because the tracer # is deactiva...
Modifies decorated function to return its locals
Below is the the instruction that describes the task: ### Input: Modifies decorated function to return its locals ### Response: def return_locals(func): '''Modifies decorated function to return its locals''' @functools.wraps(func) def wrap(*args, **kwargs): frames = [] def tracer(fram...
def print_hierarchy(self, level: int = 0, file: IO[str] = sys.stdout) \ -> None: """ Print this comparison and its children with indentation to represent nesting. :param level: The level of indentation to use. This is mostly for internal use, but you ca...
Print this comparison and its children with indentation to represent nesting. :param level: The level of indentation to use. This is mostly for internal use, but you can use it to inset the root comparison. :param file: The stream to print to. Default...
Below is the the instruction that describes the task: ### Input: Print this comparison and its children with indentation to represent nesting. :param level: The level of indentation to use. This is mostly for internal use, but you can use it to inset the root ...
def inorder(self, funct, stopOn=None): """ Iterates in order, calling the function with the current node. If stopOn is set to True or False, it will stop on true or false. """ if stopOn is None: for i in self.children: i.inorder(funct) else: ...
Iterates in order, calling the function with the current node. If stopOn is set to True or False, it will stop on true or false.
Below is the the instruction that describes the task: ### Input: Iterates in order, calling the function with the current node. If stopOn is set to True or False, it will stop on true or false. ### Response: def inorder(self, funct, stopOn=None): """ Iterates in order, calling the function with the...
def equals(self, other): """ Ensures :attr:`subject` is equal to *other*. """ self._run(unittest_case.assertEqual, (self._subject, other)) return ChainInspector(self._subject)
Ensures :attr:`subject` is equal to *other*.
Below is the the instruction that describes the task: ### Input: Ensures :attr:`subject` is equal to *other*. ### Response: def equals(self, other): """ Ensures :attr:`subject` is equal to *other*. """ self._run(unittest_case.assertEqual, (self._subject, other)) return Chain...
def process_post_tag(self, bulk_mode, api_tag): """ Create or update a Tag related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_tag: the API data for the Tag :return: the Tag object """ tag = None ...
Create or update a Tag related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_tag: the API data for the Tag :return: the Tag object
Below is the the instruction that describes the task: ### Input: Create or update a Tag related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_tag: the API data for the Tag :return: the Tag object ### Response: def process_post_tag(sel...
def create_secgroup(self, name, desc): """ Creates a new server security group. :param str name: The name of the security group to create. :param str desc: A short description of the group. """ self.nova.security_groups.create(name, desc)
Creates a new server security group. :param str name: The name of the security group to create. :param str desc: A short description of the group.
Below is the the instruction that describes the task: ### Input: Creates a new server security group. :param str name: The name of the security group to create. :param str desc: A short description of the group. ### Response: def create_secgroup(self, name, desc): """ Creates a n...
def update(self, data=None, timeout=-1, custom_headers=None, force=False): """Makes a PUT request to update a resource when a request body is required. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not...
Makes a PUT request to update a resource when a request body is required. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its complet...
Below is the the instruction that describes the task: ### Input: Makes a PUT request to update a resource when a request body is required. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operat...
def __graceful_shutdown(self): """ call shutdown routines """ retcode = 1 self.log.info("Trying to shutdown gracefully...") retcode = self.core.plugins_end_test(retcode) retcode = self.core.plugins_post_process(retcode) self.log.info("Done graceful shutdown") retu...
call shutdown routines
Below is the the instruction that describes the task: ### Input: call shutdown routines ### Response: def __graceful_shutdown(self): """ call shutdown routines """ retcode = 1 self.log.info("Trying to shutdown gracefully...") retcode = self.core.plugins_end_test(retcode) ret...
def extend_service_volume(self, stack, service, volume, args): """扩容存储卷 为指定名称的服务增加存储卷资源,并挂载到部署的容器中。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: ...
扩容存储卷 为指定名称的服务增加存储卷资源,并挂载到部署的容器中。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result ...
Below is the the instruction that describes the task: ### Input: 扩容存储卷 为指定名称的服务增加存储卷资源,并挂载到部署的容器中。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: ...
def _handle_watch_message(self, message): """ Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes """ if self.log_protocol_level is not No...
Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes
Below is the the instruction that describes the task: ### Input: Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes ### Response: def _handle_watch_message(self, me...
def _CollectHistoryAgg_(contactHist, fieldHistObj, fieldName): """ Return updated history dictionary with new field change :param dict contactHist: Existing contact history dictionary :param dict fieldHistObj: Output of _CollectHistory_ :param string fieldName: field name """ if fieldHistO...
Return updated history dictionary with new field change :param dict contactHist: Existing contact history dictionary :param dict fieldHistObj: Output of _CollectHistory_ :param string fieldName: field name
Below is the the instruction that describes the task: ### Input: Return updated history dictionary with new field change :param dict contactHist: Existing contact history dictionary :param dict fieldHistObj: Output of _CollectHistory_ :param string fieldName: field name ### Response: def _CollectHisto...
def get_decoders(decoder_num, input_layer, encoded_layer, head_num, hidden_dim, attention_activation=None, feed_forward_activation='relu', dropout_rate=0.0, trainable=True): """Get...
Get decoders. :param decoder_num: Number of decoder components. :param input_layer: Input layer. :param encoded_layer: Encoded layer from encoder. :param head_num: Number of heads in multi-head self-attention. :param hidden_dim: Hidden dimension of feed forward layer. :param attention_activatio...
Below is the the instruction that describes the task: ### Input: Get decoders. :param decoder_num: Number of decoder components. :param input_layer: Input layer. :param encoded_layer: Encoded layer from encoder. :param head_num: Number of heads in multi-head self-attention. :param hidden_dim: H...
def iter_sources(self): """Iterates over all source names and IDs.""" for src_id in xrange(self.get_source_count()): yield src_id, self.get_source_name(src_id)
Iterates over all source names and IDs.
Below is the the instruction that describes the task: ### Input: Iterates over all source names and IDs. ### Response: def iter_sources(self): """Iterates over all source names and IDs.""" for src_id in xrange(self.get_source_count()): yield src_id, self.get_source_name(src_id)
def get_terms(self): ''' GROUP BY is a shortcut to only getting the first in every list of group ''' if not self.terms.empty: return self.terms if self.from_backup: self.terms = open_pickle(TERMS_BACKUP_PATH) return self.terms engine = create_engine(se...
GROUP BY is a shortcut to only getting the first in every list of group
Below is the the instruction that describes the task: ### Input: GROUP BY is a shortcut to only getting the first in every list of group ### Response: def get_terms(self): ''' GROUP BY is a shortcut to only getting the first in every list of group ''' if not self.terms.empty: return sel...
def listar_por_equip(self, equip_id): """Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, 'nome_divisao': <...
Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, 'nome_divisao': < nome_divisao >, 'id_ambiente_logico'...
Below is the the instruction that describes the task: ### Input: Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, ...
def moreland_adjusthue (msh, m_unsat): """Moreland's AdjustHue procedure to adjust the hue value of an Msh color based on ... some criterion. *msh* should be of of shape (3, ). *m_unsat* is a scalar. Return value is the adjusted h (hue) value. """ if msh[M] >= m_unsat: return msh[H] #...
Moreland's AdjustHue procedure to adjust the hue value of an Msh color based on ... some criterion. *msh* should be of of shape (3, ). *m_unsat* is a scalar. Return value is the adjusted h (hue) value.
Below is the the instruction that describes the task: ### Input: Moreland's AdjustHue procedure to adjust the hue value of an Msh color based on ... some criterion. *msh* should be of of shape (3, ). *m_unsat* is a scalar. Return value is the adjusted h (hue) value. ### Response: def moreland_adjusth...
def set_xlim_cb(self, redraw=True): """Set plot limit based on user values.""" try: xmin = float(self.w.x_lo.get_text()) except Exception: set_min = True else: set_min = False try: xmax = float(self.w.x_hi.get_text()) excep...
Set plot limit based on user values.
Below is the the instruction that describes the task: ### Input: Set plot limit based on user values. ### Response: def set_xlim_cb(self, redraw=True): """Set plot limit based on user values.""" try: xmin = float(self.w.x_lo.get_text()) except Exception: set_min = Tr...
def send_msg_async(self, *, message_type, user_id=None, group_id=None, discuss_id=None, message, auto_escape=False): """ 发送消息 (异步版本) ------------ :param str message_type: 消息类型,支持 `private`、`group`、`discuss`,分别对应私聊、群组、讨论组 :param int user_id: 对方 QQ 号(消息类型为 `private` 时需要) ...
发送消息 (异步版本) ------------ :param str message_type: 消息类型,支持 `private`、`group`、`discuss`,分别对应私聊、群组、讨论组 :param int user_id: 对方 QQ 号(消息类型为 `private` 时需要) :param int group_id: 群号(消息类型为 `group` 时需要) :param int discuss_id: 讨论组 ID(需要从上报消息中获取,消息类型为 `discuss` 时需要) :param str | lis...
Below is the the instruction that describes the task: ### Input: 发送消息 (异步版本) ------------ :param str message_type: 消息类型,支持 `private`、`group`、`discuss`,分别对应私聊、群组、讨论组 :param int user_id: 对方 QQ 号(消息类型为 `private` 时需要) :param int group_id: 群号(消息类型为 `group` 时需要) :param int discus...
def cartesian(nodes, order='C'): ''' Cartesian product of a list of arrays Parameters ---------- nodes : list(array_like(ndim=1)) order : str, optional(default='C') ('C' or 'F') order in which the product is enumerated Returns ------- out : ndarray(ndim=2) each lin...
Cartesian product of a list of arrays Parameters ---------- nodes : list(array_like(ndim=1)) order : str, optional(default='C') ('C' or 'F') order in which the product is enumerated Returns ------- out : ndarray(ndim=2) each line corresponds to one point of the product spa...
Below is the the instruction that describes the task: ### Input: Cartesian product of a list of arrays Parameters ---------- nodes : list(array_like(ndim=1)) order : str, optional(default='C') ('C' or 'F') order in which the product is enumerated Returns ------- out : ndarray(...
def get_closest_points(self, mesh): """ For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values. """ ...
For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values.
Below is the the instruction that describes the task: ### Input: For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values. ### Res...
def download_rsr(**kwargs): """Download the pre-compiled hdf5 formatet relative spectral response functions from the internet """ # import tarfile import requests TQDM_LOADED = True try: from tqdm import tqdm except ImportError: TQDM_LOADED = False dest_dir = k...
Download the pre-compiled hdf5 formatet relative spectral response functions from the internet
Below is the the instruction that describes the task: ### Input: Download the pre-compiled hdf5 formatet relative spectral response functions from the internet ### Response: def download_rsr(**kwargs): """Download the pre-compiled hdf5 formatet relative spectral response functions from the internet ...
def generate_sleepy_cat_graph(filepath, prefixes=None, identifier="NautilusSparql"): """ Generate a graph and change the global graph to this one :param filepath: A Uri for the graph :param prefixes: A dictionary of prefixes and namespaces to bind to the graph :param identifier: An identifier that will...
Generate a graph and change the global graph to this one :param filepath: A Uri for the graph :param prefixes: A dictionary of prefixes and namespaces to bind to the graph :param identifier: An identifier that will identify the Graph root
Below is the the instruction that describes the task: ### Input: Generate a graph and change the global graph to this one :param filepath: A Uri for the graph :param prefixes: A dictionary of prefixes and namespaces to bind to the graph :param identifier: An identifier that will identify the Graph root...
def get_plugin_meta(plugins): """ Returns meta data about plugins. :param plugins: A list of plugins. :type plugins: list :returns: A list of dicts containing plugin meta data. :rtype: list """ return [ { "name": p.name, "version": p.version, ...
Returns meta data about plugins. :param plugins: A list of plugins. :type plugins: list :returns: A list of dicts containing plugin meta data. :rtype: list
Below is the the instruction that describes the task: ### Input: Returns meta data about plugins. :param plugins: A list of plugins. :type plugins: list :returns: A list of dicts containing plugin meta data. :rtype: list ### Response: def get_plugin_meta(plugins): """ Returns meta data abo...
def _api_key_patch_replace(conn, apiKey, path, value): ''' the replace patch operation on an ApiKey resource ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
the replace patch operation on an ApiKey resource
Below is the the instruction that describes the task: ### Input: the replace patch operation on an ApiKey resource ### Response: def _api_key_patch_replace(conn, apiKey, path, value): ''' the replace patch operation on an ApiKey resource ''' response = conn.update_api_key(apiKey=apiKey, ...
def reload_including_local(module): """ Reload a module. If it isn"t found, try to include the local service directory. This must be called from a thread that has acquired the import lock. :param module: the module to reload. """ try: reload(module) except ImportError: ...
Reload a module. If it isn"t found, try to include the local service directory. This must be called from a thread that has acquired the import lock. :param module: the module to reload.
Below is the the instruction that describes the task: ### Input: Reload a module. If it isn"t found, try to include the local service directory. This must be called from a thread that has acquired the import lock. :param module: the module to reload. ### Response: def reload_including_local(module):...
def _serialize( self, obj, fields_dict, error_store, many=False, accessor=None, dict_class=dict, index_errors=True, index=None, ): """Takes raw data (a dict, list, or other object) and a dict of fields to output and serializes the data based on those fields. :param o...
Takes raw data (a dict, list, or other object) and a dict of fields to output and serializes the data based on those fields. :param obj: The actual object(s) from which the fields are taken from :param dict fields_dict: Mapping of field names to :class:`Field` objects. :param ErrorStore...
Below is the the instruction that describes the task: ### Input: Takes raw data (a dict, list, or other object) and a dict of fields to output and serializes the data based on those fields. :param obj: The actual object(s) from which the fields are taken from :param dict fields_dict: Mappin...
def iter_walk_menus(self): """ Useful for example to spread changes to the prompt, e.g. enabling or disabling colors. """ yield self for item in self.name_to_command.values(): if isinstance(item, _Menu): # "Generator delegation" ;) ...
Useful for example to spread changes to the prompt, e.g. enabling or disabling colors.
Below is the the instruction that describes the task: ### Input: Useful for example to spread changes to the prompt, e.g. enabling or disabling colors. ### Response: def iter_walk_menus(self): """ Useful for example to spread changes to the prompt, e.g. enabling or disabling colors....
def should_copy(column): """ Determine if a column should be copied. """ if not isinstance(column.type, Serial): return True if column.nullable: return True if not column.server_default: return True # do not create temporary serial values; they will be defaulted o...
Determine if a column should be copied.
Below is the the instruction that describes the task: ### Input: Determine if a column should be copied. ### Response: def should_copy(column): """ Determine if a column should be copied. """ if not isinstance(column.type, Serial): return True if column.nullable: return True ...
def setattr_at_path( obj, path, val ): """ Traverses a set of nested attributes to the value on an object :param mixed obj: The object to set the attribute on :param tuple path: The path to the attribute on the object :param mixed val: The value at the attribute :rtype None: """ target...
Traverses a set of nested attributes to the value on an object :param mixed obj: The object to set the attribute on :param tuple path: The path to the attribute on the object :param mixed val: The value at the attribute :rtype None:
Below is the the instruction that describes the task: ### Input: Traverses a set of nested attributes to the value on an object :param mixed obj: The object to set the attribute on :param tuple path: The path to the attribute on the object :param mixed val: The value at the attribute :rtype None: ...
def quotation(self, origin, target): """Return quotation between two currencies (origin, target)""" if not self._backend: raise ExchangeBackendNotInstalled() return self._backend.quotation(origin, target)
Return quotation between two currencies (origin, target)
Below is the the instruction that describes the task: ### Input: Return quotation between two currencies (origin, target) ### Response: def quotation(self, origin, target): """Return quotation between two currencies (origin, target)""" if not self._backend: raise ExchangeBackendNotInsta...
def descending(self, name): ''' Add a descending index for ``name`` to this index. :param name: Name to be used in the index ''' self.components.append((name, Index.DESCENDING)) return self
Add a descending index for ``name`` to this index. :param name: Name to be used in the index
Below is the the instruction that describes the task: ### Input: Add a descending index for ``name`` to this index. :param name: Name to be used in the index ### Response: def descending(self, name): ''' Add a descending index for ``name`` to this index. :param name: Name to be us...
def clean_missing_exponent(pst_filename,clean_filename="clean.pst"): """fixes the issue where some terrible fortran program may have written a floating point format without the 'e' - like 1.0-3, really?! Parameters ---------- pst_filename : str the pest control file clean_filename : str...
fixes the issue where some terrible fortran program may have written a floating point format without the 'e' - like 1.0-3, really?! Parameters ---------- pst_filename : str the pest control file clean_filename : str the new pest control file to write. Default is "clean.pst" Ret...
Below is the the instruction that describes the task: ### Input: fixes the issue where some terrible fortran program may have written a floating point format without the 'e' - like 1.0-3, really?! Parameters ---------- pst_filename : str the pest control file clean_filename : str ...
def _set_interface_loopback_ospf_conf(self, v, load=False): """ Setter method for interface_loopback_ospf_conf, mapped from YANG variable /routing_system/interface/loopback/ip/interface_loopback_ospf_conf (container) If this variable is read-only (config: false) in the source YANG file, then _set_interf...
Setter method for interface_loopback_ospf_conf, mapped from YANG variable /routing_system/interface/loopback/ip/interface_loopback_ospf_conf (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_loopback_ospf_conf is considered as a private method. Backends l...
Below is the the instruction that describes the task: ### Input: Setter method for interface_loopback_ospf_conf, mapped from YANG variable /routing_system/interface/loopback/ip/interface_loopback_ospf_conf (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface...
def unreduce(array, shape, axis, keepdims): """Reverse summing over a dimension. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: An ar...
Reverse summing over a dimension. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: An array with axes broadcast to match the shape of the...
Below is the the instruction that describes the task: ### Input: Reverse summing over a dimension. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. ...
def learn(self, grad_arr, fix_opt_flag=False): ''' Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: ...
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
Below is the the instruction that describes the task: ### Input: Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: ...
def _raise_for_status(response): """Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given. """ http_error_msg = '' if 400 <= response.status_code < 500: http_erro...
Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given.
Below is the the instruction that describes the task: ### Input: Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given. ### Response: def _raise_for_status(response): """Raises st...
def get_dag(self, dag_id): """ Gets the DAG out of the dictionary, and refreshes it if expired """ from airflow.models.dag import DagModel # Avoid circular import # If asking for a known subdag, we want to refresh the parent root_dag_id = dag_id if dag_id in sel...
Gets the DAG out of the dictionary, and refreshes it if expired
Below is the the instruction that describes the task: ### Input: Gets the DAG out of the dictionary, and refreshes it if expired ### Response: def get_dag(self, dag_id): """ Gets the DAG out of the dictionary, and refreshes it if expired """ from airflow.models.dag import DagModel ...
def upload(self, remote_path, file_content, ondup=None, **kwargs): """上传单个文件(<2G). | 百度PCS服务目前支持最大2G的单个文件上传。 | 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。 :param remote_path: 网盘中文件的保存路径(包含文件名)。 必须以 /apps/ 开头。 .. warning:: ...
上传单个文件(<2G). | 百度PCS服务目前支持最大2G的单个文件上传。 | 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。 :param remote_path: 网盘中文件的保存路径(包含文件名)。 必须以 /apps/ 开头。 .. warning:: * 路径长度限制为1000; * 径中不能包含以下字符:...
Below is the the instruction that describes the task: ### Input: 上传单个文件(<2G). | 百度PCS服务目前支持最大2G的单个文件上传。 | 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。 :param remote_path: 网盘中文件的保存路径(包含文件名)。 必须以 /apps/ 开头。 .. warning:: ...
def fave_dashboards_by_username(self, username): """This lets us use a user's username to pull favourite dashboards""" user = security_manager.find_user(username=username) return self.fave_dashboards(user.get_id())
This lets us use a user's username to pull favourite dashboards
Below is the the instruction that describes the task: ### Input: This lets us use a user's username to pull favourite dashboards ### Response: def fave_dashboards_by_username(self, username): """This lets us use a user's username to pull favourite dashboards""" user = security_manager.find_user(use...
def relative_symlink(target, link_name): """Make a symlink to target using the shortest possible relative path.""" link_name = os.path.abspath(link_name) abs_target = os.path.abspath(target) rel_target = os.path.relpath(target, os.path.dirname(link_name)) if os.path.exists(link_name): os.re...
Make a symlink to target using the shortest possible relative path.
Below is the the instruction that describes the task: ### Input: Make a symlink to target using the shortest possible relative path. ### Response: def relative_symlink(target, link_name): """Make a symlink to target using the shortest possible relative path.""" link_name = os.path.abspath(link_name) ab...
def pub_close(self): ''' Disconnect an existing publisher socket and remove it from the local thread's cache. ''' if hasattr(self._sock_data, 'sock'): self._sock_data.sock.close() delattr(self._sock_data, 'sock')
Disconnect an existing publisher socket and remove it from the local thread's cache.
Below is the the instruction that describes the task: ### Input: Disconnect an existing publisher socket and remove it from the local thread's cache. ### Response: def pub_close(self): ''' Disconnect an existing publisher socket and remove it from the local thread's cache. '...
def trmm(self,B,trans='N'): r""" Multiplication with product-form Cholesky factor. Computes .. math:: B &:= L B \text{ if trans is 'N'} B &:= L^T B \text{ if trans is 'T'} """ if trans=='N': pftrmm(self._V,self._L,self._...
r""" Multiplication with product-form Cholesky factor. Computes .. math:: B &:= L B \text{ if trans is 'N'} B &:= L^T B \text{ if trans is 'T'}
Below is the the instruction that describes the task: ### Input: r""" Multiplication with product-form Cholesky factor. Computes .. math:: B &:= L B \text{ if trans is 'N'} B &:= L^T B \text{ if trans is 'T'} ### Response: def trmm(self,B,trans='N'): r...
def content_location(self) -> Optional[UnstructuredHeader]: """The ``Content-Location`` header.""" try: return cast(UnstructuredHeader, self[b'content-location'][0]) except (KeyError, IndexError): return None
The ``Content-Location`` header.
Below is the the instruction that describes the task: ### Input: The ``Content-Location`` header. ### Response: def content_location(self) -> Optional[UnstructuredHeader]: """The ``Content-Location`` header.""" try: return cast(UnstructuredHeader, self[b'content-location'][0]) e...
def get(key, profile=None): ''' Get a value from memcached ''' conn = salt.utils.memcached.get_conn(profile) return salt.utils.memcached.get(conn, key)
Get a value from memcached
Below is the the instruction that describes the task: ### Input: Get a value from memcached ### Response: def get(key, profile=None): ''' Get a value from memcached ''' conn = salt.utils.memcached.get_conn(profile) return salt.utils.memcached.get(conn, key)
def unit_tangent(self, t): """returns the unit tangent vector of the segment at t (centered at the origin and expressed as a complex number).""" dseg = self.derivative(t) return dseg/abs(dseg)
returns the unit tangent vector of the segment at t (centered at the origin and expressed as a complex number).
Below is the the instruction that describes the task: ### Input: returns the unit tangent vector of the segment at t (centered at the origin and expressed as a complex number). ### Response: def unit_tangent(self, t): """returns the unit tangent vector of the segment at t (centered at the o...
def rsky_distribution(self,rmax=None,smooth=0.1,nbins=100): """ Distribution of projected separations Returns a :class:`simpledists.Hist_Distribution` object. :param rmax: (optional) Maximum radius to calculate distribution. :param dr: (optional) Bin wi...
Distribution of projected separations Returns a :class:`simpledists.Hist_Distribution` object. :param rmax: (optional) Maximum radius to calculate distribution. :param dr: (optional) Bin width for histogram :param smooth: (optional) Smoothing param...
Below is the the instruction that describes the task: ### Input: Distribution of projected separations Returns a :class:`simpledists.Hist_Distribution` object. :param rmax: (optional) Maximum radius to calculate distribution. :param dr: (optional) Bin width for his...
def _join_chemical(query, cas_rn, chemical_id, chemical_name, chemical_definition): """helper function to add a query join to Chemical model :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param cas_rn: :param chemical_id: :param chemical_name: ...
helper function to add a query join to Chemical model :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param cas_rn: :param chemical_id: :param chemical_name: :param chemical_definition: :return: `sqlalchemy.orm.query.Query` object
Below is the the instruction that describes the task: ### Input: helper function to add a query join to Chemical model :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param cas_rn: :param chemical_id: :param chemical_name: :param chemical_definition...
def get_manager(self, model): """ Return the active manager for the given model. :param model: Model class to look up the manager instance for. :return: Manager instance for the model associated with this client. """ if isinstance(model, six.string_types): # u...
Return the active manager for the given model. :param model: Model class to look up the manager instance for. :return: Manager instance for the model associated with this client.
Below is the the instruction that describes the task: ### Input: Return the active manager for the given model. :param model: Model class to look up the manager instance for. :return: Manager instance for the model associated with this client. ### Response: def get_manager(self, model): """...
def addField(self, name, label, type=None, draw=None, info=None, #@ReservedAssignment extinfo=None, colour=None, negative=None, graph=None, min=None, max=None, cdef=None, line=None, #@ReservedAssignment warning=None, critical=None): """Add field to Munin Grap...
Add field to Munin Graph @param name: Field Name @param label: Field Label @param type: Stat Type: 'COUNTER' / 'ABSOLUTE' / 'DERIVE' / 'GAUGE' @param draw: Graph Type: 'AREA' / 'LINE{1,2,3}'...
Below is the the instruction that describes the task: ### Input: Add field to Munin Graph @param name: Field Name @param label: Field Label @param type: Stat Type: 'COUNTER' / 'ABSOLUTE' / 'DERIVE' / 'GAUGE' @param draw...
def get_sub_dim(src_ds, scale=None, maxdim=1024): """Compute dimensions of subsampled dataset Parameters ---------- ds : gdal.Dataset Input GDAL Datset scale : int, optional Scaling factor maxdim : int, optional Maximum dimension along either axis, in pixels ...
Compute dimensions of subsampled dataset Parameters ---------- ds : gdal.Dataset Input GDAL Datset scale : int, optional Scaling factor maxdim : int, optional Maximum dimension along either axis, in pixels Returns ------- ns Numper of samples in s...
Below is the the instruction that describes the task: ### Input: Compute dimensions of subsampled dataset Parameters ---------- ds : gdal.Dataset Input GDAL Datset scale : int, optional Scaling factor maxdim : int, optional Maximum dimension along either axis, in pixe...
def make_inst1(): """creates example data set 1""" I,d = multidict({1:80, 2:270, 3:250 , 4:160, 5:180}) # demand J,M = multidict({1:500, 2:500, 3:500}) # capacity c = {(1,1):4, (1,2):6, (1,3):9, # cost (2,1):5, (2,2):4, (2,3):7, (3,1):6, (3,2):3, (3,3):...
creates example data set 1
Below is the the instruction that describes the task: ### Input: creates example data set 1 ### Response: def make_inst1(): """creates example data set 1""" I,d = multidict({1:80, 2:270, 3:250 , 4:160, 5:180}) # demand J,M = multidict({1:500, 2:500, 3:500}) # capacity c = {(1,1):4, ...
def _get_solver(self, **kwargs): """Return a new :class:`psamm.lpsolver.lp.Solver` instance""" solver_args = dict(kwargs) solver_args.update(self._solver_args) return generic.Solver(**solver_args)
Return a new :class:`psamm.lpsolver.lp.Solver` instance
Below is the the instruction that describes the task: ### Input: Return a new :class:`psamm.lpsolver.lp.Solver` instance ### Response: def _get_solver(self, **kwargs): """Return a new :class:`psamm.lpsolver.lp.Solver` instance""" solver_args = dict(kwargs) solver_args.update(self._solver_ar...
def image_create(self, disk, label=None, description=None): """ Creates a new Image from a disk you own. :param disk: The Disk to imagize. :type disk: Disk or int :param label: The label for the resulting Image (defaults to the disk's label. :type l...
Creates a new Image from a disk you own. :param disk: The Disk to imagize. :type disk: Disk or int :param label: The label for the resulting Image (defaults to the disk's label. :type label: str :param description: The description for the new Image. ...
Below is the the instruction that describes the task: ### Input: Creates a new Image from a disk you own. :param disk: The Disk to imagize. :type disk: Disk or int :param label: The label for the resulting Image (defaults to the disk's label. :type label: str ...
def to_string(self): """Returns a string representation of the edge in dot language. """ src = self.parse_node_ref( self.get_source() ) dst = self.parse_node_ref( self.get_destination() ) if isinstance(src, frozendict): edge = [ Subgraph(obj_dict=src).to_str...
Returns a string representation of the edge in dot language.
Below is the the instruction that describes the task: ### Input: Returns a string representation of the edge in dot language. ### Response: def to_string(self): """Returns a string representation of the edge in dot language. """ src = self.parse_node_ref( self.get_source() ) dst = ...
def add_device_override(self, addr, cat, subcat, firmware=None): """Add a device override to the PLM.""" self.plm.devices.add_override(addr, 'cat', cat) self.plm.devices.add_override(addr, 'subcat', subcat) if firmware: self.plm.devices.add_override(addr, 'firmware', firmware...
Add a device override to the PLM.
Below is the the instruction that describes the task: ### Input: Add a device override to the PLM. ### Response: def add_device_override(self, addr, cat, subcat, firmware=None): """Add a device override to the PLM.""" self.plm.devices.add_override(addr, 'cat', cat) self.plm.devices.add_over...
def get_safe_label(self): """Returns a label that is safe to add to a path in the mountpoint for this volume.""" if self.info.get('label') == '/': return 'root' suffix = re.sub(r"[/ \(\)]+", "_", self.info.get('label')) if self.info.get('label') else "" if suffix and suffix...
Returns a label that is safe to add to a path in the mountpoint for this volume.
Below is the the instruction that describes the task: ### Input: Returns a label that is safe to add to a path in the mountpoint for this volume. ### Response: def get_safe_label(self): """Returns a label that is safe to add to a path in the mountpoint for this volume.""" if self.info.get('label')...
def objects_reachable_from(obj): """ Return graph of objects reachable from *obj* via ``gc.get_referrers``. Returns an :class:`~refcycle.object_graph.ObjectGraph` object holding all objects reachable from the given one by following the output of ``gc.get_referrers``. Note that unlike the :func...
Return graph of objects reachable from *obj* via ``gc.get_referrers``. Returns an :class:`~refcycle.object_graph.ObjectGraph` object holding all objects reachable from the given one by following the output of ``gc.get_referrers``. Note that unlike the :func:`~refcycle.creators.snapshot` function, the ...
Below is the the instruction that describes the task: ### Input: Return graph of objects reachable from *obj* via ``gc.get_referrers``. Returns an :class:`~refcycle.object_graph.ObjectGraph` object holding all objects reachable from the given one by following the output of ``gc.get_referrers``. Note t...
def zpoppush(self, source, destination, count, score, new_score, client=None, withscores=False, on_success=None, if_exists=None): """ Pops the first ``count`` members from the ZSET ``source`` and adds them to the ZSET ``destination`` with a score of ``new_score`...
Pops the first ``count`` members from the ZSET ``source`` and adds them to the ZSET ``destination`` with a score of ``new_score``. If ``score`` is not None, only members up to a score of ``score`` are used. Returns the members that were moved and, if ``withscores`` is True, their origina...
Below is the the instruction that describes the task: ### Input: Pops the first ``count`` members from the ZSET ``source`` and adds them to the ZSET ``destination`` with a score of ``new_score``. If ``score`` is not None, only members up to a score of ``score`` are used. Returns the members ...
def load_yaml(fname): """Load a YAML file.""" yaml = YAML(typ="safe") # Compat with HASS yaml.allow_duplicate_keys = True # Stub HASS constructors HassSafeConstructor.name = fname yaml.Constructor = HassSafeConstructor with open(fname, encoding="utf-8") as conf_file: # If config...
Load a YAML file.
Below is the the instruction that describes the task: ### Input: Load a YAML file. ### Response: def load_yaml(fname): """Load a YAML file.""" yaml = YAML(typ="safe") # Compat with HASS yaml.allow_duplicate_keys = True # Stub HASS constructors HassSafeConstructor.name = fname yaml.Const...
def QA_fetch_get_globalfuture_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 14 3 伦敦金属 LM 15 3 伦敦石油 IP 16 3 纽约商...
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 14 3 伦敦金属 LM 15 3 伦敦石油 IP 16 3 纽约商品 CO 17 3 纽约石油 NY 18...
Below is the the instruction that describes the task: ### Input: [summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 14 3 伦敦金属 LM 15 3 伦敦石油 IP 16 3 ...
def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return result if len(result) > 0 else...
Prompts the user, with a default. Returns user input from ``stdin``.
Below is the the instruction that describes the task: ### Input: Prompts the user, with a default. Returns user input from ``stdin``. ### Response: def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if defaul...
def is_real(arg): ''' is_real(x) yields True if x is a non-complex numeric object and False otherwise. Note that is_real(i) will yield True for an integer or bool i; to check for floating-point representations of numbers, use is_array(x, numpy.floating) or similar. ''' return (is_real(mag(arg))...
is_real(x) yields True if x is a non-complex numeric object and False otherwise. Note that is_real(i) will yield True for an integer or bool i; to check for floating-point representations of numbers, use is_array(x, numpy.floating) or similar.
Below is the the instruction that describes the task: ### Input: is_real(x) yields True if x is a non-complex numeric object and False otherwise. Note that is_real(i) will yield True for an integer or bool i; to check for floating-point representations of numbers, use is_array(x, numpy.floating) or similar...
def _scalar_coef_op_left(func): """decorator for operator overloading when ScalarCoef is on the left""" @wraps(func) def verif(self, scoef): if isinstance(scoef, ScalarCoefs): if len(self._vec) == len(scoef._vec): return ScalarCoefs(...
decorator for operator overloading when ScalarCoef is on the left
Below is the the instruction that describes the task: ### Input: decorator for operator overloading when ScalarCoef is on the left ### Response: def _scalar_coef_op_left(func): """decorator for operator overloading when ScalarCoef is on the left""" @wraps(func) def veri...
def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources ...
Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config
Below is the the instruction that describes the task: ### Input: Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ### Response: def get_resources_nodes(call=None, resFilter=None): ''' Retri...
def BoolEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a boolean field.""" false_byte = b'\x00' true_byte = b'\x01' if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value...
Returns an encoder for a boolean field.
Below is the the instruction that describes the task: ### Input: Returns an encoder for a boolean field. ### Response: def BoolEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a boolean field.""" false_byte = b'\x00' true_byte = b'\x01' if is_packed: tag_bytes = TagBytes(field_...
def export_records(self, bucket_name, export_path='', overwrite=True): ''' a method to export all the records from a bucket to local files :param bucket_name: string with name of bucket :param export_path: [optional] string with path to root directory for record dump :param...
a method to export all the records from a bucket to local files :param bucket_name: string with name of bucket :param export_path: [optional] string with path to root directory for record dump :param overwrite: [optional] boolean to overwrite existing files matching records :return: Tru...
Below is the the instruction that describes the task: ### Input: a method to export all the records from a bucket to local files :param bucket_name: string with name of bucket :param export_path: [optional] string with path to root directory for record dump :param overwrite: [optional] bool...
def calling_convention(self): """function calling convention. See :class:CALLING_CONVENTION_TYPES class for possible values""" if self._calling_convention is None: self._calling_convention = \ calldef_types.CALLING_CONVENTION_TYPES.extract(self.attributes) ...
function calling convention. See :class:CALLING_CONVENTION_TYPES class for possible values
Below is the the instruction that describes the task: ### Input: function calling convention. See :class:CALLING_CONVENTION_TYPES class for possible values ### Response: def calling_convention(self): """function calling convention. See :class:CALLING_CONVENTION_TYPES class for possi...
def merge_infos(info1, info2): """We often need to aggregate together multiple infos. Most keys can just be clobbered by the new info, but e.g. any keys which contain counts should be added. The merge schema is indicated by the key namespace. Namespaces: - stats.timers: Timing - stats.gaug...
We often need to aggregate together multiple infos. Most keys can just be clobbered by the new info, but e.g. any keys which contain counts should be added. The merge schema is indicated by the key namespace. Namespaces: - stats.timers: Timing - stats.gauges: Gauge values - stats.*: Counts...
Below is the the instruction that describes the task: ### Input: We often need to aggregate together multiple infos. Most keys can just be clobbered by the new info, but e.g. any keys which contain counts should be added. The merge schema is indicated by the key namespace. Namespaces: - stats....
def datetime(past=True, random=random): """ Returns a random datetime from the past... or the future! >>> mock_random.seed(0) >>> datetime(random=mock_random).isoformat() '1950-02-03T03:04:05' """ def year(): if past: return random.choice(range(1950,2005)) else...
Returns a random datetime from the past... or the future! >>> mock_random.seed(0) >>> datetime(random=mock_random).isoformat() '1950-02-03T03:04:05'
Below is the the instruction that describes the task: ### Input: Returns a random datetime from the past... or the future! >>> mock_random.seed(0) >>> datetime(random=mock_random).isoformat() '1950-02-03T03:04:05' ### Response: def datetime(past=True, random=random): """ Returns a random datet...
def make_parser(): """ Make an ArgumentParser that accepts DNS RRs """ line_parser = ZonefileLineParser() subparsers = line_parser.add_subparsers() # parse $ORIGIN sp = subparsers.add_parser("$ORIGIN") sp.add_argument("$ORIGIN", type=str) # parse $TTL sp = subparsers.add_parser...
Make an ArgumentParser that accepts DNS RRs
Below is the the instruction that describes the task: ### Input: Make an ArgumentParser that accepts DNS RRs ### Response: def make_parser(): """ Make an ArgumentParser that accepts DNS RRs """ line_parser = ZonefileLineParser() subparsers = line_parser.add_subparsers() # parse $ORIGIN ...
def scope_required(*scopes): """ Test for specific scopes that the access token has been authenticated for before processing the request and eventual response. The scopes that are passed in determine how the decorator will respond to incoming requests: - If no scopes are passed in the argument...
Test for specific scopes that the access token has been authenticated for before processing the request and eventual response. The scopes that are passed in determine how the decorator will respond to incoming requests: - If no scopes are passed in the arguments, the decorator will test for any availa...
Below is the the instruction that describes the task: ### Input: Test for specific scopes that the access token has been authenticated for before processing the request and eventual response. The scopes that are passed in determine how the decorator will respond to incoming requests: - If no scope...
def add_analyses(cls, source): """Dynamically add new analysis methods to the Timeseries class. Args: source: Can be a function, module or the filename of a python file. If a filename or a module is given, then all functions defined inside not starting with _ will be a...
Dynamically add new analysis methods to the Timeseries class. Args: source: Can be a function, module or the filename of a python file. If a filename or a module is given, then all functions defined inside not starting with _ will be added as methods. The only restric...
Below is the the instruction that describes the task: ### Input: Dynamically add new analysis methods to the Timeseries class. Args: source: Can be a function, module or the filename of a python file. If a filename or a module is given, then all functions defined inside no...
def thread_safe(method): """ wraps method with lock acquire/release cycle decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock """ @functools.wraps(method) def _locker(self, *args, **kwargs): assert hasattr(self, 'lock'), \ 'thread_saf...
wraps method with lock acquire/release cycle decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock
Below is the the instruction that describes the task: ### Input: wraps method with lock acquire/release cycle decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock ### Response: def thread_safe(method): """ wraps method with lock acquire/release cycle dec...
def apply(self, event = None): """Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.""" for section in self.config.sections(): # Run through the sections to check all the option values: for option, o in self.config.config[section].items(...
Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.
Below is the the instruction that describes the task: ### Input: Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config. ### Response: def apply(self, event = None): """Before self.onOk closes the window, it calls this function to sync the config c...
def handler_view(self, request, resource_name, ids=None): """ Handler for resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse """ signal_request.send(sender=self, request=request) time_start = time.time() self.upda...
Handler for resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse
Below is the the instruction that describes the task: ### Input: Handler for resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse ### Response: def handler_view(self, request, resource_name, ids=None): """ Handler for resources. .. ve...
def _query_nsot(url, headers, device=None): ''' if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return: ''' url = urlparse.urljoin(url, 'devices') ret = {} if not device:...
if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return:
Below is the the instruction that describes the task: ### Input: if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return: ### Response: def _query_nsot(url, headers, device=None): ''' ...
def trivialInput(symbol): """ Create a new L{IRichInput} implementation for the given input symbol. This creates a new type object and is intended to be used at module scope to define rich input types. Generally, only one use per symbol should be required. For example:: Apple = trivialIn...
Create a new L{IRichInput} implementation for the given input symbol. This creates a new type object and is intended to be used at module scope to define rich input types. Generally, only one use per symbol should be required. For example:: Apple = trivialInput(Fruit.apple) @param symbol: A...
Below is the the instruction that describes the task: ### Input: Create a new L{IRichInput} implementation for the given input symbol. This creates a new type object and is intended to be used at module scope to define rich input types. Generally, only one use per symbol should be required. For examp...
def foreach_loop(self, context): """Run step once for each item in foreach_items. On each iteration, the invoked step can use context['i'] to get the current iterator value. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate....
Run step once for each item in foreach_items. On each iteration, the invoked step can use context['i'] to get the current iterator value. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
Below is the the instruction that describes the task: ### Input: Run step once for each item in foreach_items. On each iteration, the invoked step can use context['i'] to get the current iterator value. Args: context: (pypyr.context.Context) The pypyr context. This arg will ...
def mixer(servo1, servo2, mixtype=1, gain=0.5): '''mix two servos''' s1 = servo1 - 1500 s2 = servo2 - 1500 v1 = (s1-s2)*gain v2 = (s1+s2)*gain if mixtype == 2: v2 = -v2 elif mixtype == 3: v1 = -v1 elif mixtype == 4: v1 = -v1 v2 = -v2 if v1 > 600: ...
mix two servos
Below is the the instruction that describes the task: ### Input: mix two servos ### Response: def mixer(servo1, servo2, mixtype=1, gain=0.5): '''mix two servos''' s1 = servo1 - 1500 s2 = servo2 - 1500 v1 = (s1-s2)*gain v2 = (s1+s2)*gain if mixtype == 2: v2 = -v2 elif mixtype == ...
def lspearmanr(x,y): """ Calculates a Spearman rank-order correlation coefficient. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. Usage: lspearmanr(x,y) where x and y are equal-length lists Returns: Spearman's r, two-tailed p-value """ TINY = 1e-30 if len(x) != len(y): ...
Calculates a Spearman rank-order correlation coefficient. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. Usage: lspearmanr(x,y) where x and y are equal-length lists Returns: Spearman's r, two-tailed p-value
Below is the the instruction that describes the task: ### Input: Calculates a Spearman rank-order correlation coefficient. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. Usage: lspearmanr(x,y) where x and y are equal-length lists Returns: Spearman's r, two-tailed p-value ### Response...
def dump(self): """Dump to file""" # NO Dump file selected -> DO NOTHING if self.running_config.output_file: # Determinate file format _, extension = op.splitext(self.running_config.output_file) extension = extension.replace(".", "") if extensio...
Dump to file
Below is the the instruction that describes the task: ### Input: Dump to file ### Response: def dump(self): """Dump to file""" # NO Dump file selected -> DO NOTHING if self.running_config.output_file: # Determinate file format _, extension = op.splitext(self.runnin...
def from_record(self, record): """ Constructs and returns a sequenced item object, from given ORM object. """ kwargs = self.get_field_kwargs(record) return self.sequenced_item_class(**kwargs)
Constructs and returns a sequenced item object, from given ORM object.
Below is the the instruction that describes the task: ### Input: Constructs and returns a sequenced item object, from given ORM object. ### Response: def from_record(self, record): """ Constructs and returns a sequenced item object, from given ORM object. """ kwargs = self.get_field...