code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def load_string(self, string_data, share_name, directory_name, file_name, **kwargs): """ Upload a string to Azure File Share. :param string_data: String to load. :type string_data: str :param share_name: Name of the share. :type share_name: str :param directory_name: Name of the directory. :type directory_name: str :param file_name: Name of the file. :type file_name: str :param kwargs: Optional keyword arguments that `FileService.create_file_from_text()` takes. :type kwargs: object """ self.connection.create_file_from_text(share_name, directory_name, file_name, string_data, **kwargs)
Upload a string to Azure File Share. :param string_data: String to load. :type string_data: str :param share_name: Name of the share. :type share_name: str :param directory_name: Name of the directory. :type directory_name: str :param file_name: Name of the file. :type file_name: str :param kwargs: Optional keyword arguments that `FileService.create_file_from_text()` takes. :type kwargs: object
Below is the the instruction that describes the task: ### Input: Upload a string to Azure File Share. :param string_data: String to load. :type string_data: str :param share_name: Name of the share. :type share_name: str :param directory_name: Name of the directory. :type directory_name: str :param file_name: Name of the file. :type file_name: str :param kwargs: Optional keyword arguments that `FileService.create_file_from_text()` takes. :type kwargs: object ### Response: def load_string(self, string_data, share_name, directory_name, file_name, **kwargs): """ Upload a string to Azure File Share. :param string_data: String to load. :type string_data: str :param share_name: Name of the share. :type share_name: str :param directory_name: Name of the directory. :type directory_name: str :param file_name: Name of the file. :type file_name: str :param kwargs: Optional keyword arguments that `FileService.create_file_from_text()` takes. :type kwargs: object """ self.connection.create_file_from_text(share_name, directory_name, file_name, string_data, **kwargs)
def get_max_id(cls, session): """Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM object classes that are derived from other ORM object classes, the max ``id`` of the lowest base class is returned. This is designed to be used with inheritance by joining, in which derived and base class objects have identical ``id`` values. Args: session: database session to operate in """ # sqlalchemy allows only one level of inheritance, so just check this class and all its bases id_base = None for c in [cls] + list(cls.__bases__): for base_class in c.__bases__: if base_class.__name__ == 'Base': if id_base is None: # we found our base class for determining the ID id_base = c else: raise RuntimeError("Multiple base object classes for class " + cls.__name__) # this should never happen if id_base is None: raise RuntimeError("Error searching for base class of " + cls.__name__) # get its max ID max_id = session.query(func.max(id_base.id)).scalar() # if no object is present, None is returned if max_id is None: max_id = 0 return max_id
Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM object classes that are derived from other ORM object classes, the max ``id`` of the lowest base class is returned. This is designed to be used with inheritance by joining, in which derived and base class objects have identical ``id`` values. Args: session: database session to operate in
Below is the the instruction that describes the task: ### Input: Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM object classes that are derived from other ORM object classes, the max ``id`` of the lowest base class is returned. This is designed to be used with inheritance by joining, in which derived and base class objects have identical ``id`` values. Args: session: database session to operate in ### Response: def get_max_id(cls, session): """Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM object classes that are derived from other ORM object classes, the max ``id`` of the lowest base class is returned. This is designed to be used with inheritance by joining, in which derived and base class objects have identical ``id`` values. Args: session: database session to operate in """ # sqlalchemy allows only one level of inheritance, so just check this class and all its bases id_base = None for c in [cls] + list(cls.__bases__): for base_class in c.__bases__: if base_class.__name__ == 'Base': if id_base is None: # we found our base class for determining the ID id_base = c else: raise RuntimeError("Multiple base object classes for class " + cls.__name__) # this should never happen if id_base is None: raise RuntimeError("Error searching for base class of " + cls.__name__) # get its max ID max_id = session.query(func.max(id_base.id)).scalar() # if no object is present, None is returned if max_id is None: max_id = 0 return max_id
def ok(prompt='OK ', loc={}, glo={}, cmd=""): ''' Invoke the peforth interpreter. An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="") is like a breakpoint. The prompt indicates which breakpoint it is if there are many. Arguments loc (locals) and glo (globals) along with the prompt are the debuggee's informations that is packed as a tuple (loc,glo,prompt) left on TOS of the FORTH vm when the breakpoint is called. Replace the loc=locals() with loc=dict(locals()) to get a snapshot copy instead of a reference, as well as the glo. 'exit' command to stop debugging. ''' if loc or glo: vm.push((loc,glo,prompt)) # parent's data while True: if cmd == "": # if vm.tick('accept') and not vm.multiple: # Input can be single line (default) or vm.execute('accept') # multiple lines. Press Ctrl-D to toggle cmd = vm.pop().strip() # between the two modes. Place a Ctrl-D elif vm.tick('<accept>') and vm.multiple: # before the last <Enter> key to end the vm.execute('<accept>') # input when in multiple-line mode. cmd = vm.pop().strip() # else: # cmd = input("").strip() # # pass the command line to forth VM if cmd == "": print(prompt, end="") continue elif cmd == chr(4): vm.multiple = not vm.multiple if not vm.multiple: print(prompt, end="") else: vm.dictate(cmd) if vm.multiple: vm.multiple = False # switch back to the normal mode print(prompt, end="") cmd = "" # Master switch vm.exit is a flag of boolean. When it's True # then exit to the caller that usually is python interpreter. if vm.exit: vm.exit = False # Avoid exit immediately when called again break return(vm) # support function cascade
Invoke the peforth interpreter. An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="") is like a breakpoint. The prompt indicates which breakpoint it is if there are many. Arguments loc (locals) and glo (globals) along with the prompt are the debuggee's informations that is packed as a tuple (loc,glo,prompt) left on TOS of the FORTH vm when the breakpoint is called. Replace the loc=locals() with loc=dict(locals()) to get a snapshot copy instead of a reference, as well as the glo. 'exit' command to stop debugging.
Below is the the instruction that describes the task: ### Input: Invoke the peforth interpreter. An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="") is like a breakpoint. The prompt indicates which breakpoint it is if there are many. Arguments loc (locals) and glo (globals) along with the prompt are the debuggee's informations that is packed as a tuple (loc,glo,prompt) left on TOS of the FORTH vm when the breakpoint is called. Replace the loc=locals() with loc=dict(locals()) to get a snapshot copy instead of a reference, as well as the glo. 'exit' command to stop debugging. ### Response: def ok(prompt='OK ', loc={}, glo={}, cmd=""): ''' Invoke the peforth interpreter. An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="") is like a breakpoint. The prompt indicates which breakpoint it is if there are many. Arguments loc (locals) and glo (globals) along with the prompt are the debuggee's informations that is packed as a tuple (loc,glo,prompt) left on TOS of the FORTH vm when the breakpoint is called. Replace the loc=locals() with loc=dict(locals()) to get a snapshot copy instead of a reference, as well as the glo. 'exit' command to stop debugging. ''' if loc or glo: vm.push((loc,glo,prompt)) # parent's data while True: if cmd == "": # if vm.tick('accept') and not vm.multiple: # Input can be single line (default) or vm.execute('accept') # multiple lines. Press Ctrl-D to toggle cmd = vm.pop().strip() # between the two modes. Place a Ctrl-D elif vm.tick('<accept>') and vm.multiple: # before the last <Enter> key to end the vm.execute('<accept>') # input when in multiple-line mode. cmd = vm.pop().strip() # else: # cmd = input("").strip() # # pass the command line to forth VM if cmd == "": print(prompt, end="") continue elif cmd == chr(4): vm.multiple = not vm.multiple if not vm.multiple: print(prompt, end="") else: vm.dictate(cmd) if vm.multiple: vm.multiple = False # switch back to the normal mode print(prompt, end="") cmd = "" # Master switch vm.exit is a flag of boolean. When it's True # then exit to the caller that usually is python interpreter. if vm.exit: vm.exit = False # Avoid exit immediately when called again break return(vm) # support function cascade
def create_prod_build(self, *args, **kwargs): """ Create a production build :param git_uri: str, URI of git repository :param git_ref: str, reference to commit :param git_branch: str, branch name :param user: str, user name :param component: str, not used anymore :param target: str, koji target :param architecture: str, build architecture :param yum_repourls: list, URLs for yum repos :param koji_task_id: int, koji task ID requesting build :param scratch: bool, this is a scratch build :param platform: str, the platform name :param platforms: list<str>, the name of each platform :param release: str, the release value to use :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, numbered arrangement of plugins for orchestration workflow :param signing_intent: str, signing intent of the ODCS composes :param compose_ids: list<int>, ODCS composes used :return: BuildResponse instance """ logger.warning("prod (all-in-one) builds are deprecated, " "please use create_orchestrator_build " "(support will be removed in version 0.54)") return self._do_create_prod_build(*args, **kwargs)
Create a production build :param git_uri: str, URI of git repository :param git_ref: str, reference to commit :param git_branch: str, branch name :param user: str, user name :param component: str, not used anymore :param target: str, koji target :param architecture: str, build architecture :param yum_repourls: list, URLs for yum repos :param koji_task_id: int, koji task ID requesting build :param scratch: bool, this is a scratch build :param platform: str, the platform name :param platforms: list<str>, the name of each platform :param release: str, the release value to use :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, numbered arrangement of plugins for orchestration workflow :param signing_intent: str, signing intent of the ODCS composes :param compose_ids: list<int>, ODCS composes used :return: BuildResponse instance
Below is the the instruction that describes the task: ### Input: Create a production build :param git_uri: str, URI of git repository :param git_ref: str, reference to commit :param git_branch: str, branch name :param user: str, user name :param component: str, not used anymore :param target: str, koji target :param architecture: str, build architecture :param yum_repourls: list, URLs for yum repos :param koji_task_id: int, koji task ID requesting build :param scratch: bool, this is a scratch build :param platform: str, the platform name :param platforms: list<str>, the name of each platform :param release: str, the release value to use :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, numbered arrangement of plugins for orchestration workflow :param signing_intent: str, signing intent of the ODCS composes :param compose_ids: list<int>, ODCS composes used :return: BuildResponse instance ### Response: def create_prod_build(self, *args, **kwargs): """ Create a production build :param git_uri: str, URI of git repository :param git_ref: str, reference to commit :param git_branch: str, branch name :param user: str, user name :param component: str, not used anymore :param target: str, koji target :param architecture: str, build architecture :param yum_repourls: list, URLs for yum repos :param koji_task_id: int, koji task ID requesting build :param scratch: bool, this is a scratch build :param platform: str, the platform name :param platforms: list<str>, the name of each platform :param release: str, the release value to use :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, numbered arrangement of plugins for orchestration workflow :param signing_intent: str, signing intent of the ODCS composes :param compose_ids: list<int>, ODCS composes used :return: BuildResponse instance """ logger.warning("prod (all-in-one) builds are deprecated, " "please use create_orchestrator_build " "(support will be removed in version 0.54)") return self._do_create_prod_build(*args, **kwargs)
def fill_taxid2asscs(taxid2asscs_usr, taxid2asscs_ret): """Fill user taxid2asscs for backward compatibility.""" for taxid, ab_ret in taxid2asscs_ret.items(): taxid2asscs_usr[taxid]['ID2GOs'] = ab_ret['ID2GOs'] taxid2asscs_usr[taxid]['GO2IDs'] = ab_ret['GO2IDs']
Fill user taxid2asscs for backward compatibility.
Below is the the instruction that describes the task: ### Input: Fill user taxid2asscs for backward compatibility. ### Response: def fill_taxid2asscs(taxid2asscs_usr, taxid2asscs_ret): """Fill user taxid2asscs for backward compatibility.""" for taxid, ab_ret in taxid2asscs_ret.items(): taxid2asscs_usr[taxid]['ID2GOs'] = ab_ret['ID2GOs'] taxid2asscs_usr[taxid]['GO2IDs'] = ab_ret['GO2IDs']
def get_entry(self, entry_name, key): """Returns cache entry parameter value by its name. :param str|unicode entry_name: :param key: :return: """ return self.cache[entry_name].get(key, False)
Returns cache entry parameter value by its name. :param str|unicode entry_name: :param key: :return:
Below is the the instruction that describes the task: ### Input: Returns cache entry parameter value by its name. :param str|unicode entry_name: :param key: :return: ### Response: def get_entry(self, entry_name, key): """Returns cache entry parameter value by its name. :param str|unicode entry_name: :param key: :return: """ return self.cache[entry_name].get(key, False)
def appendPath(self, path): """ Appends the inputted path to the end of the sys.path variable, provided the path does not already exist in it. :param path :type str :return bool: success """ # normalize the path path = os.path.normcase(nstr(path)).strip() if path and path != '.' and path not in sys.path: sys.path.append(path) self._addedpaths.append(path) return True return False
Appends the inputted path to the end of the sys.path variable, provided the path does not already exist in it. :param path :type str :return bool: success
Below is the the instruction that describes the task: ### Input: Appends the inputted path to the end of the sys.path variable, provided the path does not already exist in it. :param path :type str :return bool: success ### Response: def appendPath(self, path): """ Appends the inputted path to the end of the sys.path variable, provided the path does not already exist in it. :param path :type str :return bool: success """ # normalize the path path = os.path.normcase(nstr(path)).strip() if path and path != '.' and path not in sys.path: sys.path.append(path) self._addedpaths.append(path) return True return False
def error(self, message): """error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(_sys.stderr) self.exit(2, _('%s: error: %s\n') % (self.prog, message))
error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception.
Below is the the instruction that describes the task: ### Input: error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception. ### Response: def error(self, message): """error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(_sys.stderr) self.exit(2, _('%s: error: %s\n') % (self.prog, message))
def expressionToAST(ex): """Take an expression tree made out of expressions.ExpressionNode, and convert to an AST tree. This is necessary as ExpressionNode overrides many methods to act like a number. """ return ASTNode(ex.astType, ex.astKind, ex.value, [expressionToAST(c) for c in ex.children])
Take an expression tree made out of expressions.ExpressionNode, and convert to an AST tree. This is necessary as ExpressionNode overrides many methods to act like a number.
Below is the the instruction that describes the task: ### Input: Take an expression tree made out of expressions.ExpressionNode, and convert to an AST tree. This is necessary as ExpressionNode overrides many methods to act like a number. ### Response: def expressionToAST(ex): """Take an expression tree made out of expressions.ExpressionNode, and convert to an AST tree. This is necessary as ExpressionNode overrides many methods to act like a number. """ return ASTNode(ex.astType, ex.astKind, ex.value, [expressionToAST(c) for c in ex.children])
def holm(pvals, alpha=.05): """P-values correction with Holm method. Parameters ---------- pvals : array_like Array of p-values of the individual tests. alpha : float Error rate (= alpha level). Returns ------- reject : array, bool True if a hypothesis is rejected, False if not pvals_corrected : array P-values adjusted for multiple hypothesis testing using the Holm procedure. See also -------- bonf : Bonferroni correction fdr : Benjamini/Hochberg and Benjamini/Yekutieli FDR correction Notes ----- From Wikipedia: In statistics, the Holm–Bonferroni method (also called the Holm method) is used to counteract the problem of multiple comparisons. It is intended to control the family-wise error rate and offers a simple test uniformly more powerful than the Bonferroni correction. The Holm adjusted p-values are the running maximum of the sorted p-values divided by the corresponding increasing alpha level: .. math:: \\frac{\\alpha}{n}, \\frac{\\alpha}{n-1}, ..., \\frac{\\alpha}{1} where :math:`n` is the number of test. The full mathematical formula is: .. math:: \\widetilde {p}_{{(i)}}=\\max _{{j\\leq i}}\\left\\{(n-j+1)p_{{(j)}} \\right\\}_{{1}} Note that NaN values are not taken into account in the p-values correction. References ---------- - Holm, S. (1979). A simple sequentially rejective multiple test procedure. Scandinavian journal of statistics, 65-70. - https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method Examples -------- >>> from pingouin import holm >>> pvals = [.50, .003, .32, .054, .0003] >>> reject, pvals_corr = holm(pvals, alpha=.05) >>> print(reject, pvals_corr) [False True False False True] [0.64 0.012 0.64 0.162 0.0015] """ # Convert to array and save original shape pvals = np.asarray(pvals) shape_init = pvals.shape pvals = pvals.ravel() num_nan = np.isnan(pvals).sum() # Sort the (flattened) p-values pvals_sortind = np.argsort(pvals) pvals_sorted = pvals[pvals_sortind] sortrevind = pvals_sortind.argsort() ntests = pvals.size - num_nan # Now we adjust the p-values pvals_corr = np.diag(pvals_sorted * np.arange(ntests, 0, -1)[..., None]) pvals_corr = np.maximum.accumulate(pvals_corr) pvals_corr = np.clip(pvals_corr, None, 1) # And revert to the original shape and order pvals_corr = np.append(pvals_corr, np.full(num_nan, np.nan)) pvals_corrected = pvals_corr[sortrevind].reshape(shape_init) with np.errstate(invalid='ignore'): reject = np.less(pvals_corrected, alpha) return reject, pvals_corrected
P-values correction with Holm method. Parameters ---------- pvals : array_like Array of p-values of the individual tests. alpha : float Error rate (= alpha level). Returns ------- reject : array, bool True if a hypothesis is rejected, False if not pvals_corrected : array P-values adjusted for multiple hypothesis testing using the Holm procedure. See also -------- bonf : Bonferroni correction fdr : Benjamini/Hochberg and Benjamini/Yekutieli FDR correction Notes ----- From Wikipedia: In statistics, the Holm–Bonferroni method (also called the Holm method) is used to counteract the problem of multiple comparisons. It is intended to control the family-wise error rate and offers a simple test uniformly more powerful than the Bonferroni correction. The Holm adjusted p-values are the running maximum of the sorted p-values divided by the corresponding increasing alpha level: .. math:: \\frac{\\alpha}{n}, \\frac{\\alpha}{n-1}, ..., \\frac{\\alpha}{1} where :math:`n` is the number of test. The full mathematical formula is: .. math:: \\widetilde {p}_{{(i)}}=\\max _{{j\\leq i}}\\left\\{(n-j+1)p_{{(j)}} \\right\\}_{{1}} Note that NaN values are not taken into account in the p-values correction. References ---------- - Holm, S. (1979). A simple sequentially rejective multiple test procedure. Scandinavian journal of statistics, 65-70. - https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method Examples -------- >>> from pingouin import holm >>> pvals = [.50, .003, .32, .054, .0003] >>> reject, pvals_corr = holm(pvals, alpha=.05) >>> print(reject, pvals_corr) [False True False False True] [0.64 0.012 0.64 0.162 0.0015]
Below is the the instruction that describes the task: ### Input: P-values correction with Holm method. Parameters ---------- pvals : array_like Array of p-values of the individual tests. alpha : float Error rate (= alpha level). Returns ------- reject : array, bool True if a hypothesis is rejected, False if not pvals_corrected : array P-values adjusted for multiple hypothesis testing using the Holm procedure. See also -------- bonf : Bonferroni correction fdr : Benjamini/Hochberg and Benjamini/Yekutieli FDR correction Notes ----- From Wikipedia: In statistics, the Holm–Bonferroni method (also called the Holm method) is used to counteract the problem of multiple comparisons. It is intended to control the family-wise error rate and offers a simple test uniformly more powerful than the Bonferroni correction. The Holm adjusted p-values are the running maximum of the sorted p-values divided by the corresponding increasing alpha level: .. math:: \\frac{\\alpha}{n}, \\frac{\\alpha}{n-1}, ..., \\frac{\\alpha}{1} where :math:`n` is the number of test. The full mathematical formula is: .. math:: \\widetilde {p}_{{(i)}}=\\max _{{j\\leq i}}\\left\\{(n-j+1)p_{{(j)}} \\right\\}_{{1}} Note that NaN values are not taken into account in the p-values correction. References ---------- - Holm, S. (1979). A simple sequentially rejective multiple test procedure. Scandinavian journal of statistics, 65-70. - https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method Examples -------- >>> from pingouin import holm >>> pvals = [.50, .003, .32, .054, .0003] >>> reject, pvals_corr = holm(pvals, alpha=.05) >>> print(reject, pvals_corr) [False True False False True] [0.64 0.012 0.64 0.162 0.0015] ### Response: def holm(pvals, alpha=.05): """P-values correction with Holm method. Parameters ---------- pvals : array_like Array of p-values of the individual tests. alpha : float Error rate (= alpha level). Returns ------- reject : array, bool True if a hypothesis is rejected, False if not pvals_corrected : array P-values adjusted for multiple hypothesis testing using the Holm procedure. See also -------- bonf : Bonferroni correction fdr : Benjamini/Hochberg and Benjamini/Yekutieli FDR correction Notes ----- From Wikipedia: In statistics, the Holm–Bonferroni method (also called the Holm method) is used to counteract the problem of multiple comparisons. It is intended to control the family-wise error rate and offers a simple test uniformly more powerful than the Bonferroni correction. The Holm adjusted p-values are the running maximum of the sorted p-values divided by the corresponding increasing alpha level: .. math:: \\frac{\\alpha}{n}, \\frac{\\alpha}{n-1}, ..., \\frac{\\alpha}{1} where :math:`n` is the number of test. The full mathematical formula is: .. math:: \\widetilde {p}_{{(i)}}=\\max _{{j\\leq i}}\\left\\{(n-j+1)p_{{(j)}} \\right\\}_{{1}} Note that NaN values are not taken into account in the p-values correction. References ---------- - Holm, S. (1979). A simple sequentially rejective multiple test procedure. Scandinavian journal of statistics, 65-70. - https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method Examples -------- >>> from pingouin import holm >>> pvals = [.50, .003, .32, .054, .0003] >>> reject, pvals_corr = holm(pvals, alpha=.05) >>> print(reject, pvals_corr) [False True False False True] [0.64 0.012 0.64 0.162 0.0015] """ # Convert to array and save original shape pvals = np.asarray(pvals) shape_init = pvals.shape pvals = pvals.ravel() num_nan = np.isnan(pvals).sum() # Sort the (flattened) p-values pvals_sortind = np.argsort(pvals) pvals_sorted = pvals[pvals_sortind] sortrevind = pvals_sortind.argsort() ntests = pvals.size - num_nan # Now we adjust the p-values pvals_corr = np.diag(pvals_sorted * np.arange(ntests, 0, -1)[..., None]) pvals_corr = np.maximum.accumulate(pvals_corr) pvals_corr = np.clip(pvals_corr, None, 1) # And revert to the original shape and order pvals_corr = np.append(pvals_corr, np.full(num_nan, np.nan)) pvals_corrected = pvals_corr[sortrevind].reshape(shape_init) with np.errstate(invalid='ignore'): reject = np.less(pvals_corrected, alpha) return reject, pvals_corrected
def is_integer_array(val): """ Checks whether a variable is a numpy integer array. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a numpy integer array. Otherwise False. """ return is_np_array(val) and issubclass(val.dtype.type, np.integer)
Checks whether a variable is a numpy integer array. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a numpy integer array. Otherwise False.
Below is the the instruction that describes the task: ### Input: Checks whether a variable is a numpy integer array. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a numpy integer array. Otherwise False. ### Response: def is_integer_array(val): """ Checks whether a variable is a numpy integer array. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a numpy integer array. Otherwise False. """ return is_np_array(val) and issubclass(val.dtype.type, np.integer)
def parse_poi_query(north, south, east, west, amenities=None, timeout=180, maxsize=''): """ Parse the Overpass QL query based on the list of amenities. Parameters ---------- north : float Northernmost coordinate from bounding box of the search area. south : float Southernmost coordinate from bounding box of the search area. east : float Easternmost coordinate from bounding box of the search area. west : float Westernmost coordinate of the bounding box of the search area. amenities : list List of amenities that will be used for finding the POIs from the selected area. timeout : int Timeout for the API request. """ if amenities: # Overpass QL template query_template = ('[out:json][timeout:{timeout}]{maxsize};((node["amenity"~"{amenities}"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(way["amenity"~"{amenities}"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(relation["amenity"~"{amenities}"]' '({south:.6f},{west:.6f},{north:.6f},{east:.6f});(._;>;);););out;') # Parse amenties query_str = query_template.format(amenities="|".join(amenities), north=north, south=south, east=east, west=west, timeout=timeout, maxsize=maxsize) else: # Overpass QL template query_template = ('[out:json][timeout:{timeout}]{maxsize};((node["amenity"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(way["amenity"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(relation["amenity"]' '({south:.6f},{west:.6f},{north:.6f},{east:.6f});(._;>;);););out;') # Parse amenties query_str = query_template.format(north=north, south=south, east=east, west=west, timeout=timeout, maxsize=maxsize) return query_str
Parse the Overpass QL query based on the list of amenities. Parameters ---------- north : float Northernmost coordinate from bounding box of the search area. south : float Southernmost coordinate from bounding box of the search area. east : float Easternmost coordinate from bounding box of the search area. west : float Westernmost coordinate of the bounding box of the search area. amenities : list List of amenities that will be used for finding the POIs from the selected area. timeout : int Timeout for the API request.
Below is the the instruction that describes the task: ### Input: Parse the Overpass QL query based on the list of amenities. Parameters ---------- north : float Northernmost coordinate from bounding box of the search area. south : float Southernmost coordinate from bounding box of the search area. east : float Easternmost coordinate from bounding box of the search area. west : float Westernmost coordinate of the bounding box of the search area. amenities : list List of amenities that will be used for finding the POIs from the selected area. timeout : int Timeout for the API request. ### Response: def parse_poi_query(north, south, east, west, amenities=None, timeout=180, maxsize=''): """ Parse the Overpass QL query based on the list of amenities. Parameters ---------- north : float Northernmost coordinate from bounding box of the search area. south : float Southernmost coordinate from bounding box of the search area. east : float Easternmost coordinate from bounding box of the search area. west : float Westernmost coordinate of the bounding box of the search area. amenities : list List of amenities that will be used for finding the POIs from the selected area. timeout : int Timeout for the API request. """ if amenities: # Overpass QL template query_template = ('[out:json][timeout:{timeout}]{maxsize};((node["amenity"~"{amenities}"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(way["amenity"~"{amenities}"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(relation["amenity"~"{amenities}"]' '({south:.6f},{west:.6f},{north:.6f},{east:.6f});(._;>;);););out;') # Parse amenties query_str = query_template.format(amenities="|".join(amenities), north=north, south=south, east=east, west=west, timeout=timeout, maxsize=maxsize) else: # Overpass QL template query_template = ('[out:json][timeout:{timeout}]{maxsize};((node["amenity"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(way["amenity"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(relation["amenity"]' '({south:.6f},{west:.6f},{north:.6f},{east:.6f});(._;>;);););out;') # Parse amenties query_str = query_template.format(north=north, south=south, east=east, west=west, timeout=timeout, maxsize=maxsize) return query_str
def compile(self, model): """Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimization passes. Args: model (DeviceModel): The device model that we should compile this sensor graph for. """ log = SensorLog(InMemoryStorageEngine(model), model) self.sensor_graph = SensorGraph(log, model) allocator = StreamAllocator(self.sensor_graph, model) self._scope_stack = [] # Create a root scope root = RootScope(self.sensor_graph, allocator) self._scope_stack.append(root) for statement in self.statements: statement.execute(self.sensor_graph, self._scope_stack) self.sensor_graph.initialize_remaining_constants() self.sensor_graph.sort_nodes()
Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimization passes. Args: model (DeviceModel): The device model that we should compile this sensor graph for.
Below is the the instruction that describes the task: ### Input: Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimization passes. Args: model (DeviceModel): The device model that we should compile this sensor graph for. ### Response: def compile(self, model): """Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimization passes. Args: model (DeviceModel): The device model that we should compile this sensor graph for. """ log = SensorLog(InMemoryStorageEngine(model), model) self.sensor_graph = SensorGraph(log, model) allocator = StreamAllocator(self.sensor_graph, model) self._scope_stack = [] # Create a root scope root = RootScope(self.sensor_graph, allocator) self._scope_stack.append(root) for statement in self.statements: statement.execute(self.sensor_graph, self._scope_stack) self.sensor_graph.initialize_remaining_constants() self.sensor_graph.sort_nodes()
def connect(cls, resource): """Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource. """ import boto return boto.s3.connect_to_region(cls.get_region(resource))
Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource.
Below is the the instruction that describes the task: ### Input: Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource. ### Response: def connect(cls, resource): """Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource. """ import boto return boto.s3.connect_to_region(cls.get_region(resource))
def make_requests_session(): """ :returns: requests session :rtype: :class:`requests.Session` """ session = requests.Session() version = __import__('steam').__version__ ua = "python-steam/{0} {1}".format(version, session.headers['User-Agent']) session.headers['User-Agent'] = ua return session
:returns: requests session :rtype: :class:`requests.Session`
Below is the the instruction that describes the task: ### Input: :returns: requests session :rtype: :class:`requests.Session` ### Response: def make_requests_session(): """ :returns: requests session :rtype: :class:`requests.Session` """ session = requests.Session() version = __import__('steam').__version__ ua = "python-steam/{0} {1}".format(version, session.headers['User-Agent']) session.headers['User-Agent'] = ua return session
def can_cloak_as(user, other_user): """ Returns true if `user` can cloak as `other_user` """ # check to see if the user is allowed to do this can_cloak = False try: can_cloak = user.can_cloak_as(other_user) except AttributeError as e: try: can_cloak = user.is_staff except AttributeError as e: pass return can_cloak
Returns true if `user` can cloak as `other_user`
Below is the the instruction that describes the task: ### Input: Returns true if `user` can cloak as `other_user` ### Response: def can_cloak_as(user, other_user): """ Returns true if `user` can cloak as `other_user` """ # check to see if the user is allowed to do this can_cloak = False try: can_cloak = user.can_cloak_as(other_user) except AttributeError as e: try: can_cloak = user.is_staff except AttributeError as e: pass return can_cloak
def trigger_dag(args): """ Creates a dag run for the specified dag :param args: :return: """ log = LoggingMixin().log try: message = api_client.trigger_dag(dag_id=args.dag_id, run_id=args.run_id, conf=args.conf, execution_date=args.exec_date) except IOError as err: log.error(err) raise AirflowException(err) log.info(message)
Creates a dag run for the specified dag :param args: :return:
Below is the the instruction that describes the task: ### Input: Creates a dag run for the specified dag :param args: :return: ### Response: def trigger_dag(args): """ Creates a dag run for the specified dag :param args: :return: """ log = LoggingMixin().log try: message = api_client.trigger_dag(dag_id=args.dag_id, run_id=args.run_id, conf=args.conf, execution_date=args.exec_date) except IOError as err: log.error(err) raise AirflowException(err) log.info(message)
def _add_escape_character_for_quote_prime_character(self, text): """ Fix for https://github.com/openatx/facebook-wda/issues/33 Returns: string with properly formated quotes, or non changed text """ if text is not None: if "'" in text: return text.replace("'","\\'") elif '"' in text: return text.replace('"','\\"') else: return text else: return text
Fix for https://github.com/openatx/facebook-wda/issues/33 Returns: string with properly formated quotes, or non changed text
Below is the the instruction that describes the task: ### Input: Fix for https://github.com/openatx/facebook-wda/issues/33 Returns: string with properly formated quotes, or non changed text ### Response: def _add_escape_character_for_quote_prime_character(self, text): """ Fix for https://github.com/openatx/facebook-wda/issues/33 Returns: string with properly formated quotes, or non changed text """ if text is not None: if "'" in text: return text.replace("'","\\'") elif '"' in text: return text.replace('"','\\"') else: return text else: return text
def create_paste(self, content): """Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happens instead. """ r = requests.post( self.endpoint + '/pastes', data={'content': content}, allow_redirects=False) if r.status_code == 302: return r.headers['Location'] if r.status_code == 413: raise MaxLengthExceeded('%d bytes' % len(content)) try: error_message = r.json()['error'] except Exception: error_message = r.text raise UnexpectedError(error_message)
Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happens instead.
Below is the the instruction that describes the task: ### Input: Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happens instead. ### Response: def create_paste(self, content): """Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happens instead. """ r = requests.post( self.endpoint + '/pastes', data={'content': content}, allow_redirects=False) if r.status_code == 302: return r.headers['Location'] if r.status_code == 413: raise MaxLengthExceeded('%d bytes' % len(content)) try: error_message = r.json()['error'] except Exception: error_message = r.text raise UnexpectedError(error_message)
def _splice_index(*key): """ Utility for key management in dig/dug If first elem of key list contains an index[], spread it out as a second numeric index. >>> _splice_index('abc[0]', 'def') ('abc', 0, 'def') >>> _splice_index('abc[a]', 'def') ('abc[a]', 'def') >>> _splice_index('abc[200]', 'def') ('abc', 200, 'def') >>> _splice_index('abc', 'def') ('abc', 'def') >>> _splice_index(0, 'abc', 'def') (0, 'abc', 'def') """ if isinstance(key[0], str): result = rx_index.search(key[0]) if result: return tuple([result.group(1), int(result.group(2))] + list(key[1:])) return key
Utility for key management in dig/dug If first elem of key list contains an index[], spread it out as a second numeric index. >>> _splice_index('abc[0]', 'def') ('abc', 0, 'def') >>> _splice_index('abc[a]', 'def') ('abc[a]', 'def') >>> _splice_index('abc[200]', 'def') ('abc', 200, 'def') >>> _splice_index('abc', 'def') ('abc', 'def') >>> _splice_index(0, 'abc', 'def') (0, 'abc', 'def')
Below is the the instruction that describes the task: ### Input: Utility for key management in dig/dug If first elem of key list contains an index[], spread it out as a second numeric index. >>> _splice_index('abc[0]', 'def') ('abc', 0, 'def') >>> _splice_index('abc[a]', 'def') ('abc[a]', 'def') >>> _splice_index('abc[200]', 'def') ('abc', 200, 'def') >>> _splice_index('abc', 'def') ('abc', 'def') >>> _splice_index(0, 'abc', 'def') (0, 'abc', 'def') ### Response: def _splice_index(*key): """ Utility for key management in dig/dug If first elem of key list contains an index[], spread it out as a second numeric index. >>> _splice_index('abc[0]', 'def') ('abc', 0, 'def') >>> _splice_index('abc[a]', 'def') ('abc[a]', 'def') >>> _splice_index('abc[200]', 'def') ('abc', 200, 'def') >>> _splice_index('abc', 'def') ('abc', 'def') >>> _splice_index(0, 'abc', 'def') (0, 'abc', 'def') """ if isinstance(key[0], str): result = rx_index.search(key[0]) if result: return tuple([result.group(1), int(result.group(2))] + list(key[1:])) return key
def getPIDStatus(jobStoreName): """ Determine the status of a process with a particular pid. Checks to see if a process exists or not. :return: A string indicating the status of the PID of the workflow as stored in the jobstore. :rtype: str """ try: jobstore = Toil.resumeJobStore(jobStoreName) except NoSuchJobStoreException: return 'QUEUED' except NoSuchFileException: return 'QUEUED' try: with jobstore.readSharedFileStream('pid.log') as pidFile: pid = int(pidFile.read()) try: os.kill(pid, 0) # Does not kill process when 0 is passed. except OSError: # Process not found, must be done. return 'COMPLETED' else: return 'RUNNING' except NoSuchFileException: pass return 'QUEUED'
Determine the status of a process with a particular pid. Checks to see if a process exists or not. :return: A string indicating the status of the PID of the workflow as stored in the jobstore. :rtype: str
Below is the the instruction that describes the task: ### Input: Determine the status of a process with a particular pid. Checks to see if a process exists or not. :return: A string indicating the status of the PID of the workflow as stored in the jobstore. :rtype: str ### Response: def getPIDStatus(jobStoreName): """ Determine the status of a process with a particular pid. Checks to see if a process exists or not. :return: A string indicating the status of the PID of the workflow as stored in the jobstore. :rtype: str """ try: jobstore = Toil.resumeJobStore(jobStoreName) except NoSuchJobStoreException: return 'QUEUED' except NoSuchFileException: return 'QUEUED' try: with jobstore.readSharedFileStream('pid.log') as pidFile: pid = int(pidFile.read()) try: os.kill(pid, 0) # Does not kill process when 0 is passed. except OSError: # Process not found, must be done. return 'COMPLETED' else: return 'RUNNING' except NoSuchFileException: pass return 'QUEUED'
def find_interface_by_mac(self, **kwargs): """Find the interface through which a MAC can be reached. Args: mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format. Returns: list[dict]: a list of mac table data. Raises: KeyError: if `mac_address` is not specified. Examples: >>> from pprint import pprint >>> import pynos.device >>> conn = ('10.24.39.211', '22') >>> auth = ('admin', 'password') >>> with pynos.device.Device(conn=conn, auth=auth) as dev: ... x = dev.find_interface_by_mac( ... mac_address='10:23:45:67:89:ab') ... pprint(x) # doctest: +ELLIPSIS [{'interface'...'mac_address'...'state'...'type'...'vlan'...}] """ mac = kwargs.pop('mac_address') results = [x for x in self.mac_table if x['mac_address'] == mac] return results
Find the interface through which a MAC can be reached. Args: mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format. Returns: list[dict]: a list of mac table data. Raises: KeyError: if `mac_address` is not specified. Examples: >>> from pprint import pprint >>> import pynos.device >>> conn = ('10.24.39.211', '22') >>> auth = ('admin', 'password') >>> with pynos.device.Device(conn=conn, auth=auth) as dev: ... x = dev.find_interface_by_mac( ... mac_address='10:23:45:67:89:ab') ... pprint(x) # doctest: +ELLIPSIS [{'interface'...'mac_address'...'state'...'type'...'vlan'...}]
Below is the the instruction that describes the task: ### Input: Find the interface through which a MAC can be reached. Args: mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format. Returns: list[dict]: a list of mac table data. Raises: KeyError: if `mac_address` is not specified. Examples: >>> from pprint import pprint >>> import pynos.device >>> conn = ('10.24.39.211', '22') >>> auth = ('admin', 'password') >>> with pynos.device.Device(conn=conn, auth=auth) as dev: ... x = dev.find_interface_by_mac( ... mac_address='10:23:45:67:89:ab') ... pprint(x) # doctest: +ELLIPSIS [{'interface'...'mac_address'...'state'...'type'...'vlan'...}] ### Response: def find_interface_by_mac(self, **kwargs): """Find the interface through which a MAC can be reached. Args: mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format. Returns: list[dict]: a list of mac table data. Raises: KeyError: if `mac_address` is not specified. Examples: >>> from pprint import pprint >>> import pynos.device >>> conn = ('10.24.39.211', '22') >>> auth = ('admin', 'password') >>> with pynos.device.Device(conn=conn, auth=auth) as dev: ... x = dev.find_interface_by_mac( ... mac_address='10:23:45:67:89:ab') ... pprint(x) # doctest: +ELLIPSIS [{'interface'...'mac_address'...'state'...'type'...'vlan'...}] """ mac = kwargs.pop('mac_address') results = [x for x in self.mac_table if x['mac_address'] == mac] return results
def transpose(self): """Create a transpose of this matrix.""" ma4 = Matrix4(self.get_col(0), self.get_col(1), self.get_col(2), self.get_col(3)) return ma4
Create a transpose of this matrix.
Below is the the instruction that describes the task: ### Input: Create a transpose of this matrix. ### Response: def transpose(self): """Create a transpose of this matrix.""" ma4 = Matrix4(self.get_col(0), self.get_col(1), self.get_col(2), self.get_col(3)) return ma4
def auth_none(self, username): """ Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the L{BadAuthenticationType} exception raised. @param username: the username to authenticate as @type username: string @return: list of auth types permissible for the next stage of authentication (normally empty) @rtype: list @raise BadAuthenticationType: if "none" authentication isn't allowed by the server for this user @raise SSHException: if the authentication failed due to a network error @since: 1.5 """ if (not self.active) or (not self.initial_kex_done): raise SSHException('No existing session') my_event = threading.Event() self.auth_handler = AuthHandler(self) self.auth_handler.auth_none(username, my_event) return self.auth_handler.wait_for_response(my_event)
Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the L{BadAuthenticationType} exception raised. @param username: the username to authenticate as @type username: string @return: list of auth types permissible for the next stage of authentication (normally empty) @rtype: list @raise BadAuthenticationType: if "none" authentication isn't allowed by the server for this user @raise SSHException: if the authentication failed due to a network error @since: 1.5
Below is the the instruction that describes the task: ### Input: Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the L{BadAuthenticationType} exception raised. @param username: the username to authenticate as @type username: string @return: list of auth types permissible for the next stage of authentication (normally empty) @rtype: list @raise BadAuthenticationType: if "none" authentication isn't allowed by the server for this user @raise SSHException: if the authentication failed due to a network error @since: 1.5 ### Response: def auth_none(self, username): """ Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the L{BadAuthenticationType} exception raised. @param username: the username to authenticate as @type username: string @return: list of auth types permissible for the next stage of authentication (normally empty) @rtype: list @raise BadAuthenticationType: if "none" authentication isn't allowed by the server for this user @raise SSHException: if the authentication failed due to a network error @since: 1.5 """ if (not self.active) or (not self.initial_kex_done): raise SSHException('No existing session') my_event = threading.Event() self.auth_handler = AuthHandler(self) self.auth_handler.auth_none(username, my_event) return self.auth_handler.wait_for_response(my_event)
def visit_UnaryOp(self, node): """ Update range with given unary operation. >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse(''' ... def foo(): ... a = 2 ... c = -a ... d = ~a ... f = +a ... e = not a''') >>> pm = passmanager.PassManager("test") >>> res = pm.gather(RangeValues, node) >>> res['f'] Interval(low=2, high=2) >>> res['c'] Interval(low=-2, high=-2) >>> res['d'] Interval(low=-3, high=-3) >>> res['e'] Interval(low=0, high=1) """ res = self.visit(node.operand) if isinstance(node.op, ast.Not): res = Interval(0, 1) elif(isinstance(node.op, ast.Invert) and isinstance(res.high, int) and isinstance(res.low, int)): res = Interval(~res.high, ~res.low) elif isinstance(node.op, ast.UAdd): pass elif isinstance(node.op, ast.USub): res = Interval(-res.high, -res.low) else: res = UNKNOWN_RANGE return self.add(node, res)
Update range with given unary operation. >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse(''' ... def foo(): ... a = 2 ... c = -a ... d = ~a ... f = +a ... e = not a''') >>> pm = passmanager.PassManager("test") >>> res = pm.gather(RangeValues, node) >>> res['f'] Interval(low=2, high=2) >>> res['c'] Interval(low=-2, high=-2) >>> res['d'] Interval(low=-3, high=-3) >>> res['e'] Interval(low=0, high=1)
Below is the the instruction that describes the task: ### Input: Update range with given unary operation. >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse(''' ... def foo(): ... a = 2 ... c = -a ... d = ~a ... f = +a ... e = not a''') >>> pm = passmanager.PassManager("test") >>> res = pm.gather(RangeValues, node) >>> res['f'] Interval(low=2, high=2) >>> res['c'] Interval(low=-2, high=-2) >>> res['d'] Interval(low=-3, high=-3) >>> res['e'] Interval(low=0, high=1) ### Response: def visit_UnaryOp(self, node): """ Update range with given unary operation. >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse(''' ... def foo(): ... a = 2 ... c = -a ... d = ~a ... f = +a ... e = not a''') >>> pm = passmanager.PassManager("test") >>> res = pm.gather(RangeValues, node) >>> res['f'] Interval(low=2, high=2) >>> res['c'] Interval(low=-2, high=-2) >>> res['d'] Interval(low=-3, high=-3) >>> res['e'] Interval(low=0, high=1) """ res = self.visit(node.operand) if isinstance(node.op, ast.Not): res = Interval(0, 1) elif(isinstance(node.op, ast.Invert) and isinstance(res.high, int) and isinstance(res.low, int)): res = Interval(~res.high, ~res.low) elif isinstance(node.op, ast.UAdd): pass elif isinstance(node.op, ast.USub): res = Interval(-res.high, -res.low) else: res = UNKNOWN_RANGE return self.add(node, res)
def split_quantities(data, units='units', magnitude='magnitude', list_of_dicts=False): """ split pint.Quantity objects into <unit,magnitude> pairs Parameters ---------- data : dict units : str name for units key magnitude : str name for magnitude key list_of_dicts: bool treat list of dicts as additional branches Examples -------- >>> from pprint import pprint >>> from pint import UnitRegistry >>> ureg = UnitRegistry() >>> Q = ureg.Quantity >>> qdata = {'energy': Q(1.602e-22, 'kilojoule'), ... 'meta': None, ... 'other': {'y': Q([4,5,6], 'nanometer')}, ... 'x': Q([1,2,3], 'nanometer'), ... 'y': Q([8,9,10], 'meter')} ... >>> split_data = split_quantities(qdata) >>> pprint(split_data) {'energy': {'magnitude': 1.602e-22, 'units': 'kilojoule'}, 'meta': None, 'other': {'y': {'magnitude': array([4, 5, 6]), 'units': 'nanometer'}}, 'x': {'magnitude': array([1, 2, 3]), 'units': 'nanometer'}, 'y': {'magnitude': array([ 8, 9, 10]), 'units': 'meter'}} """ try: from pint.quantity import _Quantity except ImportError: raise ImportError('please install pint to use this module') list_of_dicts = '__list__' if list_of_dicts else None data_flatten = flatten(data, list_of_dicts=list_of_dicts) for key, val in data_flatten.items(): if isinstance(val, _Quantity): data_flatten[key] = {units: str(val.units), magnitude: val.magnitude} return unflatten(data_flatten, list_of_dicts=list_of_dicts)
split pint.Quantity objects into <unit,magnitude> pairs Parameters ---------- data : dict units : str name for units key magnitude : str name for magnitude key list_of_dicts: bool treat list of dicts as additional branches Examples -------- >>> from pprint import pprint >>> from pint import UnitRegistry >>> ureg = UnitRegistry() >>> Q = ureg.Quantity >>> qdata = {'energy': Q(1.602e-22, 'kilojoule'), ... 'meta': None, ... 'other': {'y': Q([4,5,6], 'nanometer')}, ... 'x': Q([1,2,3], 'nanometer'), ... 'y': Q([8,9,10], 'meter')} ... >>> split_data = split_quantities(qdata) >>> pprint(split_data) {'energy': {'magnitude': 1.602e-22, 'units': 'kilojoule'}, 'meta': None, 'other': {'y': {'magnitude': array([4, 5, 6]), 'units': 'nanometer'}}, 'x': {'magnitude': array([1, 2, 3]), 'units': 'nanometer'}, 'y': {'magnitude': array([ 8, 9, 10]), 'units': 'meter'}}
Below is the the instruction that describes the task: ### Input: split pint.Quantity objects into <unit,magnitude> pairs Parameters ---------- data : dict units : str name for units key magnitude : str name for magnitude key list_of_dicts: bool treat list of dicts as additional branches Examples -------- >>> from pprint import pprint >>> from pint import UnitRegistry >>> ureg = UnitRegistry() >>> Q = ureg.Quantity >>> qdata = {'energy': Q(1.602e-22, 'kilojoule'), ... 'meta': None, ... 'other': {'y': Q([4,5,6], 'nanometer')}, ... 'x': Q([1,2,3], 'nanometer'), ... 'y': Q([8,9,10], 'meter')} ... >>> split_data = split_quantities(qdata) >>> pprint(split_data) {'energy': {'magnitude': 1.602e-22, 'units': 'kilojoule'}, 'meta': None, 'other': {'y': {'magnitude': array([4, 5, 6]), 'units': 'nanometer'}}, 'x': {'magnitude': array([1, 2, 3]), 'units': 'nanometer'}, 'y': {'magnitude': array([ 8, 9, 10]), 'units': 'meter'}} ### Response: def split_quantities(data, units='units', magnitude='magnitude', list_of_dicts=False): """ split pint.Quantity objects into <unit,magnitude> pairs Parameters ---------- data : dict units : str name for units key magnitude : str name for magnitude key list_of_dicts: bool treat list of dicts as additional branches Examples -------- >>> from pprint import pprint >>> from pint import UnitRegistry >>> ureg = UnitRegistry() >>> Q = ureg.Quantity >>> qdata = {'energy': Q(1.602e-22, 'kilojoule'), ... 'meta': None, ... 'other': {'y': Q([4,5,6], 'nanometer')}, ... 'x': Q([1,2,3], 'nanometer'), ... 'y': Q([8,9,10], 'meter')} ... >>> split_data = split_quantities(qdata) >>> pprint(split_data) {'energy': {'magnitude': 1.602e-22, 'units': 'kilojoule'}, 'meta': None, 'other': {'y': {'magnitude': array([4, 5, 6]), 'units': 'nanometer'}}, 'x': {'magnitude': array([1, 2, 3]), 'units': 'nanometer'}, 'y': {'magnitude': array([ 8, 9, 10]), 'units': 'meter'}} """ try: from pint.quantity import _Quantity except ImportError: raise ImportError('please install pint to use this module') list_of_dicts = '__list__' if list_of_dicts else None data_flatten = flatten(data, list_of_dicts=list_of_dicts) for key, val in data_flatten.items(): if isinstance(val, _Quantity): data_flatten[key] = {units: str(val.units), magnitude: val.magnitude} return unflatten(data_flatten, list_of_dicts=list_of_dicts)
def _decode_module_id(self, module_id): """ decode module id to string based on @antirez moduleTypeNameByID function from redis/src/module.c :param module_id: 64bit integer :return: string """ name = [''] * 9 module_id >>= 10 for i in reversed(range(9)): name[i] = self.charset[module_id & 63] module_id >>= 6 return ''.join(name)
decode module id to string based on @antirez moduleTypeNameByID function from redis/src/module.c :param module_id: 64bit integer :return: string
Below is the the instruction that describes the task: ### Input: decode module id to string based on @antirez moduleTypeNameByID function from redis/src/module.c :param module_id: 64bit integer :return: string ### Response: def _decode_module_id(self, module_id): """ decode module id to string based on @antirez moduleTypeNameByID function from redis/src/module.c :param module_id: 64bit integer :return: string """ name = [''] * 9 module_id >>= 10 for i in reversed(range(9)): name[i] = self.charset[module_id & 63] module_id >>= 6 return ''.join(name)
def any_i18n(*args): """ Return True if any argument appears to be an i18n string. """ for a in args: if a is not None and not isinstance(a, str): return True return False
Return True if any argument appears to be an i18n string.
Below is the the instruction that describes the task: ### Input: Return True if any argument appears to be an i18n string. ### Response: def any_i18n(*args): """ Return True if any argument appears to be an i18n string. """ for a in args: if a is not None and not isinstance(a, str): return True return False
def routers_updated(self, context, routers, operation=None, data=None, shuffle_agents=False): """Notify cfg agents about configuration changes to routers. This includes operations performed on the router like when a router interface is added or removed. """ if routers: self._notification(context, 'routers_updated', routers, operation, shuffle_agents)
Notify cfg agents about configuration changes to routers. This includes operations performed on the router like when a router interface is added or removed.
Below is the the instruction that describes the task: ### Input: Notify cfg agents about configuration changes to routers. This includes operations performed on the router like when a router interface is added or removed. ### Response: def routers_updated(self, context, routers, operation=None, data=None, shuffle_agents=False): """Notify cfg agents about configuration changes to routers. This includes operations performed on the router like when a router interface is added or removed. """ if routers: self._notification(context, 'routers_updated', routers, operation, shuffle_agents)
def getDigitalMaximum(self, chn=None): """ Returns the maximum digital value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getDigitalMaximum(0) 32767 >>> f._close() >>> del f """ if chn is not None: if 0 <= chn < self.signals_in_file: return self.digital_max(chn) else: return 0 else: digMax = np.zeros(self.signals_in_file) for i in np.arange(self.signals_in_file): digMax[i] = self.digital_max(i) return digMax
Returns the maximum digital value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getDigitalMaximum(0) 32767 >>> f._close() >>> del f
Below is the the instruction that describes the task: ### Input: Returns the maximum digital value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getDigitalMaximum(0) 32767 >>> f._close() >>> del f ### Response: def getDigitalMaximum(self, chn=None): """ Returns the maximum digital value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getDigitalMaximum(0) 32767 >>> f._close() >>> del f """ if chn is not None: if 0 <= chn < self.signals_in_file: return self.digital_max(chn) else: return 0 else: digMax = np.zeros(self.signals_in_file) for i in np.arange(self.signals_in_file): digMax[i] = self.digital_max(i) return digMax
def encode(self, obj): """ Take a Python object and return it as a tuple (value, value_type), a blob and a one-char code for what type it is """ if self._is_valid_mysql_bigint(obj): return obj, 'i' value = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) value_type = 'p' if ( self._compress_min_length and len(value) >= self._compress_min_length ): value = zlib.compress(value, self._compress_level) value_type = 'z' return value, value_type
Take a Python object and return it as a tuple (value, value_type), a blob and a one-char code for what type it is
Below is the the instruction that describes the task: ### Input: Take a Python object and return it as a tuple (value, value_type), a blob and a one-char code for what type it is ### Response: def encode(self, obj): """ Take a Python object and return it as a tuple (value, value_type), a blob and a one-char code for what type it is """ if self._is_valid_mysql_bigint(obj): return obj, 'i' value = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) value_type = 'p' if ( self._compress_min_length and len(value) >= self._compress_min_length ): value = zlib.compress(value, self._compress_level) value_type = 'z' return value, value_type
def store(self, msg, stuff_to_store, *args, **kwargs): """ Stores a particular item to disk. The storage service always accepts these parameters: :param trajectory_name: Name or current trajectory and name of top node in hdf5 file :param filename: Name of the hdf5 file :param file_title: If file needs to be created, assigns a title to the file. The following messages (first argument msg) are understood and the following arguments can be provided in combination with the message: * :const:`pypet.pypetconstants.PREPARE_MERGE` ('PREPARE_MERGE'): Called to prepare a trajectory for merging, see also 'MERGE' below. Will also be called if merging cannot happen within the same hdf5 file. Stores already enlarged parameters and updates meta information. :param stuff_to_store: Trajectory that is about to be extended by another one :param changed_parameters: List containing all parameters that were enlarged due to merging :param old_length: Old length of trajectory before merge * :const:`pypet.pypetconstants.MERGE` ('MERGE') Note that before merging within HDF5 file, the storage service will be called with msg='PREPARE_MERGE' before, see above. Raises a ValueError if the two trajectories are not stored within the very same hdf5 file. Then the current trajectory needs to perform the merge slowly item by item. Merges two trajectories, parameters are: :param stuff_to_store: The trajectory data is merged into :param other_trajectory_name: Name of the other trajectory :param rename_dict: Dictionary containing the old result and derived parameter names in the other trajectory and their new names in the current trajectory. :param move_nodes: Whether to move the nodes from the other to the current trajectory :param delete_trajectory: Whether to delete the other trajectory after merging. * :const:`pypet.pypetconstants.BACKUP` ('BACKUP') :param stuff_to_store: Trajectory to be backed up :param backup_filename: Name of file where to store the backup. If None the backup file will be in the same folder as your hdf5 file and named 'backup_XXXXX.hdf5' where 'XXXXX' is the name of your current trajectory. * :const:`pypet.pypetconstants.TRAJECTORY` ('TRAJECTORY') Stores the whole trajectory :param stuff_to_store: The trajectory to be stored :param only_init: If you just want to initialise the store. If yes, only meta information about the trajectory is stored and none of the nodes/leaves within the trajectory. :param store_data: How to store data, the following settings are understood: :const:`pypet.pypetconstants.STORE_NOTHING`: (0) Nothing is stored :const:`pypet.pypetconstants.STORE_DATA_SKIPPING`: (1) Data of not already stored nodes is stored :const:`pypet.pypetconstants.STORE_DATA`: (2) Data of all nodes is stored. However, existing data on disk is left untouched. :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3) Data of all nodes is stored and data on disk is overwritten. May lead to fragmentation of the HDF5 file. The user is adviced to recompress the file manually later on. * :const:`pypet.pypetconstants.SINGLE_RUN` ('SINGLE_RUN') :param stuff_to_store: The trajectory :param store_data: How to store data see above :param store_final: If final meta info should be stored * :const:`pypet.pypetconstants.LEAF` Stores a parameter or result Note that everything that is supported by the storage service and that is stored to disk will be perfectly recovered. For instance, you store a tuple of numpy 32 bit integers, you will get a tuple of numpy 32 bit integers after loading independent of the platform! :param stuff_to_sore: Result or parameter to store In order to determine what to store, the function '_store' of the parameter or result is called. This function returns a dictionary with name keys and data to store as values. In order to determine how to store the data, the storage flags are considered, see below. The function '_store' has to return a dictionary containing values only from the following objects: * python natives (int, long, str, bool, float, complex), * numpy natives, arrays and matrices of type np.int8-64, np.uint8-64, np.float32-64, np.complex, np.str * python lists and tuples of the previous types (python natives + numpy natives and arrays) Lists and tuples are not allowed to be nested and must be homogeneous, i.e. only contain data of one particular type. Only integers, or only floats, etc. * python dictionaries of the previous types (not nested!), data can be heterogeneous, keys must be strings. For example, one key-value-pair of string and int and one key-value pair of string and float, and so on. * pandas DataFrames_ * :class:`~pypet.parameter.ObjectTable` .. _DataFrames: http://pandas.pydata.org/pandas-docs/dev/dsintro.html#dataframe The keys from the '_store' dictionaries determine how the data will be named in the hdf5 file. :param store_data: How to store the data, see above for a descitpion. :param store_flags: Flags describing how to store data. :const:`~pypet.HDF5StorageService.ARRAY` ('ARRAY') Store stuff as array :const:`~pypet.HDF5StorageService.CARRAY` ('CARRAY') Store stuff as carray :const:`~pypet.HDF5StorageService.TABLE` ('TABLE') Store stuff as pytable :const:`~pypet.HDF5StorageService.DICT` ('DICT') Store stuff as pytable but reconstructs it later as dictionary on loading :const:`~pypet.HDF%StorageService.FRAME` ('FRAME') Store stuff as pandas data frame Storage flags can also be provided by the parameters and results themselves if they implement a function '_store_flags' that returns a dictionary with the names of the data to store as keys and the flags as values. If no storage flags are provided, they are automatically inferred from the data. See :const:`pypet.HDF5StorageService.TYPE_FLAG_MAPPING` for the mapping from type to flag. :param overwrite: Can be used if parts of a leaf should be replaced. Either a list of HDF5 names or `True` if this should account for all. * :const:`pypet.pypetconstants.DELETE` ('DELETE') Removes an item from disk. Empty group nodes, results and non-explored parameters can be removed. :param stuff_to_store: The item to be removed. :param delete_only: Potential list of parts of a leaf node that should be deleted. :param remove_from_item: If `delete_only` is used, whether deleted nodes should also be erased from the leaf nodes themseleves. :param recursive: If you want to delete a group node you can recursively delete all its children. * :const:`pypet.pypetconstants.GROUP` ('GROUP') :param stuff_to_store: The group to store :param store_data: How to store data :param recursive: To recursively load everything below. :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.TREE` Stores a single node or a full subtree :param stuff_to_store: Node to store :param store_data: How to store data :param recursive: Whether to store recursively the whole sub-tree :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.DELETE_LINK` Deletes a link from hard drive :param name: The full colon separated name of the link * :const:`pypet.pypetconstants.LIST` .. _store-lists: Stores several items at once :param stuff_to_store: Iterable whose items are to be stored. Iterable must contain tuples, for example `[(msg1,item1,arg1,kwargs1),(msg2,item2,arg2,kwargs2),...]` * :const:`pypet.pypetconstants.ACCESS_DATA` Requests and manipulates data within the storage. Storage must be open. :param stuff_to_store: A colon separated name to the data path :param item_name: The name of the data item to interact with :param request: A functional request in form of a string :param args: Positional arguments passed to the reques :param kwargs: Keyword arguments passed to the request * :const:`pypet.pypetconstants.OPEN_FILE` Opens the HDF5 file and keeps it open :param stuff_to_store: ``None`` * :const:`pypet.pypetconstants.CLOSE_FILE` Closes an HDF5 file that was kept open, must be open before. :param stuff_to_store: ``None`` * :const:`pypet.pypetconstants.FLUSH` Flushes an open file, must be open before. :param stuff_to_store: ``None`` :raises: NoSuchServiceError if message or data is not understood """ opened = True try: opened = self._srvc_opening_routine('a', msg, kwargs) if msg == pypetconstants.MERGE: self._trj_merge_trajectories(*args, **kwargs) elif msg == pypetconstants.BACKUP: self._trj_backup_trajectory(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.PREPARE_MERGE: self._trj_prepare_merge(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.TRAJECTORY: self._trj_store_trajectory(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.SINGLE_RUN: self._srn_store_single_run(stuff_to_store, *args, **kwargs) elif msg in pypetconstants.LEAF: self._prm_store_parameter_or_result(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.DELETE: self._all_delete_parameter_or_result_or_group(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.GROUP: self._grp_store_group(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.TREE: self._tree_store_sub_branch(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.DELETE_LINK: self._lnk_delete_link(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.LIST: self._srvc_store_several_items(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.ACCESS_DATA: return self._hdf5_interact_with_data(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.OPEN_FILE: opened = False # Wee need to keep the file open to allow later interaction self._keep_open = True self._node_processing_timer.active = False # This might be open quite long # so we don't want to display horribly long opening times elif msg == pypetconstants.CLOSE_FILE: opened = True # Simply conduct the closing routine afterwards self._keep_open = False elif msg == pypetconstants.FLUSH: self._hdf5file.flush() else: raise pex.NoSuchServiceError('I do not know how to handle `%s`' % msg) except: self._logger.error('Failed storing `%s`' % str(stuff_to_store)) raise finally: self._srvc_closing_routine(opened)
Stores a particular item to disk. The storage service always accepts these parameters: :param trajectory_name: Name or current trajectory and name of top node in hdf5 file :param filename: Name of the hdf5 file :param file_title: If file needs to be created, assigns a title to the file. The following messages (first argument msg) are understood and the following arguments can be provided in combination with the message: * :const:`pypet.pypetconstants.PREPARE_MERGE` ('PREPARE_MERGE'): Called to prepare a trajectory for merging, see also 'MERGE' below. Will also be called if merging cannot happen within the same hdf5 file. Stores already enlarged parameters and updates meta information. :param stuff_to_store: Trajectory that is about to be extended by another one :param changed_parameters: List containing all parameters that were enlarged due to merging :param old_length: Old length of trajectory before merge * :const:`pypet.pypetconstants.MERGE` ('MERGE') Note that before merging within HDF5 file, the storage service will be called with msg='PREPARE_MERGE' before, see above. Raises a ValueError if the two trajectories are not stored within the very same hdf5 file. Then the current trajectory needs to perform the merge slowly item by item. Merges two trajectories, parameters are: :param stuff_to_store: The trajectory data is merged into :param other_trajectory_name: Name of the other trajectory :param rename_dict: Dictionary containing the old result and derived parameter names in the other trajectory and their new names in the current trajectory. :param move_nodes: Whether to move the nodes from the other to the current trajectory :param delete_trajectory: Whether to delete the other trajectory after merging. * :const:`pypet.pypetconstants.BACKUP` ('BACKUP') :param stuff_to_store: Trajectory to be backed up :param backup_filename: Name of file where to store the backup. If None the backup file will be in the same folder as your hdf5 file and named 'backup_XXXXX.hdf5' where 'XXXXX' is the name of your current trajectory. * :const:`pypet.pypetconstants.TRAJECTORY` ('TRAJECTORY') Stores the whole trajectory :param stuff_to_store: The trajectory to be stored :param only_init: If you just want to initialise the store. If yes, only meta information about the trajectory is stored and none of the nodes/leaves within the trajectory. :param store_data: How to store data, the following settings are understood: :const:`pypet.pypetconstants.STORE_NOTHING`: (0) Nothing is stored :const:`pypet.pypetconstants.STORE_DATA_SKIPPING`: (1) Data of not already stored nodes is stored :const:`pypet.pypetconstants.STORE_DATA`: (2) Data of all nodes is stored. However, existing data on disk is left untouched. :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3) Data of all nodes is stored and data on disk is overwritten. May lead to fragmentation of the HDF5 file. The user is adviced to recompress the file manually later on. * :const:`pypet.pypetconstants.SINGLE_RUN` ('SINGLE_RUN') :param stuff_to_store: The trajectory :param store_data: How to store data see above :param store_final: If final meta info should be stored * :const:`pypet.pypetconstants.LEAF` Stores a parameter or result Note that everything that is supported by the storage service and that is stored to disk will be perfectly recovered. For instance, you store a tuple of numpy 32 bit integers, you will get a tuple of numpy 32 bit integers after loading independent of the platform! :param stuff_to_sore: Result or parameter to store In order to determine what to store, the function '_store' of the parameter or result is called. This function returns a dictionary with name keys and data to store as values. In order to determine how to store the data, the storage flags are considered, see below. The function '_store' has to return a dictionary containing values only from the following objects: * python natives (int, long, str, bool, float, complex), * numpy natives, arrays and matrices of type np.int8-64, np.uint8-64, np.float32-64, np.complex, np.str * python lists and tuples of the previous types (python natives + numpy natives and arrays) Lists and tuples are not allowed to be nested and must be homogeneous, i.e. only contain data of one particular type. Only integers, or only floats, etc. * python dictionaries of the previous types (not nested!), data can be heterogeneous, keys must be strings. For example, one key-value-pair of string and int and one key-value pair of string and float, and so on. * pandas DataFrames_ * :class:`~pypet.parameter.ObjectTable` .. _DataFrames: http://pandas.pydata.org/pandas-docs/dev/dsintro.html#dataframe The keys from the '_store' dictionaries determine how the data will be named in the hdf5 file. :param store_data: How to store the data, see above for a descitpion. :param store_flags: Flags describing how to store data. :const:`~pypet.HDF5StorageService.ARRAY` ('ARRAY') Store stuff as array :const:`~pypet.HDF5StorageService.CARRAY` ('CARRAY') Store stuff as carray :const:`~pypet.HDF5StorageService.TABLE` ('TABLE') Store stuff as pytable :const:`~pypet.HDF5StorageService.DICT` ('DICT') Store stuff as pytable but reconstructs it later as dictionary on loading :const:`~pypet.HDF%StorageService.FRAME` ('FRAME') Store stuff as pandas data frame Storage flags can also be provided by the parameters and results themselves if they implement a function '_store_flags' that returns a dictionary with the names of the data to store as keys and the flags as values. If no storage flags are provided, they are automatically inferred from the data. See :const:`pypet.HDF5StorageService.TYPE_FLAG_MAPPING` for the mapping from type to flag. :param overwrite: Can be used if parts of a leaf should be replaced. Either a list of HDF5 names or `True` if this should account for all. * :const:`pypet.pypetconstants.DELETE` ('DELETE') Removes an item from disk. Empty group nodes, results and non-explored parameters can be removed. :param stuff_to_store: The item to be removed. :param delete_only: Potential list of parts of a leaf node that should be deleted. :param remove_from_item: If `delete_only` is used, whether deleted nodes should also be erased from the leaf nodes themseleves. :param recursive: If you want to delete a group node you can recursively delete all its children. * :const:`pypet.pypetconstants.GROUP` ('GROUP') :param stuff_to_store: The group to store :param store_data: How to store data :param recursive: To recursively load everything below. :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.TREE` Stores a single node or a full subtree :param stuff_to_store: Node to store :param store_data: How to store data :param recursive: Whether to store recursively the whole sub-tree :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.DELETE_LINK` Deletes a link from hard drive :param name: The full colon separated name of the link * :const:`pypet.pypetconstants.LIST` .. _store-lists: Stores several items at once :param stuff_to_store: Iterable whose items are to be stored. Iterable must contain tuples, for example `[(msg1,item1,arg1,kwargs1),(msg2,item2,arg2,kwargs2),...]` * :const:`pypet.pypetconstants.ACCESS_DATA` Requests and manipulates data within the storage. Storage must be open. :param stuff_to_store: A colon separated name to the data path :param item_name: The name of the data item to interact with :param request: A functional request in form of a string :param args: Positional arguments passed to the reques :param kwargs: Keyword arguments passed to the request * :const:`pypet.pypetconstants.OPEN_FILE` Opens the HDF5 file and keeps it open :param stuff_to_store: ``None`` * :const:`pypet.pypetconstants.CLOSE_FILE` Closes an HDF5 file that was kept open, must be open before. :param stuff_to_store: ``None`` * :const:`pypet.pypetconstants.FLUSH` Flushes an open file, must be open before. :param stuff_to_store: ``None`` :raises: NoSuchServiceError if message or data is not understood
Below is the the instruction that describes the task: ### Input: Stores a particular item to disk. The storage service always accepts these parameters: :param trajectory_name: Name or current trajectory and name of top node in hdf5 file :param filename: Name of the hdf5 file :param file_title: If file needs to be created, assigns a title to the file. The following messages (first argument msg) are understood and the following arguments can be provided in combination with the message: * :const:`pypet.pypetconstants.PREPARE_MERGE` ('PREPARE_MERGE'): Called to prepare a trajectory for merging, see also 'MERGE' below. Will also be called if merging cannot happen within the same hdf5 file. Stores already enlarged parameters and updates meta information. :param stuff_to_store: Trajectory that is about to be extended by another one :param changed_parameters: List containing all parameters that were enlarged due to merging :param old_length: Old length of trajectory before merge * :const:`pypet.pypetconstants.MERGE` ('MERGE') Note that before merging within HDF5 file, the storage service will be called with msg='PREPARE_MERGE' before, see above. Raises a ValueError if the two trajectories are not stored within the very same hdf5 file. Then the current trajectory needs to perform the merge slowly item by item. Merges two trajectories, parameters are: :param stuff_to_store: The trajectory data is merged into :param other_trajectory_name: Name of the other trajectory :param rename_dict: Dictionary containing the old result and derived parameter names in the other trajectory and their new names in the current trajectory. :param move_nodes: Whether to move the nodes from the other to the current trajectory :param delete_trajectory: Whether to delete the other trajectory after merging. * :const:`pypet.pypetconstants.BACKUP` ('BACKUP') :param stuff_to_store: Trajectory to be backed up :param backup_filename: Name of file where to store the backup. If None the backup file will be in the same folder as your hdf5 file and named 'backup_XXXXX.hdf5' where 'XXXXX' is the name of your current trajectory. * :const:`pypet.pypetconstants.TRAJECTORY` ('TRAJECTORY') Stores the whole trajectory :param stuff_to_store: The trajectory to be stored :param only_init: If you just want to initialise the store. If yes, only meta information about the trajectory is stored and none of the nodes/leaves within the trajectory. :param store_data: How to store data, the following settings are understood: :const:`pypet.pypetconstants.STORE_NOTHING`: (0) Nothing is stored :const:`pypet.pypetconstants.STORE_DATA_SKIPPING`: (1) Data of not already stored nodes is stored :const:`pypet.pypetconstants.STORE_DATA`: (2) Data of all nodes is stored. However, existing data on disk is left untouched. :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3) Data of all nodes is stored and data on disk is overwritten. May lead to fragmentation of the HDF5 file. The user is adviced to recompress the file manually later on. * :const:`pypet.pypetconstants.SINGLE_RUN` ('SINGLE_RUN') :param stuff_to_store: The trajectory :param store_data: How to store data see above :param store_final: If final meta info should be stored * :const:`pypet.pypetconstants.LEAF` Stores a parameter or result Note that everything that is supported by the storage service and that is stored to disk will be perfectly recovered. For instance, you store a tuple of numpy 32 bit integers, you will get a tuple of numpy 32 bit integers after loading independent of the platform! :param stuff_to_sore: Result or parameter to store In order to determine what to store, the function '_store' of the parameter or result is called. This function returns a dictionary with name keys and data to store as values. In order to determine how to store the data, the storage flags are considered, see below. The function '_store' has to return a dictionary containing values only from the following objects: * python natives (int, long, str, bool, float, complex), * numpy natives, arrays and matrices of type np.int8-64, np.uint8-64, np.float32-64, np.complex, np.str * python lists and tuples of the previous types (python natives + numpy natives and arrays) Lists and tuples are not allowed to be nested and must be homogeneous, i.e. only contain data of one particular type. Only integers, or only floats, etc. * python dictionaries of the previous types (not nested!), data can be heterogeneous, keys must be strings. For example, one key-value-pair of string and int and one key-value pair of string and float, and so on. * pandas DataFrames_ * :class:`~pypet.parameter.ObjectTable` .. _DataFrames: http://pandas.pydata.org/pandas-docs/dev/dsintro.html#dataframe The keys from the '_store' dictionaries determine how the data will be named in the hdf5 file. :param store_data: How to store the data, see above for a descitpion. :param store_flags: Flags describing how to store data. :const:`~pypet.HDF5StorageService.ARRAY` ('ARRAY') Store stuff as array :const:`~pypet.HDF5StorageService.CARRAY` ('CARRAY') Store stuff as carray :const:`~pypet.HDF5StorageService.TABLE` ('TABLE') Store stuff as pytable :const:`~pypet.HDF5StorageService.DICT` ('DICT') Store stuff as pytable but reconstructs it later as dictionary on loading :const:`~pypet.HDF%StorageService.FRAME` ('FRAME') Store stuff as pandas data frame Storage flags can also be provided by the parameters and results themselves if they implement a function '_store_flags' that returns a dictionary with the names of the data to store as keys and the flags as values. If no storage flags are provided, they are automatically inferred from the data. See :const:`pypet.HDF5StorageService.TYPE_FLAG_MAPPING` for the mapping from type to flag. :param overwrite: Can be used if parts of a leaf should be replaced. Either a list of HDF5 names or `True` if this should account for all. * :const:`pypet.pypetconstants.DELETE` ('DELETE') Removes an item from disk. Empty group nodes, results and non-explored parameters can be removed. :param stuff_to_store: The item to be removed. :param delete_only: Potential list of parts of a leaf node that should be deleted. :param remove_from_item: If `delete_only` is used, whether deleted nodes should also be erased from the leaf nodes themseleves. :param recursive: If you want to delete a group node you can recursively delete all its children. * :const:`pypet.pypetconstants.GROUP` ('GROUP') :param stuff_to_store: The group to store :param store_data: How to store data :param recursive: To recursively load everything below. :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.TREE` Stores a single node or a full subtree :param stuff_to_store: Node to store :param store_data: How to store data :param recursive: Whether to store recursively the whole sub-tree :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.DELETE_LINK` Deletes a link from hard drive :param name: The full colon separated name of the link * :const:`pypet.pypetconstants.LIST` .. _store-lists: Stores several items at once :param stuff_to_store: Iterable whose items are to be stored. Iterable must contain tuples, for example `[(msg1,item1,arg1,kwargs1),(msg2,item2,arg2,kwargs2),...]` * :const:`pypet.pypetconstants.ACCESS_DATA` Requests and manipulates data within the storage. Storage must be open. :param stuff_to_store: A colon separated name to the data path :param item_name: The name of the data item to interact with :param request: A functional request in form of a string :param args: Positional arguments passed to the reques :param kwargs: Keyword arguments passed to the request * :const:`pypet.pypetconstants.OPEN_FILE` Opens the HDF5 file and keeps it open :param stuff_to_store: ``None`` * :const:`pypet.pypetconstants.CLOSE_FILE` Closes an HDF5 file that was kept open, must be open before. :param stuff_to_store: ``None`` * :const:`pypet.pypetconstants.FLUSH` Flushes an open file, must be open before. :param stuff_to_store: ``None`` :raises: NoSuchServiceError if message or data is not understood ### Response: def store(self, msg, stuff_to_store, *args, **kwargs): """ Stores a particular item to disk. The storage service always accepts these parameters: :param trajectory_name: Name or current trajectory and name of top node in hdf5 file :param filename: Name of the hdf5 file :param file_title: If file needs to be created, assigns a title to the file. The following messages (first argument msg) are understood and the following arguments can be provided in combination with the message: * :const:`pypet.pypetconstants.PREPARE_MERGE` ('PREPARE_MERGE'): Called to prepare a trajectory for merging, see also 'MERGE' below. Will also be called if merging cannot happen within the same hdf5 file. Stores already enlarged parameters and updates meta information. :param stuff_to_store: Trajectory that is about to be extended by another one :param changed_parameters: List containing all parameters that were enlarged due to merging :param old_length: Old length of trajectory before merge * :const:`pypet.pypetconstants.MERGE` ('MERGE') Note that before merging within HDF5 file, the storage service will be called with msg='PREPARE_MERGE' before, see above. Raises a ValueError if the two trajectories are not stored within the very same hdf5 file. Then the current trajectory needs to perform the merge slowly item by item. Merges two trajectories, parameters are: :param stuff_to_store: The trajectory data is merged into :param other_trajectory_name: Name of the other trajectory :param rename_dict: Dictionary containing the old result and derived parameter names in the other trajectory and their new names in the current trajectory. :param move_nodes: Whether to move the nodes from the other to the current trajectory :param delete_trajectory: Whether to delete the other trajectory after merging. * :const:`pypet.pypetconstants.BACKUP` ('BACKUP') :param stuff_to_store: Trajectory to be backed up :param backup_filename: Name of file where to store the backup. If None the backup file will be in the same folder as your hdf5 file and named 'backup_XXXXX.hdf5' where 'XXXXX' is the name of your current trajectory. * :const:`pypet.pypetconstants.TRAJECTORY` ('TRAJECTORY') Stores the whole trajectory :param stuff_to_store: The trajectory to be stored :param only_init: If you just want to initialise the store. If yes, only meta information about the trajectory is stored and none of the nodes/leaves within the trajectory. :param store_data: How to store data, the following settings are understood: :const:`pypet.pypetconstants.STORE_NOTHING`: (0) Nothing is stored :const:`pypet.pypetconstants.STORE_DATA_SKIPPING`: (1) Data of not already stored nodes is stored :const:`pypet.pypetconstants.STORE_DATA`: (2) Data of all nodes is stored. However, existing data on disk is left untouched. :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3) Data of all nodes is stored and data on disk is overwritten. May lead to fragmentation of the HDF5 file. The user is adviced to recompress the file manually later on. * :const:`pypet.pypetconstants.SINGLE_RUN` ('SINGLE_RUN') :param stuff_to_store: The trajectory :param store_data: How to store data see above :param store_final: If final meta info should be stored * :const:`pypet.pypetconstants.LEAF` Stores a parameter or result Note that everything that is supported by the storage service and that is stored to disk will be perfectly recovered. For instance, you store a tuple of numpy 32 bit integers, you will get a tuple of numpy 32 bit integers after loading independent of the platform! :param stuff_to_sore: Result or parameter to store In order to determine what to store, the function '_store' of the parameter or result is called. This function returns a dictionary with name keys and data to store as values. In order to determine how to store the data, the storage flags are considered, see below. The function '_store' has to return a dictionary containing values only from the following objects: * python natives (int, long, str, bool, float, complex), * numpy natives, arrays and matrices of type np.int8-64, np.uint8-64, np.float32-64, np.complex, np.str * python lists and tuples of the previous types (python natives + numpy natives and arrays) Lists and tuples are not allowed to be nested and must be homogeneous, i.e. only contain data of one particular type. Only integers, or only floats, etc. * python dictionaries of the previous types (not nested!), data can be heterogeneous, keys must be strings. For example, one key-value-pair of string and int and one key-value pair of string and float, and so on. * pandas DataFrames_ * :class:`~pypet.parameter.ObjectTable` .. _DataFrames: http://pandas.pydata.org/pandas-docs/dev/dsintro.html#dataframe The keys from the '_store' dictionaries determine how the data will be named in the hdf5 file. :param store_data: How to store the data, see above for a descitpion. :param store_flags: Flags describing how to store data. :const:`~pypet.HDF5StorageService.ARRAY` ('ARRAY') Store stuff as array :const:`~pypet.HDF5StorageService.CARRAY` ('CARRAY') Store stuff as carray :const:`~pypet.HDF5StorageService.TABLE` ('TABLE') Store stuff as pytable :const:`~pypet.HDF5StorageService.DICT` ('DICT') Store stuff as pytable but reconstructs it later as dictionary on loading :const:`~pypet.HDF%StorageService.FRAME` ('FRAME') Store stuff as pandas data frame Storage flags can also be provided by the parameters and results themselves if they implement a function '_store_flags' that returns a dictionary with the names of the data to store as keys and the flags as values. If no storage flags are provided, they are automatically inferred from the data. See :const:`pypet.HDF5StorageService.TYPE_FLAG_MAPPING` for the mapping from type to flag. :param overwrite: Can be used if parts of a leaf should be replaced. Either a list of HDF5 names or `True` if this should account for all. * :const:`pypet.pypetconstants.DELETE` ('DELETE') Removes an item from disk. Empty group nodes, results and non-explored parameters can be removed. :param stuff_to_store: The item to be removed. :param delete_only: Potential list of parts of a leaf node that should be deleted. :param remove_from_item: If `delete_only` is used, whether deleted nodes should also be erased from the leaf nodes themseleves. :param recursive: If you want to delete a group node you can recursively delete all its children. * :const:`pypet.pypetconstants.GROUP` ('GROUP') :param stuff_to_store: The group to store :param store_data: How to store data :param recursive: To recursively load everything below. :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.TREE` Stores a single node or a full subtree :param stuff_to_store: Node to store :param store_data: How to store data :param recursive: Whether to store recursively the whole sub-tree :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.DELETE_LINK` Deletes a link from hard drive :param name: The full colon separated name of the link * :const:`pypet.pypetconstants.LIST` .. _store-lists: Stores several items at once :param stuff_to_store: Iterable whose items are to be stored. Iterable must contain tuples, for example `[(msg1,item1,arg1,kwargs1),(msg2,item2,arg2,kwargs2),...]` * :const:`pypet.pypetconstants.ACCESS_DATA` Requests and manipulates data within the storage. Storage must be open. :param stuff_to_store: A colon separated name to the data path :param item_name: The name of the data item to interact with :param request: A functional request in form of a string :param args: Positional arguments passed to the reques :param kwargs: Keyword arguments passed to the request * :const:`pypet.pypetconstants.OPEN_FILE` Opens the HDF5 file and keeps it open :param stuff_to_store: ``None`` * :const:`pypet.pypetconstants.CLOSE_FILE` Closes an HDF5 file that was kept open, must be open before. :param stuff_to_store: ``None`` * :const:`pypet.pypetconstants.FLUSH` Flushes an open file, must be open before. :param stuff_to_store: ``None`` :raises: NoSuchServiceError if message or data is not understood """ opened = True try: opened = self._srvc_opening_routine('a', msg, kwargs) if msg == pypetconstants.MERGE: self._trj_merge_trajectories(*args, **kwargs) elif msg == pypetconstants.BACKUP: self._trj_backup_trajectory(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.PREPARE_MERGE: self._trj_prepare_merge(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.TRAJECTORY: self._trj_store_trajectory(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.SINGLE_RUN: self._srn_store_single_run(stuff_to_store, *args, **kwargs) elif msg in pypetconstants.LEAF: self._prm_store_parameter_or_result(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.DELETE: self._all_delete_parameter_or_result_or_group(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.GROUP: self._grp_store_group(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.TREE: self._tree_store_sub_branch(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.DELETE_LINK: self._lnk_delete_link(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.LIST: self._srvc_store_several_items(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.ACCESS_DATA: return self._hdf5_interact_with_data(stuff_to_store, *args, **kwargs) elif msg == pypetconstants.OPEN_FILE: opened = False # Wee need to keep the file open to allow later interaction self._keep_open = True self._node_processing_timer.active = False # This might be open quite long # so we don't want to display horribly long opening times elif msg == pypetconstants.CLOSE_FILE: opened = True # Simply conduct the closing routine afterwards self._keep_open = False elif msg == pypetconstants.FLUSH: self._hdf5file.flush() else: raise pex.NoSuchServiceError('I do not know how to handle `%s`' % msg) except: self._logger.error('Failed storing `%s`' % str(stuff_to_store)) raise finally: self._srvc_closing_routine(opened)
def token(self): """ obtains a token from the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: self._generateForOAuthSecurity(self._client_id, self._secret_id, self._token_url) return self._token
obtains a token from the site
Below is the the instruction that describes the task: ### Input: obtains a token from the site ### Response: def token(self): """ obtains a token from the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: self._generateForOAuthSecurity(self._client_id, self._secret_id, self._token_url) return self._token
def is_production(flag_name: str = 'PRODUCTION', strict: bool = False): """ Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`` env, ``False`` otherwise """ return env_bool_flag(flag_name, strict=strict)
Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`` env, ``False`` otherwise
Below is the the instruction that describes the task: ### Input: Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`` env, ``False`` otherwise ### Response: def is_production(flag_name: str = 'PRODUCTION', strict: bool = False): """ Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`` env, ``False`` otherwise """ return env_bool_flag(flag_name, strict=strict)
def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None): """ Random truncated normal variates. """ sigma = 1. / np.sqrt(tau) na = utils.normcdf((a - mu) / sigma) nb = utils.normcdf((b - mu) / sigma) # Use the inverse CDF generation method. U = np.random.mtrand.uniform(size=size) q = U * nb + (1 - U) * na R = utils.invcdf(q) # Unnormalize return R * sigma + mu
Random truncated normal variates.
Below is the the instruction that describes the task: ### Input: Random truncated normal variates. ### Response: def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None): """ Random truncated normal variates. """ sigma = 1. / np.sqrt(tau) na = utils.normcdf((a - mu) / sigma) nb = utils.normcdf((b - mu) / sigma) # Use the inverse CDF generation method. U = np.random.mtrand.uniform(size=size) q = U * nb + (1 - U) * na R = utils.invcdf(q) # Unnormalize return R * sigma + mu
def set_progress(self, scan_id, progress): """ Sets scan_id scan's progress. """ if progress > 0 and progress <= 100: self.scans_table[scan_id]['progress'] = progress if progress == 100: self.scans_table[scan_id]['end_time'] = int(time.time())
Sets scan_id scan's progress.
Below is the the instruction that describes the task: ### Input: Sets scan_id scan's progress. ### Response: def set_progress(self, scan_id, progress): """ Sets scan_id scan's progress. """ if progress > 0 and progress <= 100: self.scans_table[scan_id]['progress'] = progress if progress == 100: self.scans_table[scan_id]['end_time'] = int(time.time())
def run_to_rel_pos(self, **kwargs): """ Run to a position relative to the current `position` value. The new position will be current `position` + `position_sp`. When the new position is reached, the motor will stop using the action specified by `stop_action`. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_TO_REL_POS
Run to a position relative to the current `position` value. The new position will be current `position` + `position_sp`. When the new position is reached, the motor will stop using the action specified by `stop_action`.
Below is the the instruction that describes the task: ### Input: Run to a position relative to the current `position` value. The new position will be current `position` + `position_sp`. When the new position is reached, the motor will stop using the action specified by `stop_action`. ### Response: def run_to_rel_pos(self, **kwargs): """ Run to a position relative to the current `position` value. The new position will be current `position` + `position_sp`. When the new position is reached, the motor will stop using the action specified by `stop_action`. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_TO_REL_POS
def as_report_request(self, rules, timer=datetime.utcnow): """Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determines the current time Return: a ``ServicecontrolServicesReportRequest`` generated from this instance governed by the provided ``rules`` Raises: ValueError: if the fields in this instance cannot be used to create a valid ``ServicecontrolServicesReportRequest`` """ if not self.service_name: raise ValueError(u'the service name must be set') op = super(Info, self).as_operation(timer=timer) # Populate metrics and labels if they can be associated with a # method/operation if op.operationId and op.operationName: labels = {} for known_label in rules.labels: known_label.do_labels_update(self, labels) # Forcibly add system label reporting here, as the base service # config does not specify it as a label. labels[_KNOWN_LABELS.SCC_PLATFORM.label_name] = ( self.platform.friendly_string()) labels[_KNOWN_LABELS.SCC_SERVICE_AGENT.label_name] = ( SERVICE_AGENT) labels[_KNOWN_LABELS.SCC_USER_AGENT.label_name] = USER_AGENT if labels: op.labels = encoding.PyValueToMessage( sc_messages.Operation.LabelsValue, labels) for known_metric in rules.metrics: known_metric.do_operation_update(self, op) # Populate the log entries now = timer() op.logEntries = [self._as_log_entry(l, now) for l in rules.logs] return sc_messages.ServicecontrolServicesReportRequest( serviceName=self.service_name, reportRequest=sc_messages.ReportRequest(operations=[op]))
Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determines the current time Return: a ``ServicecontrolServicesReportRequest`` generated from this instance governed by the provided ``rules`` Raises: ValueError: if the fields in this instance cannot be used to create a valid ``ServicecontrolServicesReportRequest``
Below is the the instruction that describes the task: ### Input: Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determines the current time Return: a ``ServicecontrolServicesReportRequest`` generated from this instance governed by the provided ``rules`` Raises: ValueError: if the fields in this instance cannot be used to create a valid ``ServicecontrolServicesReportRequest`` ### Response: def as_report_request(self, rules, timer=datetime.utcnow): """Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determines the current time Return: a ``ServicecontrolServicesReportRequest`` generated from this instance governed by the provided ``rules`` Raises: ValueError: if the fields in this instance cannot be used to create a valid ``ServicecontrolServicesReportRequest`` """ if not self.service_name: raise ValueError(u'the service name must be set') op = super(Info, self).as_operation(timer=timer) # Populate metrics and labels if they can be associated with a # method/operation if op.operationId and op.operationName: labels = {} for known_label in rules.labels: known_label.do_labels_update(self, labels) # Forcibly add system label reporting here, as the base service # config does not specify it as a label. labels[_KNOWN_LABELS.SCC_PLATFORM.label_name] = ( self.platform.friendly_string()) labels[_KNOWN_LABELS.SCC_SERVICE_AGENT.label_name] = ( SERVICE_AGENT) labels[_KNOWN_LABELS.SCC_USER_AGENT.label_name] = USER_AGENT if labels: op.labels = encoding.PyValueToMessage( sc_messages.Operation.LabelsValue, labels) for known_metric in rules.metrics: known_metric.do_operation_update(self, op) # Populate the log entries now = timer() op.logEntries = [self._as_log_entry(l, now) for l in rules.logs] return sc_messages.ServicecontrolServicesReportRequest( serviceName=self.service_name, reportRequest=sc_messages.ReportRequest(operations=[op]))
def is_dict_like(obj, attr=('keys', 'items')): """test if object is dict like""" for a in attr: if not hasattr(obj, a): return False return True
test if object is dict like
Below is the the instruction that describes the task: ### Input: test if object is dict like ### Response: def is_dict_like(obj, attr=('keys', 'items')): """test if object is dict like""" for a in attr: if not hasattr(obj, a): return False return True
def cee_map_priority_group_table_pfc(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") name_key = ET.SubElement(cee_map, "name") name_key.text = kwargs.pop('name') priority_group_table = ET.SubElement(cee_map, "priority-group-table") PGID_key = ET.SubElement(priority_group_table, "PGID") PGID_key.text = kwargs.pop('PGID') pfc = ET.SubElement(priority_group_table, "pfc") pfc.text = kwargs.pop('pfc') callback = kwargs.pop('callback', self._callback) return callback(config)
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def cee_map_priority_group_table_pfc(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") name_key = ET.SubElement(cee_map, "name") name_key.text = kwargs.pop('name') priority_group_table = ET.SubElement(cee_map, "priority-group-table") PGID_key = ET.SubElement(priority_group_table, "PGID") PGID_key.text = kwargs.pop('PGID') pfc = ET.SubElement(priority_group_table, "pfc") pfc.text = kwargs.pop('pfc') callback = kwargs.pop('callback', self._callback) return callback(config)
def clean_text(text): """Clean text before parsing.""" # Replace a few nasty unicode characters with their ASCII equivalent maps = {u'×': u'x', u'–': u'-', u'−': '-'} for element in maps: text = text.replace(element, maps[element]) # Replace genitives text = re.sub(r'(?<=\w)\'s\b|(?<=\w)s\'(?!\w)', ' ', text) logging.debug(u'Clean text: "%s"', text) return text
Clean text before parsing.
Below is the the instruction that describes the task: ### Input: Clean text before parsing. ### Response: def clean_text(text): """Clean text before parsing.""" # Replace a few nasty unicode characters with their ASCII equivalent maps = {u'×': u'x', u'–': u'-', u'−': '-'} for element in maps: text = text.replace(element, maps[element]) # Replace genitives text = re.sub(r'(?<=\w)\'s\b|(?<=\w)s\'(?!\w)', ' ', text) logging.debug(u'Clean text: "%s"', text) return text
def _content(note, content): """ content of the note :param note: note object :param content: content string to make the main body of the note :return: """ note.content = EvernoteMgr.set_header() note.content += sanitize(content) return note
content of the note :param note: note object :param content: content string to make the main body of the note :return:
Below is the the instruction that describes the task: ### Input: content of the note :param note: note object :param content: content string to make the main body of the note :return: ### Response: def _content(note, content): """ content of the note :param note: note object :param content: content string to make the main body of the note :return: """ note.content = EvernoteMgr.set_header() note.content += sanitize(content) return note
def DeserializeUnsigned(self, reader): """ Deserialize unsigned data only. Args: reader (neo.IO.BinaryReader): """ self.Version = reader.ReadUInt32() self.PrevHash = reader.ReadUInt256() self.MerkleRoot = reader.ReadUInt256() self.Timestamp = reader.ReadUInt32() self.Index = reader.ReadUInt32() self.ConsensusData = reader.ReadUInt64() self.NextConsensus = reader.ReadUInt160()
Deserialize unsigned data only. Args: reader (neo.IO.BinaryReader):
Below is the the instruction that describes the task: ### Input: Deserialize unsigned data only. Args: reader (neo.IO.BinaryReader): ### Response: def DeserializeUnsigned(self, reader): """ Deserialize unsigned data only. Args: reader (neo.IO.BinaryReader): """ self.Version = reader.ReadUInt32() self.PrevHash = reader.ReadUInt256() self.MerkleRoot = reader.ReadUInt256() self.Timestamp = reader.ReadUInt32() self.Index = reader.ReadUInt32() self.ConsensusData = reader.ReadUInt64() self.NextConsensus = reader.ReadUInt160()
def distance(self, loc): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ assert type(loc) == type(self) # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [ self.lon, self.lat, loc.lon, loc.lat, ]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371000 # Radius of earth in meters. return c * r
Calculate the great circle distance between two points on the earth (specified in decimal degrees)
Below is the the instruction that describes the task: ### Input: Calculate the great circle distance between two points on the earth (specified in decimal degrees) ### Response: def distance(self, loc): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ assert type(loc) == type(self) # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [ self.lon, self.lat, loc.lon, loc.lat, ]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371000 # Radius of earth in meters. return c * r
def repository_create(name, body, hosts=None, profile=None): ''' .. versionadded:: 2017.7.0 Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option. name Repository name body Repository definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html CLI example:: salt myminion elasticsearch.repository_create testrepo '{"type":"fs","settings":{"location":"/tmp/test","compress":true}}' ''' es = _get_instance(hosts, profile) try: result = es.snapshot.create_repository(repository=name, body=body) return result.get('acknowledged', False) except elasticsearch.TransportError as e: raise CommandExecutionError("Cannot create repository {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error))
.. versionadded:: 2017.7.0 Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option. name Repository name body Repository definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html CLI example:: salt myminion elasticsearch.repository_create testrepo '{"type":"fs","settings":{"location":"/tmp/test","compress":true}}'
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2017.7.0 Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option. name Repository name body Repository definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html CLI example:: salt myminion elasticsearch.repository_create testrepo '{"type":"fs","settings":{"location":"/tmp/test","compress":true}}' ### Response: def repository_create(name, body, hosts=None, profile=None): ''' .. versionadded:: 2017.7.0 Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option. name Repository name body Repository definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html CLI example:: salt myminion elasticsearch.repository_create testrepo '{"type":"fs","settings":{"location":"/tmp/test","compress":true}}' ''' es = _get_instance(hosts, profile) try: result = es.snapshot.create_repository(repository=name, body=body) return result.get('acknowledged', False) except elasticsearch.TransportError as e: raise CommandExecutionError("Cannot create repository {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error))
def mdr_mutual_information(X, Y, labels, base=2): """Calculates the MDR mutual information, I(XY;labels), in the given base MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating the mutual information between the resulting model's predictions and the labels. Parameters ---------- X: array-like (# samples) An array of values corresponding to one feature in the MDR model Y: array-like (# samples) An array of values corresponding to one feature in the MDR model labels: array-like (# samples) The class labels corresponding to features X and Y base: integer (default: 2) The base in which to calculate MDR mutual information Returns ---------- mdr_mutual_information: float The MDR mutual information calculated according to the equation I(XY;labels) = H(labels) - H(labels|XY) """ return mutual_information(_mdr_predict(X, Y, labels), labels, base=base)
Calculates the MDR mutual information, I(XY;labels), in the given base MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating the mutual information between the resulting model's predictions and the labels. Parameters ---------- X: array-like (# samples) An array of values corresponding to one feature in the MDR model Y: array-like (# samples) An array of values corresponding to one feature in the MDR model labels: array-like (# samples) The class labels corresponding to features X and Y base: integer (default: 2) The base in which to calculate MDR mutual information Returns ---------- mdr_mutual_information: float The MDR mutual information calculated according to the equation I(XY;labels) = H(labels) - H(labels|XY)
Below is the the instruction that describes the task: ### Input: Calculates the MDR mutual information, I(XY;labels), in the given base MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating the mutual information between the resulting model's predictions and the labels. Parameters ---------- X: array-like (# samples) An array of values corresponding to one feature in the MDR model Y: array-like (# samples) An array of values corresponding to one feature in the MDR model labels: array-like (# samples) The class labels corresponding to features X and Y base: integer (default: 2) The base in which to calculate MDR mutual information Returns ---------- mdr_mutual_information: float The MDR mutual information calculated according to the equation I(XY;labels) = H(labels) - H(labels|XY) ### Response: def mdr_mutual_information(X, Y, labels, base=2): """Calculates the MDR mutual information, I(XY;labels), in the given base MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating the mutual information between the resulting model's predictions and the labels. Parameters ---------- X: array-like (# samples) An array of values corresponding to one feature in the MDR model Y: array-like (# samples) An array of values corresponding to one feature in the MDR model labels: array-like (# samples) The class labels corresponding to features X and Y base: integer (default: 2) The base in which to calculate MDR mutual information Returns ---------- mdr_mutual_information: float The MDR mutual information calculated according to the equation I(XY;labels) = H(labels) - H(labels|XY) """ return mutual_information(_mdr_predict(X, Y, labels), labels, base=base)
def as_part(func): """ Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) def make(self): return cadquery.Workplane('XY').box(self.x, self.y, self.z) box = Box(x=6, y=3, z=1) May also be written as:: import cadquery from cqparts.utils.wrappers import as_part @as_part def make_box(x=1, y=2, z=4): return cadquery.Workplane('XY').box(x, y, z) box = make_box(x=6, y=3, z=1) In both cases, ``box`` is a :class:`Part <cqparts.Part>` instance. """ from .. import Part def inner(*args, **kwargs): part_class = type(func.__name__, (Part,), { 'make': lambda self: func(*args, **kwargs), }) return part_class() inner.__doc__ = func.__doc__ return inner
Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) def make(self): return cadquery.Workplane('XY').box(self.x, self.y, self.z) box = Box(x=6, y=3, z=1) May also be written as:: import cadquery from cqparts.utils.wrappers import as_part @as_part def make_box(x=1, y=2, z=4): return cadquery.Workplane('XY').box(x, y, z) box = make_box(x=6, y=3, z=1) In both cases, ``box`` is a :class:`Part <cqparts.Part>` instance.
Below is the the instruction that describes the task: ### Input: Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) def make(self): return cadquery.Workplane('XY').box(self.x, self.y, self.z) box = Box(x=6, y=3, z=1) May also be written as:: import cadquery from cqparts.utils.wrappers import as_part @as_part def make_box(x=1, y=2, z=4): return cadquery.Workplane('XY').box(x, y, z) box = make_box(x=6, y=3, z=1) In both cases, ``box`` is a :class:`Part <cqparts.Part>` instance. ### Response: def as_part(func): """ Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) def make(self): return cadquery.Workplane('XY').box(self.x, self.y, self.z) box = Box(x=6, y=3, z=1) May also be written as:: import cadquery from cqparts.utils.wrappers import as_part @as_part def make_box(x=1, y=2, z=4): return cadquery.Workplane('XY').box(x, y, z) box = make_box(x=6, y=3, z=1) In both cases, ``box`` is a :class:`Part <cqparts.Part>` instance. """ from .. import Part def inner(*args, **kwargs): part_class = type(func.__name__, (Part,), { 'make': lambda self: func(*args, **kwargs), }) return part_class() inner.__doc__ = func.__doc__ return inner
def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]): """check function consistency with uniform random numbers""" if isinstance(arg_shapes, int): assert dim shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim)) arg_shapes = [shape] * arg_shapes for dtype in type_list: ndarray_arg = [] numpy_arg = [] for s in arg_shapes: npy = np.random.uniform(rmin, 10, s).astype(dtype) narr = mx.nd.array(npy, dtype=dtype) ndarray_arg.append(narr) numpy_arg.append(npy) out1 = uf(*ndarray_arg) if npuf is None: out2 = uf(*numpy_arg).astype(dtype) else: out2 = npuf(*numpy_arg).astype(dtype) assert out1.shape == out2.shape if isinstance(out1, mx.nd.NDArray): out1 = out1.asnumpy() if dtype == np.float16: assert reldiff(out1, out2) < 2e-3 else: assert reldiff(out1, out2) < 1e-6
check function consistency with uniform random numbers
Below is the the instruction that describes the task: ### Input: check function consistency with uniform random numbers ### Response: def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]): """check function consistency with uniform random numbers""" if isinstance(arg_shapes, int): assert dim shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim)) arg_shapes = [shape] * arg_shapes for dtype in type_list: ndarray_arg = [] numpy_arg = [] for s in arg_shapes: npy = np.random.uniform(rmin, 10, s).astype(dtype) narr = mx.nd.array(npy, dtype=dtype) ndarray_arg.append(narr) numpy_arg.append(npy) out1 = uf(*ndarray_arg) if npuf is None: out2 = uf(*numpy_arg).astype(dtype) else: out2 = npuf(*numpy_arg).astype(dtype) assert out1.shape == out2.shape if isinstance(out1, mx.nd.NDArray): out1 = out1.asnumpy() if dtype == np.float16: assert reldiff(out1, out2) < 2e-3 else: assert reldiff(out1, out2) < 1e-6
def cut(self): """ Cuts the text from the serial to the clipboard. """ text = self.selectedText() for editor in self.editors(): editor.cut() QtGui.QApplication.clipboard().setText(text)
Cuts the text from the serial to the clipboard.
Below is the the instruction that describes the task: ### Input: Cuts the text from the serial to the clipboard. ### Response: def cut(self): """ Cuts the text from the serial to the clipboard. """ text = self.selectedText() for editor in self.editors(): editor.cut() QtGui.QApplication.clipboard().setText(text)
async def getLiftRows(self, lops): ''' Returns: Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict) ''' for oper in lops: func = self._lift_funcs.get(oper[0]) if func is None: raise s_exc.NoSuchLift(name=oper[0]) async for row in func(oper): buid = row[0] props = await self.getBuidProps(buid) yield (buid, props)
Returns: Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict)
Below is the the instruction that describes the task: ### Input: Returns: Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict) ### Response: async def getLiftRows(self, lops): ''' Returns: Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict) ''' for oper in lops: func = self._lift_funcs.get(oper[0]) if func is None: raise s_exc.NoSuchLift(name=oper[0]) async for row in func(oper): buid = row[0] props = await self.getBuidProps(buid) yield (buid, props)
def files_generator(path, recursive): """Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for each file in the given path containing the path and the name of the file. """ if recursive: for (path, _, files) in os.walk(path): for file in files: if not file.endswith(BATCH_EXTENSION): yield (path, file) else: for file in os.listdir(path): if (os.path.isfile(os.path.join(path, file)) and not file.endswith(BATCH_EXTENSION)): yield (path, file)
Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for each file in the given path containing the path and the name of the file.
Below is the the instruction that describes the task: ### Input: Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for each file in the given path containing the path and the name of the file. ### Response: def files_generator(path, recursive): """Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for each file in the given path containing the path and the name of the file. """ if recursive: for (path, _, files) in os.walk(path): for file in files: if not file.endswith(BATCH_EXTENSION): yield (path, file) else: for file in os.listdir(path): if (os.path.isfile(os.path.join(path, file)) and not file.endswith(BATCH_EXTENSION)): yield (path, file)
def _get_underlying_data(self, instance): """Return data from raw data store, rather than overridden __get__ methods. Should NOT be overwritten. """ self._touch(instance) return self.data.get(instance, None)
Return data from raw data store, rather than overridden __get__ methods. Should NOT be overwritten.
Below is the the instruction that describes the task: ### Input: Return data from raw data store, rather than overridden __get__ methods. Should NOT be overwritten. ### Response: def _get_underlying_data(self, instance): """Return data from raw data store, rather than overridden __get__ methods. Should NOT be overwritten. """ self._touch(instance) return self.data.get(instance, None)
def locally_linear_embedding(self, num_dims=None): '''Locally Linear Embedding (LLE). Note: may need to call barycenter_edge_weights() before this! ''' W = self.matrix() # compute M = (I-W)'(I-W) M = W.T.dot(W) - W.T - W if issparse(M): M = M.toarray() M.flat[::M.shape[0] + 1] += 1 return _null_space(M, num_vecs=num_dims, overwrite=True)
Locally Linear Embedding (LLE). Note: may need to call barycenter_edge_weights() before this!
Below is the the instruction that describes the task: ### Input: Locally Linear Embedding (LLE). Note: may need to call barycenter_edge_weights() before this! ### Response: def locally_linear_embedding(self, num_dims=None): '''Locally Linear Embedding (LLE). Note: may need to call barycenter_edge_weights() before this! ''' W = self.matrix() # compute M = (I-W)'(I-W) M = W.T.dot(W) - W.T - W if issparse(M): M = M.toarray() M.flat[::M.shape[0] + 1] += 1 return _null_space(M, num_vecs=num_dims, overwrite=True)
def cli(env, identifier): """Detail firewall.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if firewall_type == 'vlan': rules = mgr.get_dedicated_fwl_rules(firewall_id) else: rules = mgr.get_standard_fwl_rules(firewall_id) env.fout(get_rules_table(rules))
Detail firewall.
Below is the the instruction that describes the task: ### Input: Detail firewall. ### Response: def cli(env, identifier): """Detail firewall.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if firewall_type == 'vlan': rules = mgr.get_dedicated_fwl_rules(firewall_id) else: rules = mgr.get_standard_fwl_rules(firewall_id) env.fout(get_rules_table(rules))
def prevparent(self, parent, depth): ''' Subtract lines from our curline if the name of a node is prefixed with the parent directory when traversing the grandparent object. ''' pdir = os.path.dirname(self.name) if depth > 1: # can't jump to parent of root node! for c, d in parent.traverse(): if c.name == self.name: break if c.name.startswith(pdir): parent.curline -= 1 else: # otherwise jus skip to previous directory pdir = self.name # - 1 otherwise hidden parent node throws count off & our # self.curline doesn't change! line = -1 for c, d in parent.traverse(): if c.name == self.name: break if os.path.isdir(c.name) and c.name in parent.children[0:]: parent.curline = line line += 1 return pdir
Subtract lines from our curline if the name of a node is prefixed with the parent directory when traversing the grandparent object.
Below is the the instruction that describes the task: ### Input: Subtract lines from our curline if the name of a node is prefixed with the parent directory when traversing the grandparent object. ### Response: def prevparent(self, parent, depth): ''' Subtract lines from our curline if the name of a node is prefixed with the parent directory when traversing the grandparent object. ''' pdir = os.path.dirname(self.name) if depth > 1: # can't jump to parent of root node! for c, d in parent.traverse(): if c.name == self.name: break if c.name.startswith(pdir): parent.curline -= 1 else: # otherwise jus skip to previous directory pdir = self.name # - 1 otherwise hidden parent node throws count off & our # self.curline doesn't change! line = -1 for c, d in parent.traverse(): if c.name == self.name: break if os.path.isdir(c.name) and c.name in parent.children[0:]: parent.curline = line line += 1 return pdir
def flag_change(self, flags, level, location=None, worksheet=None, message=''): ''' Wraps the pushing of a change flag into the flags dictionary to handle all edge cases/auto-filling. ''' if not isinstance(level, basestring): try: level = self.FLAG_LEVEL_CODES[level] except KeyError: level = 'fatal' if location == None: location = (-1, -1) ftuple = self.FlagLevelTuple(level, location, worksheet, message) # Handle flags[level] not being present try: flags[level].append(ftuple) except KeyError: flags[level] = [ftuple]
Wraps the pushing of a change flag into the flags dictionary to handle all edge cases/auto-filling.
Below is the the instruction that describes the task: ### Input: Wraps the pushing of a change flag into the flags dictionary to handle all edge cases/auto-filling. ### Response: def flag_change(self, flags, level, location=None, worksheet=None, message=''): ''' Wraps the pushing of a change flag into the flags dictionary to handle all edge cases/auto-filling. ''' if not isinstance(level, basestring): try: level = self.FLAG_LEVEL_CODES[level] except KeyError: level = 'fatal' if location == None: location = (-1, -1) ftuple = self.FlagLevelTuple(level, location, worksheet, message) # Handle flags[level] not being present try: flags[level].append(ftuple) except KeyError: flags[level] = [ftuple]
def logline_timestamp_comparator(t1, t2): """Comparator for timestamps in logline format. Args: t1: Timestamp in logline format. t2: Timestamp in logline format. Returns: -1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2. """ dt1 = _parse_logline_timestamp(t1) dt2 = _parse_logline_timestamp(t2) for u1, u2 in zip(dt1, dt2): if u1 < u2: return -1 elif u1 > u2: return 1 return 0
Comparator for timestamps in logline format. Args: t1: Timestamp in logline format. t2: Timestamp in logline format. Returns: -1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2.
Below is the the instruction that describes the task: ### Input: Comparator for timestamps in logline format. Args: t1: Timestamp in logline format. t2: Timestamp in logline format. Returns: -1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2. ### Response: def logline_timestamp_comparator(t1, t2): """Comparator for timestamps in logline format. Args: t1: Timestamp in logline format. t2: Timestamp in logline format. Returns: -1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2. """ dt1 = _parse_logline_timestamp(t1) dt2 = _parse_logline_timestamp(t2) for u1, u2 in zip(dt1, dt2): if u1 < u2: return -1 elif u1 > u2: return 1 return 0
def create_actor_tri(pts, tris, color, **kwargs): """ Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create triangles triangles = vtk.vtkCellArray() for tri in tris: tmp = vtk.vtkTriangle() for i, v in enumerate(tri): tmp.GetPointIds().SetId(i, v) triangles.InsertNextCell(tmp) # Create a PolyData object and add points & triangles polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(triangles) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor
Below is the the instruction that describes the task: ### Input: Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor ### Response: def create_actor_tri(pts, tris, color, **kwargs): """ Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create triangles triangles = vtk.vtkCellArray() for tri in tris: tmp = vtk.vtkTriangle() for i, v in enumerate(tri): tmp.GetPointIds().SetId(i, v) triangles.InsertNextCell(tmp) # Create a PolyData object and add points & triangles polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(triangles) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
def Produce_Predictions(FileName,train,test): """ Produces predictions for testing set, based off of training set. :param FileName: This is the csv file name we wish to have our predictions exported to. :param train: This is the file name of a csv file that will be the training set. :param test: This is the file name of the testing set that predictions will be made for. :returns: Returns nothing, creates csv file containing predictions for testing set. """ TestFileName=test TrainFileName=train trainDF=pd.read_csv(train) train=Feature_Engineering(train,trainDF) test=Feature_Engineering(test,trainDF) MLA=Create_Random_Forest(TrainFileName) predictions = MLA.predict(test) predictions = pd.DataFrame(predictions, columns=['Survived']) test = pd.read_csv(TestFileName) predictions = pd.concat((test.iloc[:, 0], predictions), axis = 1) predictions.to_csv(FileName, sep=",", index = False)
Produces predictions for testing set, based off of training set. :param FileName: This is the csv file name we wish to have our predictions exported to. :param train: This is the file name of a csv file that will be the training set. :param test: This is the file name of the testing set that predictions will be made for. :returns: Returns nothing, creates csv file containing predictions for testing set.
Below is the the instruction that describes the task: ### Input: Produces predictions for testing set, based off of training set. :param FileName: This is the csv file name we wish to have our predictions exported to. :param train: This is the file name of a csv file that will be the training set. :param test: This is the file name of the testing set that predictions will be made for. :returns: Returns nothing, creates csv file containing predictions for testing set. ### Response: def Produce_Predictions(FileName,train,test): """ Produces predictions for testing set, based off of training set. :param FileName: This is the csv file name we wish to have our predictions exported to. :param train: This is the file name of a csv file that will be the training set. :param test: This is the file name of the testing set that predictions will be made for. :returns: Returns nothing, creates csv file containing predictions for testing set. """ TestFileName=test TrainFileName=train trainDF=pd.read_csv(train) train=Feature_Engineering(train,trainDF) test=Feature_Engineering(test,trainDF) MLA=Create_Random_Forest(TrainFileName) predictions = MLA.predict(test) predictions = pd.DataFrame(predictions, columns=['Survived']) test = pd.read_csv(TestFileName) predictions = pd.concat((test.iloc[:, 0], predictions), axis = 1) predictions.to_csv(FileName, sep=",", index = False)
def auth(self, request): """ let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth """ callback_url = self.callback_url(request) request_token = Pocket.get_request_token(consumer_key=self.consumer_key, redirect_uri=callback_url) # Save the request token information for later request.session['request_token'] = request_token # URL to redirect user to, to authorize your app auth_url = Pocket.get_auth_url(code=request_token, redirect_uri=callback_url) return auth_url
let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth
Below is the the instruction that describes the task: ### Input: let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth ### Response: def auth(self, request): """ let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth """ callback_url = self.callback_url(request) request_token = Pocket.get_request_token(consumer_key=self.consumer_key, redirect_uri=callback_url) # Save the request token information for later request.session['request_token'] = request_token # URL to redirect user to, to authorize your app auth_url = Pocket.get_auth_url(code=request_token, redirect_uri=callback_url) return auth_url
def _evaluate_tempyREPR(self, child, repr_cls): """Assign a score ito a TempyRepr class. The scores depends on the current scope and position of the object in which the TempyREPR is found.""" score = 0 if repr_cls.__name__ == self.__class__.__name__: # One point if the REPR have the same name of the container score += 1 elif repr_cls.__name__ == self.root.__class__.__name__: # One point if the REPR have the same name of the Tempy tree root score += 1 # Add points defined in scorers methods of used TempyPlaces for parent_cls in _filter_classes(repr_cls.__mro__[1:], TempyPlace): for scorer in ( method for method in dir(parent_cls) if method.startswith("_reprscore") ): score += getattr(parent_cls, scorer, lambda *args: 0)( parent_cls, self, child ) return score
Assign a score ito a TempyRepr class. The scores depends on the current scope and position of the object in which the TempyREPR is found.
Below is the the instruction that describes the task: ### Input: Assign a score ito a TempyRepr class. The scores depends on the current scope and position of the object in which the TempyREPR is found. ### Response: def _evaluate_tempyREPR(self, child, repr_cls): """Assign a score ito a TempyRepr class. The scores depends on the current scope and position of the object in which the TempyREPR is found.""" score = 0 if repr_cls.__name__ == self.__class__.__name__: # One point if the REPR have the same name of the container score += 1 elif repr_cls.__name__ == self.root.__class__.__name__: # One point if the REPR have the same name of the Tempy tree root score += 1 # Add points defined in scorers methods of used TempyPlaces for parent_cls in _filter_classes(repr_cls.__mro__[1:], TempyPlace): for scorer in ( method for method in dir(parent_cls) if method.startswith("_reprscore") ): score += getattr(parent_cls, scorer, lambda *args: 0)( parent_cls, self, child ) return score
def batch(self, num): """ Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration. :param int num: number of results per iteration :return: iterator holding list of results """ self._params.pop('limit', None) # Limit and batch are mutually exclusive it = iter(self) while True: chunk = list(islice(it, num)) if not chunk: return yield chunk
Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration. :param int num: number of results per iteration :return: iterator holding list of results
Below is the the instruction that describes the task: ### Input: Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration. :param int num: number of results per iteration :return: iterator holding list of results ### Response: def batch(self, num): """ Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration. :param int num: number of results per iteration :return: iterator holding list of results """ self._params.pop('limit', None) # Limit and batch are mutually exclusive it = iter(self) while True: chunk = list(islice(it, num)) if not chunk: return yield chunk
def _gen_input_mask(mask): """Generate input mask from bytemask""" return input_mask( shift=bool(mask & MOD_Shift), lock=bool(mask & MOD_Lock), control=bool(mask & MOD_Control), mod1=bool(mask & MOD_Mod1), mod2=bool(mask & MOD_Mod2), mod3=bool(mask & MOD_Mod3), mod4=bool(mask & MOD_Mod4), mod5=bool(mask & MOD_Mod5))
Generate input mask from bytemask
Below is the the instruction that describes the task: ### Input: Generate input mask from bytemask ### Response: def _gen_input_mask(mask): """Generate input mask from bytemask""" return input_mask( shift=bool(mask & MOD_Shift), lock=bool(mask & MOD_Lock), control=bool(mask & MOD_Control), mod1=bool(mask & MOD_Mod1), mod2=bool(mask & MOD_Mod2), mod3=bool(mask & MOD_Mod3), mod4=bool(mask & MOD_Mod4), mod5=bool(mask & MOD_Mod5))
def _apply_record_length_checks(self, i, r, summarize=False, context=None): """Apply record length checks on the given record `r`.""" for code, message, modulus in self._record_length_checks: if i % modulus == 0: # support sampling if len(r) != len(self._field_names): p = {'code': code} if not summarize: p['message'] = message p['row'] = i + 1 p['record'] = r p['length'] = len(r) if context is not None: p['context'] = context yield p
Apply record length checks on the given record `r`.
Below is the the instruction that describes the task: ### Input: Apply record length checks on the given record `r`. ### Response: def _apply_record_length_checks(self, i, r, summarize=False, context=None): """Apply record length checks on the given record `r`.""" for code, message, modulus in self._record_length_checks: if i % modulus == 0: # support sampling if len(r) != len(self._field_names): p = {'code': code} if not summarize: p['message'] = message p['row'] = i + 1 p['record'] = r p['length'] = len(r) if context is not None: p['context'] = context yield p
def temp_dir(apply_chown=None, apply_chmod=None, remove_using_sudo=None, remove_force=False): """ Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :type apply_chown: unicode :param apply_chmod: Optional; change the permissions of the directory. :type apply_chmod: unicode :param remove_using_sudo: Use sudo for removing the directory. ``None`` (default) means it is used depending on whether ``apply_chown`` has been set. :type remove_using_sudo: bool | NoneType :param remove_force: Force the removal. :type remove_force: bool :return: Path to the temporary directory. :rtype: unicode """ path = get_remote_temp() try: if apply_chmod: run(chmod(apply_chmod, path)) if apply_chown: if remove_using_sudo is None: remove_using_sudo = True sudo(chown(apply_chown, path)) yield path finally: remove_ignore(path, use_sudo=remove_using_sudo, force=remove_force)
Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :type apply_chown: unicode :param apply_chmod: Optional; change the permissions of the directory. :type apply_chmod: unicode :param remove_using_sudo: Use sudo for removing the directory. ``None`` (default) means it is used depending on whether ``apply_chown`` has been set. :type remove_using_sudo: bool | NoneType :param remove_force: Force the removal. :type remove_force: bool :return: Path to the temporary directory. :rtype: unicode
Below is the the instruction that describes the task: ### Input: Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :type apply_chown: unicode :param apply_chmod: Optional; change the permissions of the directory. :type apply_chmod: unicode :param remove_using_sudo: Use sudo for removing the directory. ``None`` (default) means it is used depending on whether ``apply_chown`` has been set. :type remove_using_sudo: bool | NoneType :param remove_force: Force the removal. :type remove_force: bool :return: Path to the temporary directory. :rtype: unicode ### Response: def temp_dir(apply_chown=None, apply_chmod=None, remove_using_sudo=None, remove_force=False): """ Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :type apply_chown: unicode :param apply_chmod: Optional; change the permissions of the directory. :type apply_chmod: unicode :param remove_using_sudo: Use sudo for removing the directory. ``None`` (default) means it is used depending on whether ``apply_chown`` has been set. :type remove_using_sudo: bool | NoneType :param remove_force: Force the removal. :type remove_force: bool :return: Path to the temporary directory. :rtype: unicode """ path = get_remote_temp() try: if apply_chmod: run(chmod(apply_chmod, path)) if apply_chown: if remove_using_sudo is None: remove_using_sudo = True sudo(chown(apply_chown, path)) yield path finally: remove_ignore(path, use_sudo=remove_using_sudo, force=remove_force)
def interpret_script(shell_script): """Make it appear as if commands are typed into the terminal.""" with CaptureOutput() as capturer: shell = subprocess.Popen(['bash', '-'], stdin=subprocess.PIPE) with open(shell_script) as handle: for line in handle: sys.stdout.write(ansi_wrap('$', color='green') + ' ' + line) sys.stdout.flush() shell.stdin.write(line) shell.stdin.flush() shell.stdin.close() time.sleep(12) # Get the text that was shown in the terminal. captured_output = capturer.get_text() # Store the text that was shown in the terminal. filename, extension = os.path.splitext(shell_script) transcript_file = '%s.txt' % filename logger.info("Updating %s ..", format_path(transcript_file)) with open(transcript_file, 'w') as handle: handle.write(ansi_strip(captured_output))
Make it appear as if commands are typed into the terminal.
Below is the the instruction that describes the task: ### Input: Make it appear as if commands are typed into the terminal. ### Response: def interpret_script(shell_script): """Make it appear as if commands are typed into the terminal.""" with CaptureOutput() as capturer: shell = subprocess.Popen(['bash', '-'], stdin=subprocess.PIPE) with open(shell_script) as handle: for line in handle: sys.stdout.write(ansi_wrap('$', color='green') + ' ' + line) sys.stdout.flush() shell.stdin.write(line) shell.stdin.flush() shell.stdin.close() time.sleep(12) # Get the text that was shown in the terminal. captured_output = capturer.get_text() # Store the text that was shown in the terminal. filename, extension = os.path.splitext(shell_script) transcript_file = '%s.txt' % filename logger.info("Updating %s ..", format_path(transcript_file)) with open(transcript_file, 'w') as handle: handle.write(ansi_strip(captured_output))
def define_sub_network_cycle_constraints( subnetwork, snapshots, passive_branch_p, attribute): """ Constructs cycle_constraints for a particular subnetwork """ sub_network_cycle_constraints = {} sub_network_cycle_index = [] matrix = subnetwork.C.tocsc() branches = subnetwork.branches() for col_j in range( matrix.shape[1] ): cycle_is = matrix.getcol(col_j).nonzero()[0] if len(cycle_is) == 0: continue sub_network_cycle_index.append((subnetwork.name, col_j)) branch_idx_attributes = [] for cycle_i in cycle_is: branch_idx = branches.index[cycle_i] attribute_value = 1e5 * branches.at[ branch_idx, attribute] * subnetwork.C[ cycle_i, col_j] branch_idx_attributes.append( (branch_idx, attribute_value)) for snapshot in snapshots: expression_list = [ (attribute_value, passive_branch_p[branch_idx[0], branch_idx[1], snapshot]) for (branch_idx, attribute_value) in branch_idx_attributes] lhs = LExpression(expression_list) sub_network_cycle_constraints[subnetwork.name,col_j,snapshot] = LConstraint(lhs,"==",LExpression()) return( sub_network_cycle_index, sub_network_cycle_constraints)
Constructs cycle_constraints for a particular subnetwork
Below is the the instruction that describes the task: ### Input: Constructs cycle_constraints for a particular subnetwork ### Response: def define_sub_network_cycle_constraints( subnetwork, snapshots, passive_branch_p, attribute): """ Constructs cycle_constraints for a particular subnetwork """ sub_network_cycle_constraints = {} sub_network_cycle_index = [] matrix = subnetwork.C.tocsc() branches = subnetwork.branches() for col_j in range( matrix.shape[1] ): cycle_is = matrix.getcol(col_j).nonzero()[0] if len(cycle_is) == 0: continue sub_network_cycle_index.append((subnetwork.name, col_j)) branch_idx_attributes = [] for cycle_i in cycle_is: branch_idx = branches.index[cycle_i] attribute_value = 1e5 * branches.at[ branch_idx, attribute] * subnetwork.C[ cycle_i, col_j] branch_idx_attributes.append( (branch_idx, attribute_value)) for snapshot in snapshots: expression_list = [ (attribute_value, passive_branch_p[branch_idx[0], branch_idx[1], snapshot]) for (branch_idx, attribute_value) in branch_idx_attributes] lhs = LExpression(expression_list) sub_network_cycle_constraints[subnetwork.name,col_j,snapshot] = LConstraint(lhs,"==",LExpression()) return( sub_network_cycle_index, sub_network_cycle_constraints)
def peer_store_and_set(relation_id=None, peer_relation_name='cluster', peer_store_fatal=False, relation_settings=None, delimiter='_', **kwargs): """Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and peer_store() at the same time, with the same data. @param relation_id: the id of the relation to store the data on. Defaults to the current relation. @param peer_store_fatal: Set to True, the function will raise an exception should the peer sotrage not be avialable.""" relation_settings = relation_settings if relation_settings else {} relation_set(relation_id=relation_id, relation_settings=relation_settings, **kwargs) if is_relation_made(peer_relation_name): for key, value in six.iteritems(dict(list(kwargs.items()) + list(relation_settings.items()))): key_prefix = relation_id or current_relation_id() peer_store(key_prefix + delimiter + key, value, relation_name=peer_relation_name) else: if peer_store_fatal: raise ValueError('Unable to detect ' 'peer relation {}'.format(peer_relation_name))
Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and peer_store() at the same time, with the same data. @param relation_id: the id of the relation to store the data on. Defaults to the current relation. @param peer_store_fatal: Set to True, the function will raise an exception should the peer sotrage not be avialable.
Below is the the instruction that describes the task: ### Input: Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and peer_store() at the same time, with the same data. @param relation_id: the id of the relation to store the data on. Defaults to the current relation. @param peer_store_fatal: Set to True, the function will raise an exception should the peer sotrage not be avialable. ### Response: def peer_store_and_set(relation_id=None, peer_relation_name='cluster', peer_store_fatal=False, relation_settings=None, delimiter='_', **kwargs): """Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and peer_store() at the same time, with the same data. @param relation_id: the id of the relation to store the data on. Defaults to the current relation. @param peer_store_fatal: Set to True, the function will raise an exception should the peer sotrage not be avialable.""" relation_settings = relation_settings if relation_settings else {} relation_set(relation_id=relation_id, relation_settings=relation_settings, **kwargs) if is_relation_made(peer_relation_name): for key, value in six.iteritems(dict(list(kwargs.items()) + list(relation_settings.items()))): key_prefix = relation_id or current_relation_id() peer_store(key_prefix + delimiter + key, value, relation_name=peer_relation_name) else: if peer_store_fatal: raise ValueError('Unable to detect ' 'peer relation {}'.format(peer_relation_name))
def group_samaccountnames(self, base_dn): """For the current ADUser instance, determine which groups the user is a member of and convert the group DistinguishedNames to sAMAccountNames. The resulting list of groups may not be complete if explicit_membership_only was set to True when the object factory method (user() or users()) was called. :param str base_dn: The base DN to search within :return: A list of groups (sAMAccountNames) for which the current ADUser instance is a member, sAMAccountNames :rtype: list """ #pylint: disable=no-member mappings = self.samaccountnames(base_dn, self.memberof) #pylint: enable=no-member groups = [samaccountname for samaccountname in mappings.values()] if not groups: logging.info("%s - unable to retrieve any groups for the current ADUser instance", self.samaccountname) return groups
For the current ADUser instance, determine which groups the user is a member of and convert the group DistinguishedNames to sAMAccountNames. The resulting list of groups may not be complete if explicit_membership_only was set to True when the object factory method (user() or users()) was called. :param str base_dn: The base DN to search within :return: A list of groups (sAMAccountNames) for which the current ADUser instance is a member, sAMAccountNames :rtype: list
Below is the the instruction that describes the task: ### Input: For the current ADUser instance, determine which groups the user is a member of and convert the group DistinguishedNames to sAMAccountNames. The resulting list of groups may not be complete if explicit_membership_only was set to True when the object factory method (user() or users()) was called. :param str base_dn: The base DN to search within :return: A list of groups (sAMAccountNames) for which the current ADUser instance is a member, sAMAccountNames :rtype: list ### Response: def group_samaccountnames(self, base_dn): """For the current ADUser instance, determine which groups the user is a member of and convert the group DistinguishedNames to sAMAccountNames. The resulting list of groups may not be complete if explicit_membership_only was set to True when the object factory method (user() or users()) was called. :param str base_dn: The base DN to search within :return: A list of groups (sAMAccountNames) for which the current ADUser instance is a member, sAMAccountNames :rtype: list """ #pylint: disable=no-member mappings = self.samaccountnames(base_dn, self.memberof) #pylint: enable=no-member groups = [samaccountname for samaccountname in mappings.values()] if not groups: logging.info("%s - unable to retrieve any groups for the current ADUser instance", self.samaccountname) return groups
def add_library(self, library): """ Adds functions from a library module :param library: the library module :return: """ for fn in library.__dict__.copy().values(): # ignore imported methods and anything beginning __ if inspect.isfunction(fn) and inspect.getmodule(fn) == library and not fn.__name__.startswith('__'): name = fn.__name__.lower() # strip preceding _ chars used to avoid conflicts with Java keywords if name.startswith('_'): name = name[1:] self._functions[name] = fn
Adds functions from a library module :param library: the library module :return:
Below is the the instruction that describes the task: ### Input: Adds functions from a library module :param library: the library module :return: ### Response: def add_library(self, library): """ Adds functions from a library module :param library: the library module :return: """ for fn in library.__dict__.copy().values(): # ignore imported methods and anything beginning __ if inspect.isfunction(fn) and inspect.getmodule(fn) == library and not fn.__name__.startswith('__'): name = fn.__name__.lower() # strip preceding _ chars used to avoid conflicts with Java keywords if name.startswith('_'): name = name[1:] self._functions[name] = fn
def badge(self, *args, **kwargs): """ Latest Build Status Badge Checks the status of the latest build of a given branch and returns corresponding badge svg. This method is ``experimental`` """ return self._makeApiCall(self.funcinfo["badge"], *args, **kwargs)
Latest Build Status Badge Checks the status of the latest build of a given branch and returns corresponding badge svg. This method is ``experimental``
Below is the the instruction that describes the task: ### Input: Latest Build Status Badge Checks the status of the latest build of a given branch and returns corresponding badge svg. This method is ``experimental`` ### Response: def badge(self, *args, **kwargs): """ Latest Build Status Badge Checks the status of the latest build of a given branch and returns corresponding badge svg. This method is ``experimental`` """ return self._makeApiCall(self.funcinfo["badge"], *args, **kwargs)
def two_phase_dP_dz_gravitational(angle, alpha, rhol, rhog, g=g): r'''This function handles calculation of two-phase liquid-gas pressure drop due to gravitation for flow inside channels. This is a differential calculation for a segment with an infinitesimal difference in elevation for use in performing integration over a pipe as shown in [1]_ and [2]_. .. math:: -\left(\frac{dP}{dz} \right)_{grav} = [\alpha\rho_g + (1-\alpha) \rho_l]g \sin \theta Parameters ---------- angle : float The angle of the pipe with respect to the horizontal, [degrees] alpha : float Void fraction (area of gas / total area of channel), [-] rhol : float Liquid phase density, [kg/m^3] rhog : float Gas phase density, [kg/m^3] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- dP_dz : float Gravitational component of pressure drop for two-phase flow, [Pa/m] Notes ----- Examples -------- >>> two_phase_dP_dz_gravitational(angle=90, alpha=0.9685, rhol=1518, ... rhog=2.6) 493.6187084149995 References ---------- .. [1] Rohsenow, Warren and James Hartnett and Young Cho. Handbook of Heat Transfer, 3E. New York: McGraw-Hill, 1998. .. [2] Kim, Sung-Min, and Issam Mudawar. "Review of Databases and Predictive Methods for Pressure Drop in Adiabatic, Condensing and Boiling Mini/Micro-Channel Flows." International Journal of Heat and Mass Transfer 77 (October 2014): 74-97. doi:10.1016/j.ijheatmasstransfer.2014.04.035. ''' angle = radians(angle) return g*sin(angle)*(alpha*rhog + (1. - alpha)*rhol)
r'''This function handles calculation of two-phase liquid-gas pressure drop due to gravitation for flow inside channels. This is a differential calculation for a segment with an infinitesimal difference in elevation for use in performing integration over a pipe as shown in [1]_ and [2]_. .. math:: -\left(\frac{dP}{dz} \right)_{grav} = [\alpha\rho_g + (1-\alpha) \rho_l]g \sin \theta Parameters ---------- angle : float The angle of the pipe with respect to the horizontal, [degrees] alpha : float Void fraction (area of gas / total area of channel), [-] rhol : float Liquid phase density, [kg/m^3] rhog : float Gas phase density, [kg/m^3] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- dP_dz : float Gravitational component of pressure drop for two-phase flow, [Pa/m] Notes ----- Examples -------- >>> two_phase_dP_dz_gravitational(angle=90, alpha=0.9685, rhol=1518, ... rhog=2.6) 493.6187084149995 References ---------- .. [1] Rohsenow, Warren and James Hartnett and Young Cho. Handbook of Heat Transfer, 3E. New York: McGraw-Hill, 1998. .. [2] Kim, Sung-Min, and Issam Mudawar. "Review of Databases and Predictive Methods for Pressure Drop in Adiabatic, Condensing and Boiling Mini/Micro-Channel Flows." International Journal of Heat and Mass Transfer 77 (October 2014): 74-97. doi:10.1016/j.ijheatmasstransfer.2014.04.035.
Below is the the instruction that describes the task: ### Input: r'''This function handles calculation of two-phase liquid-gas pressure drop due to gravitation for flow inside channels. This is a differential calculation for a segment with an infinitesimal difference in elevation for use in performing integration over a pipe as shown in [1]_ and [2]_. .. math:: -\left(\frac{dP}{dz} \right)_{grav} = [\alpha\rho_g + (1-\alpha) \rho_l]g \sin \theta Parameters ---------- angle : float The angle of the pipe with respect to the horizontal, [degrees] alpha : float Void fraction (area of gas / total area of channel), [-] rhol : float Liquid phase density, [kg/m^3] rhog : float Gas phase density, [kg/m^3] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- dP_dz : float Gravitational component of pressure drop for two-phase flow, [Pa/m] Notes ----- Examples -------- >>> two_phase_dP_dz_gravitational(angle=90, alpha=0.9685, rhol=1518, ... rhog=2.6) 493.6187084149995 References ---------- .. [1] Rohsenow, Warren and James Hartnett and Young Cho. Handbook of Heat Transfer, 3E. New York: McGraw-Hill, 1998. .. [2] Kim, Sung-Min, and Issam Mudawar. "Review of Databases and Predictive Methods for Pressure Drop in Adiabatic, Condensing and Boiling Mini/Micro-Channel Flows." International Journal of Heat and Mass Transfer 77 (October 2014): 74-97. doi:10.1016/j.ijheatmasstransfer.2014.04.035. ### Response: def two_phase_dP_dz_gravitational(angle, alpha, rhol, rhog, g=g): r'''This function handles calculation of two-phase liquid-gas pressure drop due to gravitation for flow inside channels. This is a differential calculation for a segment with an infinitesimal difference in elevation for use in performing integration over a pipe as shown in [1]_ and [2]_. .. math:: -\left(\frac{dP}{dz} \right)_{grav} = [\alpha\rho_g + (1-\alpha) \rho_l]g \sin \theta Parameters ---------- angle : float The angle of the pipe with respect to the horizontal, [degrees] alpha : float Void fraction (area of gas / total area of channel), [-] rhol : float Liquid phase density, [kg/m^3] rhog : float Gas phase density, [kg/m^3] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- dP_dz : float Gravitational component of pressure drop for two-phase flow, [Pa/m] Notes ----- Examples -------- >>> two_phase_dP_dz_gravitational(angle=90, alpha=0.9685, rhol=1518, ... rhog=2.6) 493.6187084149995 References ---------- .. [1] Rohsenow, Warren and James Hartnett and Young Cho. Handbook of Heat Transfer, 3E. New York: McGraw-Hill, 1998. .. [2] Kim, Sung-Min, and Issam Mudawar. "Review of Databases and Predictive Methods for Pressure Drop in Adiabatic, Condensing and Boiling Mini/Micro-Channel Flows." International Journal of Heat and Mass Transfer 77 (October 2014): 74-97. doi:10.1016/j.ijheatmasstransfer.2014.04.035. ''' angle = radians(angle) return g*sin(angle)*(alpha*rhog + (1. - alpha)*rhol)
def unwrap(self): """Return a deep copy of myself as a list, and unwrap any wrapper objects in me.""" return [v.unwrap() if hasattr(v, 'unwrap') and not hasattr(v, 'no_unwrap') else v for v in self]
Return a deep copy of myself as a list, and unwrap any wrapper objects in me.
Below is the the instruction that describes the task: ### Input: Return a deep copy of myself as a list, and unwrap any wrapper objects in me. ### Response: def unwrap(self): """Return a deep copy of myself as a list, and unwrap any wrapper objects in me.""" return [v.unwrap() if hasattr(v, 'unwrap') and not hasattr(v, 'no_unwrap') else v for v in self]
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ msg = self.msg if self.args: msg = msg.format(*self.args) return maybe_encode(msg)
Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message.
Below is the the instruction that describes the task: ### Input: Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. ### Response: def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ msg = self.msg if self.args: msg = msg.format(*self.args) return maybe_encode(msg)
def Decrypt(self, encrypted_data): """Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data. """ index_split = -(len(encrypted_data) % AES.block_size) if index_split: remaining_encrypted_data = encrypted_data[index_split:] encrypted_data = encrypted_data[:index_split] else: remaining_encrypted_data = b'' decrypted_data = self._aes_cipher.decrypt(encrypted_data) return decrypted_data, remaining_encrypted_data
Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data.
Below is the the instruction that describes the task: ### Input: Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data. ### Response: def Decrypt(self, encrypted_data): """Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data. """ index_split = -(len(encrypted_data) % AES.block_size) if index_split: remaining_encrypted_data = encrypted_data[index_split:] encrypted_data = encrypted_data[:index_split] else: remaining_encrypted_data = b'' decrypted_data = self._aes_cipher.decrypt(encrypted_data) return decrypted_data, remaining_encrypted_data
def getSiblings(self, textId, subreference): """ Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param subreference: CapitainsCtsPassage Reference :type subreference: str :return: Tuple of references :rtype: (str, str) """ text = CtsText( urn=textId, retriever=self.endpoint ) return text.getPrevNextUrn(subreference)
Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param subreference: CapitainsCtsPassage Reference :type subreference: str :return: Tuple of references :rtype: (str, str)
Below is the the instruction that describes the task: ### Input: Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param subreference: CapitainsCtsPassage Reference :type subreference: str :return: Tuple of references :rtype: (str, str) ### Response: def getSiblings(self, textId, subreference): """ Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param subreference: CapitainsCtsPassage Reference :type subreference: str :return: Tuple of references :rtype: (str, str) """ text = CtsText( urn=textId, retriever=self.endpoint ) return text.getPrevNextUrn(subreference)
def namedb_get_record_states_at(cur, history_id, block_number): """ Get the state(s) that the given history record was in at a given block height. Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10) However, if the record changed at this block, then this method returns all states the record passed through. Returns an array of record states """ query = 'SELECT block_id,history_data FROM history WHERE history_id = ? AND block_id == ? ORDER BY block_id DESC,vtxindex DESC' args = (history_id, block_number) history_rows = namedb_query_execute(cur, query, args) ret = [] for row in history_rows: history_data = simplejson.loads(row['history_data']) ret.append(history_data) if len(ret) > 0: # record changed in this block return ret # if the record did not change in this block, then find the last version of the record query = 'SELECT block_id,history_data FROM history WHERE history_id = ? AND block_id < ? ORDER BY block_id DESC,vtxindex DESC LIMIT 1' args = (history_id, block_number) history_rows = namedb_query_execute(cur, query, args) for row in history_rows: history_data = simplejson.loads(row['history_data']) ret.append(history_data) return ret
Get the state(s) that the given history record was in at a given block height. Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10) However, if the record changed at this block, then this method returns all states the record passed through. Returns an array of record states
Below is the the instruction that describes the task: ### Input: Get the state(s) that the given history record was in at a given block height. Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10) However, if the record changed at this block, then this method returns all states the record passed through. Returns an array of record states ### Response: def namedb_get_record_states_at(cur, history_id, block_number): """ Get the state(s) that the given history record was in at a given block height. Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10) However, if the record changed at this block, then this method returns all states the record passed through. Returns an array of record states """ query = 'SELECT block_id,history_data FROM history WHERE history_id = ? AND block_id == ? ORDER BY block_id DESC,vtxindex DESC' args = (history_id, block_number) history_rows = namedb_query_execute(cur, query, args) ret = [] for row in history_rows: history_data = simplejson.loads(row['history_data']) ret.append(history_data) if len(ret) > 0: # record changed in this block return ret # if the record did not change in this block, then find the last version of the record query = 'SELECT block_id,history_data FROM history WHERE history_id = ? AND block_id < ? ORDER BY block_id DESC,vtxindex DESC LIMIT 1' args = (history_id, block_number) history_rows = namedb_query_execute(cur, query, args) for row in history_rows: history_data = simplejson.loads(row['history_data']) ret.append(history_data) return ret
def from_der_data(cls, data): """Decode DER-encoded certificate. :Parameters: - `data`: the encoded certificate :Types: - `data`: `bytes` :Return: decoded certificate data :Returntype: ASN1CertificateData """ # pylint: disable=W0212 logger.debug("Decoding DER certificate: {0!r}".format(data)) if cls._cert_asn1_type is None: cls._cert_asn1_type = Certificate() cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0] result = cls() tbs_cert = cert.getComponentByName('tbsCertificate') subject = tbs_cert.getComponentByName('subject') logger.debug("Subject: {0!r}".format(subject)) result._decode_subject(subject) validity = tbs_cert.getComponentByName('validity') result._decode_validity(validity) extensions = tbs_cert.getComponentByName('extensions') if extensions: for extension in extensions: logger.debug("Extension: {0!r}".format(extension)) oid = extension.getComponentByName('extnID') logger.debug("OID: {0!r}".format(oid)) if oid != SUBJECT_ALT_NAME_OID: continue value = extension.getComponentByName('extnValue') logger.debug("Value: {0!r}".format(value)) if isinstance(value, Any): # should be OctetString, but is Any # in pyasn1_modules-0.0.1a value = der_decoder.decode(value, asn1Spec = OctetString())[0] alt_names = der_decoder.decode(value, asn1Spec = GeneralNames())[0] logger.debug("SubjectAltName: {0!r}".format(alt_names)) result._decode_alt_names(alt_names) return result
Decode DER-encoded certificate. :Parameters: - `data`: the encoded certificate :Types: - `data`: `bytes` :Return: decoded certificate data :Returntype: ASN1CertificateData
Below is the the instruction that describes the task: ### Input: Decode DER-encoded certificate. :Parameters: - `data`: the encoded certificate :Types: - `data`: `bytes` :Return: decoded certificate data :Returntype: ASN1CertificateData ### Response: def from_der_data(cls, data): """Decode DER-encoded certificate. :Parameters: - `data`: the encoded certificate :Types: - `data`: `bytes` :Return: decoded certificate data :Returntype: ASN1CertificateData """ # pylint: disable=W0212 logger.debug("Decoding DER certificate: {0!r}".format(data)) if cls._cert_asn1_type is None: cls._cert_asn1_type = Certificate() cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0] result = cls() tbs_cert = cert.getComponentByName('tbsCertificate') subject = tbs_cert.getComponentByName('subject') logger.debug("Subject: {0!r}".format(subject)) result._decode_subject(subject) validity = tbs_cert.getComponentByName('validity') result._decode_validity(validity) extensions = tbs_cert.getComponentByName('extensions') if extensions: for extension in extensions: logger.debug("Extension: {0!r}".format(extension)) oid = extension.getComponentByName('extnID') logger.debug("OID: {0!r}".format(oid)) if oid != SUBJECT_ALT_NAME_OID: continue value = extension.getComponentByName('extnValue') logger.debug("Value: {0!r}".format(value)) if isinstance(value, Any): # should be OctetString, but is Any # in pyasn1_modules-0.0.1a value = der_decoder.decode(value, asn1Spec = OctetString())[0] alt_names = der_decoder.decode(value, asn1Spec = GeneralNames())[0] logger.debug("SubjectAltName: {0!r}".format(alt_names)) result._decode_alt_names(alt_names) return result
def ensure_v8_src(): """ Ensure that v8 src are presents and up-to-date """ path = local_path('v8') if not os.path.isdir(path): fetch_v8(path) else: update_v8(path) checkout_v8_version(local_path("v8/v8"), V8_VERSION) dependencies_sync(path)
Ensure that v8 src are presents and up-to-date
Below is the the instruction that describes the task: ### Input: Ensure that v8 src are presents and up-to-date ### Response: def ensure_v8_src(): """ Ensure that v8 src are presents and up-to-date """ path = local_path('v8') if not os.path.isdir(path): fetch_v8(path) else: update_v8(path) checkout_v8_version(local_path("v8/v8"), V8_VERSION) dependencies_sync(path)
def list_privileges(name, **client_args): ''' List privileges from a user. name Name of the user from whom privileges will be listed. CLI Example: .. code-block:: bash salt '*' influxdb.list_privileges <name> ''' client = _client(**client_args) res = {} for item in client.get_list_privileges(name): res[item['database']] = item['privilege'].split()[0].lower() return res
List privileges from a user. name Name of the user from whom privileges will be listed. CLI Example: .. code-block:: bash salt '*' influxdb.list_privileges <name>
Below is the the instruction that describes the task: ### Input: List privileges from a user. name Name of the user from whom privileges will be listed. CLI Example: .. code-block:: bash salt '*' influxdb.list_privileges <name> ### Response: def list_privileges(name, **client_args): ''' List privileges from a user. name Name of the user from whom privileges will be listed. CLI Example: .. code-block:: bash salt '*' influxdb.list_privileges <name> ''' client = _client(**client_args) res = {} for item in client.get_list_privileges(name): res[item['database']] = item['privilege'].split()[0].lower() return res
def has_concluded(self, bigchain, current_votes=[]): """Check if the election can be concluded or not. * Elections can only be concluded if the validator set has not changed since the election was initiated. * Elections can be concluded only if the current votes form a supermajority. Custom elections may override this function and introduce additional checks. """ if self.has_validator_set_changed(bigchain): return False election_pk = self.to_public_key(self.id) votes_committed = self.get_commited_votes(bigchain, election_pk) votes_current = self.count_votes(election_pk, current_votes) total_votes = sum(output.amount for output in self.outputs) if (votes_committed < (2/3) * total_votes) and \ (votes_committed + votes_current >= (2/3)*total_votes): return True return False
Check if the election can be concluded or not. * Elections can only be concluded if the validator set has not changed since the election was initiated. * Elections can be concluded only if the current votes form a supermajority. Custom elections may override this function and introduce additional checks.
Below is the the instruction that describes the task: ### Input: Check if the election can be concluded or not. * Elections can only be concluded if the validator set has not changed since the election was initiated. * Elections can be concluded only if the current votes form a supermajority. Custom elections may override this function and introduce additional checks. ### Response: def has_concluded(self, bigchain, current_votes=[]): """Check if the election can be concluded or not. * Elections can only be concluded if the validator set has not changed since the election was initiated. * Elections can be concluded only if the current votes form a supermajority. Custom elections may override this function and introduce additional checks. """ if self.has_validator_set_changed(bigchain): return False election_pk = self.to_public_key(self.id) votes_committed = self.get_commited_votes(bigchain, election_pk) votes_current = self.count_votes(election_pk, current_votes) total_votes = sum(output.amount for output in self.outputs) if (votes_committed < (2/3) * total_votes) and \ (votes_committed + votes_current >= (2/3)*total_votes): return True return False
def selectAssemblies(pth, manifest=None): """ Return a binary's dependent assemblies files that should be included. Return a list of pairs (name, fullpath) """ rv = [] if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if manifest: _depNames = set([dep.name for dep in manifest.dependentAssemblies]) for assembly in getAssemblies(pth): if seen.get(assembly.getid().upper(), 0): continue if manifest and not assembly.name in _depNames: # Add assembly as dependency to our final output exe's manifest logger.info("Adding %s to dependent assemblies " "of final executable", assembly.name) manifest.dependentAssemblies.append(assembly) _depNames.add(assembly.name) if not dylib.include_library(assembly.name): logger.debug("Skipping assembly %s", assembly.getid()) continue if assembly.optional: logger.debug("Skipping optional assembly %s", assembly.getid()) continue files = assembly.find_files() if files: seen[assembly.getid().upper()] = 1 for fn in files: fname, fext = os.path.splitext(fn) if fext.lower() == ".manifest": nm = assembly.name + fext else: nm = os.path.basename(fn) ftocnm = nm if assembly.language not in (None, "", "*", "neutral"): ftocnm = os.path.join(assembly.getlanguage(), ftocnm) nm, ftocnm, fn = [item.encode(sys.getfilesystemencoding()) for item in (nm, ftocnm, fn)] if not seen.get(fn.upper(), 0): logger.debug("Adding %s", ftocnm) seen[nm.upper()] = 1 seen[fn.upper()] = 1 rv.append((ftocnm, fn)) else: #logger.info("skipping %s part of assembly %s dependency of %s", # ftocnm, assembly.name, pth) pass else: logger.error("Assembly %s not found", assembly.getid()) return rv
Return a binary's dependent assemblies files that should be included. Return a list of pairs (name, fullpath)
Below is the the instruction that describes the task: ### Input: Return a binary's dependent assemblies files that should be included. Return a list of pairs (name, fullpath) ### Response: def selectAssemblies(pth, manifest=None): """ Return a binary's dependent assemblies files that should be included. Return a list of pairs (name, fullpath) """ rv = [] if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if manifest: _depNames = set([dep.name for dep in manifest.dependentAssemblies]) for assembly in getAssemblies(pth): if seen.get(assembly.getid().upper(), 0): continue if manifest and not assembly.name in _depNames: # Add assembly as dependency to our final output exe's manifest logger.info("Adding %s to dependent assemblies " "of final executable", assembly.name) manifest.dependentAssemblies.append(assembly) _depNames.add(assembly.name) if not dylib.include_library(assembly.name): logger.debug("Skipping assembly %s", assembly.getid()) continue if assembly.optional: logger.debug("Skipping optional assembly %s", assembly.getid()) continue files = assembly.find_files() if files: seen[assembly.getid().upper()] = 1 for fn in files: fname, fext = os.path.splitext(fn) if fext.lower() == ".manifest": nm = assembly.name + fext else: nm = os.path.basename(fn) ftocnm = nm if assembly.language not in (None, "", "*", "neutral"): ftocnm = os.path.join(assembly.getlanguage(), ftocnm) nm, ftocnm, fn = [item.encode(sys.getfilesystemencoding()) for item in (nm, ftocnm, fn)] if not seen.get(fn.upper(), 0): logger.debug("Adding %s", ftocnm) seen[nm.upper()] = 1 seen[fn.upper()] = 1 rv.append((ftocnm, fn)) else: #logger.info("skipping %s part of assembly %s dependency of %s", # ftocnm, assembly.name, pth) pass else: logger.error("Assembly %s not found", assembly.getid()) return rv
def invite(self, event): """A new user has been invited to enrol by an admin user""" self.log('Inviting new user to enrol') name = event.data['name'] email = event.data['email'] method = event.data['method'] self._invite(name, method, email, event.client.uuid, event)
A new user has been invited to enrol by an admin user
Below is the the instruction that describes the task: ### Input: A new user has been invited to enrol by an admin user ### Response: def invite(self, event): """A new user has been invited to enrol by an admin user""" self.log('Inviting new user to enrol') name = event.data['name'] email = event.data['email'] method = event.data['method'] self._invite(name, method, email, event.client.uuid, event)
def Type_string(self, text, interval = 0, dl = 0): """键盘输入字符串,interval是字符间输入时间间隔,单位"秒" """ self.Delay(dl) self.keyboard.type_string(text, interval)
键盘输入字符串,interval是字符间输入时间间隔,单位"秒"
Below is the the instruction that describes the task: ### Input: 键盘输入字符串,interval是字符间输入时间间隔,单位"秒" ### Response: def Type_string(self, text, interval = 0, dl = 0): """键盘输入字符串,interval是字符间输入时间间隔,单位"秒" """ self.Delay(dl) self.keyboard.type_string(text, interval)
def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False): """Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Returns ------- xy_coords : function A function that maps a Pegasus index (u, w, k, z) in a Pegasus lattice to x,y coordinates such as used by a plot. """ import numpy as np m = G.graph.get('rows') h_offsets = G.graph.get("horizontal_offsets") v_offsets = G.graph.get("vertical_offsets") tile_width = G.graph.get("tile") tile_center = tile_width / 2 - .5 # want the enter plot to fill in [0, 1] when scale=1 scale /= m * tile_width if center is None: center = np.zeros(dim) else: center = np.asarray(center) paddims = dim - 2 if paddims < 0: raise ValueError("layout must have at least two dimensions") if len(center) != dim: raise ValueError("length of center coordinates must match dimension of layout") if crosses: # adjustment for crosses cross_shift = 2. else: cross_shift = 0. def _xy_coords(u, w, k, z): # orientation, major perpendicular offset, minor perpendicular offset, parallel offset if k % 2: p = -.1 else: p = .1 if u: xy = np.array([z*tile_width+h_offsets[k] + tile_center, -tile_width*w-k-p+cross_shift]) else: xy = np.array([tile_width*w+k+p+cross_shift, -z*tile_width-v_offsets[k]-tile_center]) # convention for Pegasus-lattice pictures is to invert the y-axis return np.hstack((xy * scale, np.zeros(paddims))) + center return _xy_coords
Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Returns ------- xy_coords : function A function that maps a Pegasus index (u, w, k, z) in a Pegasus lattice to x,y coordinates such as used by a plot.
Below is the the instruction that describes the task: ### Input: Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Returns ------- xy_coords : function A function that maps a Pegasus index (u, w, k, z) in a Pegasus lattice to x,y coordinates such as used by a plot. ### Response: def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False): """Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Returns ------- xy_coords : function A function that maps a Pegasus index (u, w, k, z) in a Pegasus lattice to x,y coordinates such as used by a plot. """ import numpy as np m = G.graph.get('rows') h_offsets = G.graph.get("horizontal_offsets") v_offsets = G.graph.get("vertical_offsets") tile_width = G.graph.get("tile") tile_center = tile_width / 2 - .5 # want the enter plot to fill in [0, 1] when scale=1 scale /= m * tile_width if center is None: center = np.zeros(dim) else: center = np.asarray(center) paddims = dim - 2 if paddims < 0: raise ValueError("layout must have at least two dimensions") if len(center) != dim: raise ValueError("length of center coordinates must match dimension of layout") if crosses: # adjustment for crosses cross_shift = 2. else: cross_shift = 0. def _xy_coords(u, w, k, z): # orientation, major perpendicular offset, minor perpendicular offset, parallel offset if k % 2: p = -.1 else: p = .1 if u: xy = np.array([z*tile_width+h_offsets[k] + tile_center, -tile_width*w-k-p+cross_shift]) else: xy = np.array([tile_width*w+k+p+cross_shift, -z*tile_width-v_offsets[k]-tile_center]) # convention for Pegasus-lattice pictures is to invert the y-axis return np.hstack((xy * scale, np.zeros(paddims))) + center return _xy_coords
def header_output(self): '''只输出cookie的key-value字串. 比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129 ''' result = [] for key in self.keys(): result.append(key + '=' + self.get(key).value) return '; '.join(result)
只输出cookie的key-value字串. 比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129
Below is the the instruction that describes the task: ### Input: 只输出cookie的key-value字串. 比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129 ### Response: def header_output(self): '''只输出cookie的key-value字串. 比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129 ''' result = [] for key in self.keys(): result.append(key + '=' + self.get(key).value) return '; '.join(result)
def cid(self): """The PubChem Compound Identifier (CID). .. note:: When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an automatically generated record may be returned that contains properties that have been calculated on the fly. These records will not have a CID property. """ if 'id' in self.record and 'id' in self.record['id'] and 'cid' in self.record['id']['id']: return self.record['id']['id']['cid']
The PubChem Compound Identifier (CID). .. note:: When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an automatically generated record may be returned that contains properties that have been calculated on the fly. These records will not have a CID property.
Below is the the instruction that describes the task: ### Input: The PubChem Compound Identifier (CID). .. note:: When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an automatically generated record may be returned that contains properties that have been calculated on the fly. These records will not have a CID property. ### Response: def cid(self): """The PubChem Compound Identifier (CID). .. note:: When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an automatically generated record may be returned that contains properties that have been calculated on the fly. These records will not have a CID property. """ if 'id' in self.record and 'id' in self.record['id'] and 'cid' in self.record['id']['id']: return self.record['id']['id']['cid']
def pcolormesh(self, *args, **kwargs): """Create a pseudocolor plot of a 2-D array. If a 3D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==2`` and the first two axes do not span dimensions other than those spanned by that channel. Uses pcolor_helper to ensure that color boundaries are drawn bisecting point positions, when possible. Quicker than pcolor Parameters ---------- data : 2D WrightTools.data.Data object Data to plot. channel : int or string (optional) Channel index or name. Default is 0. dynamic_range : boolean (optional) Force plotting of all contours, overloading for major extent. Only applies to signed data. Default is False. autolabel : {'none', 'both', 'x', 'y'} (optional) Parameterize application of labels directly from data object. Default is none. xlabel : string (optional) xlabel. Default is None. ylabel : string (optional) ylabel. Default is None. **kwargs matplotlib.axes.Axes.pcolormesh__ optional keyword arguments. __ https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html Returns ------- matplotlib.collections.QuadMesh """ args, kwargs = self._parse_plot_args(*args, **kwargs, plot_type="pcolormesh") return super().pcolormesh(*args, **kwargs)
Create a pseudocolor plot of a 2-D array. If a 3D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==2`` and the first two axes do not span dimensions other than those spanned by that channel. Uses pcolor_helper to ensure that color boundaries are drawn bisecting point positions, when possible. Quicker than pcolor Parameters ---------- data : 2D WrightTools.data.Data object Data to plot. channel : int or string (optional) Channel index or name. Default is 0. dynamic_range : boolean (optional) Force plotting of all contours, overloading for major extent. Only applies to signed data. Default is False. autolabel : {'none', 'both', 'x', 'y'} (optional) Parameterize application of labels directly from data object. Default is none. xlabel : string (optional) xlabel. Default is None. ylabel : string (optional) ylabel. Default is None. **kwargs matplotlib.axes.Axes.pcolormesh__ optional keyword arguments. __ https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html Returns ------- matplotlib.collections.QuadMesh
Below is the the instruction that describes the task: ### Input: Create a pseudocolor plot of a 2-D array. If a 3D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==2`` and the first two axes do not span dimensions other than those spanned by that channel. Uses pcolor_helper to ensure that color boundaries are drawn bisecting point positions, when possible. Quicker than pcolor Parameters ---------- data : 2D WrightTools.data.Data object Data to plot. channel : int or string (optional) Channel index or name. Default is 0. dynamic_range : boolean (optional) Force plotting of all contours, overloading for major extent. Only applies to signed data. Default is False. autolabel : {'none', 'both', 'x', 'y'} (optional) Parameterize application of labels directly from data object. Default is none. xlabel : string (optional) xlabel. Default is None. ylabel : string (optional) ylabel. Default is None. **kwargs matplotlib.axes.Axes.pcolormesh__ optional keyword arguments. __ https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html Returns ------- matplotlib.collections.QuadMesh ### Response: def pcolormesh(self, *args, **kwargs): """Create a pseudocolor plot of a 2-D array. If a 3D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==2`` and the first two axes do not span dimensions other than those spanned by that channel. Uses pcolor_helper to ensure that color boundaries are drawn bisecting point positions, when possible. Quicker than pcolor Parameters ---------- data : 2D WrightTools.data.Data object Data to plot. channel : int or string (optional) Channel index or name. Default is 0. dynamic_range : boolean (optional) Force plotting of all contours, overloading for major extent. Only applies to signed data. Default is False. autolabel : {'none', 'both', 'x', 'y'} (optional) Parameterize application of labels directly from data object. Default is none. xlabel : string (optional) xlabel. Default is None. ylabel : string (optional) ylabel. Default is None. **kwargs matplotlib.axes.Axes.pcolormesh__ optional keyword arguments. __ https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html Returns ------- matplotlib.collections.QuadMesh """ args, kwargs = self._parse_plot_args(*args, **kwargs, plot_type="pcolormesh") return super().pcolormesh(*args, **kwargs)
def encode(self, word, max_length=4): """Return the Statistics Canada code for a word. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 4) of the code to return Returns ------- str The Statistics Canada name code value Examples -------- >>> pe = StatisticsCanada() >>> pe.encode('Christopher') 'CHRS' >>> pe.encode('Niall') 'NL' >>> pe.encode('Smith') 'SMTH' >>> pe.encode('Schmidt') 'SCHM' """ # uppercase, normalize, decompose, and filter non-A-Z out word = unicode_normalize('NFKD', text_type(word.upper())) word = word.replace('ß', 'SS') word = ''.join(c for c in word if c in self._uc_set) if not word: return '' code = word[1:] for vowel in self._uc_vy_set: code = code.replace(vowel, '') code = word[0] + code code = self._delete_consecutive_repeats(code) code = code.replace(' ', '') return code[:max_length]
Return the Statistics Canada code for a word. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 4) of the code to return Returns ------- str The Statistics Canada name code value Examples -------- >>> pe = StatisticsCanada() >>> pe.encode('Christopher') 'CHRS' >>> pe.encode('Niall') 'NL' >>> pe.encode('Smith') 'SMTH' >>> pe.encode('Schmidt') 'SCHM'
Below is the the instruction that describes the task: ### Input: Return the Statistics Canada code for a word. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 4) of the code to return Returns ------- str The Statistics Canada name code value Examples -------- >>> pe = StatisticsCanada() >>> pe.encode('Christopher') 'CHRS' >>> pe.encode('Niall') 'NL' >>> pe.encode('Smith') 'SMTH' >>> pe.encode('Schmidt') 'SCHM' ### Response: def encode(self, word, max_length=4): """Return the Statistics Canada code for a word. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 4) of the code to return Returns ------- str The Statistics Canada name code value Examples -------- >>> pe = StatisticsCanada() >>> pe.encode('Christopher') 'CHRS' >>> pe.encode('Niall') 'NL' >>> pe.encode('Smith') 'SMTH' >>> pe.encode('Schmidt') 'SCHM' """ # uppercase, normalize, decompose, and filter non-A-Z out word = unicode_normalize('NFKD', text_type(word.upper())) word = word.replace('ß', 'SS') word = ''.join(c for c in word if c in self._uc_set) if not word: return '' code = word[1:] for vowel in self._uc_vy_set: code = code.replace(vowel, '') code = word[0] + code code = self._delete_consecutive_repeats(code) code = code.replace(' ', '') return code[:max_length]
def chdir(__path: str) -> ContextManager: """Context handler to temporarily switch directories. Args: __path: Directory to change to Yields: Execution context in ``path`` """ old = os.getcwd() try: os.chdir(__path) yield finally: os.chdir(old)
Context handler to temporarily switch directories. Args: __path: Directory to change to Yields: Execution context in ``path``
Below is the the instruction that describes the task: ### Input: Context handler to temporarily switch directories. Args: __path: Directory to change to Yields: Execution context in ``path`` ### Response: def chdir(__path: str) -> ContextManager: """Context handler to temporarily switch directories. Args: __path: Directory to change to Yields: Execution context in ``path`` """ old = os.getcwd() try: os.chdir(__path) yield finally: os.chdir(old)
def typing(self, *, channel: str): """Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnectedError: Websocket connection is closed. """ payload = {"id": self._next_msg_id(), "type": "typing", "channel": channel} self.send_over_websocket(payload=payload)
Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnectedError: Websocket connection is closed.
Below is the the instruction that describes the task: ### Input: Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnectedError: Websocket connection is closed. ### Response: def typing(self, *, channel: str): """Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnectedError: Websocket connection is closed. """ payload = {"id": self._next_msg_id(), "type": "typing", "channel": channel} self.send_over_websocket(payload=payload)
def pre_save(self, model_instance, add): """Updates socket.gethostname() on each save.""" value = socket.gethostname() setattr(model_instance, self.attname, value) return value
Updates socket.gethostname() on each save.
Below is the the instruction that describes the task: ### Input: Updates socket.gethostname() on each save. ### Response: def pre_save(self, model_instance, add): """Updates socket.gethostname() on each save.""" value = socket.gethostname() setattr(model_instance, self.attname, value) return value
def exploit_single(self, ip, operating_system): """ Exploits a single ip, exploit is based on the given operating system. """ result = None if "Windows Server 2008" in operating_system or "Windows 7" in operating_system: result = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'eternalblue_exploit7.py'), str(ip), os.path.join(self.datadir, 'final_combined.bin'), "12"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif "Windows Server 2012" in operating_system or "Windows 10" in operating_system or "Windows 8.1" in operating_system: result = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'eternalblue_exploit8.py'), str(ip), os.path.join(self.datadir, 'final_combined.bin'), "12"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: return ["System target could not be automatically identified"] return result.stdout.decode('utf-8').split('\n')
Exploits a single ip, exploit is based on the given operating system.
Below is the the instruction that describes the task: ### Input: Exploits a single ip, exploit is based on the given operating system. ### Response: def exploit_single(self, ip, operating_system): """ Exploits a single ip, exploit is based on the given operating system. """ result = None if "Windows Server 2008" in operating_system or "Windows 7" in operating_system: result = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'eternalblue_exploit7.py'), str(ip), os.path.join(self.datadir, 'final_combined.bin'), "12"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif "Windows Server 2012" in operating_system or "Windows 10" in operating_system or "Windows 8.1" in operating_system: result = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'eternalblue_exploit8.py'), str(ip), os.path.join(self.datadir, 'final_combined.bin'), "12"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: return ["System target could not be automatically identified"] return result.stdout.decode('utf-8').split('\n')
def partial_predict(self, X, y=None): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : array-like shape=(n_samples, n_features) A single timeseries. Returns ------- Y : array, shape=(n_samples,) Index of the cluster that each sample belongs to """ if isinstance(X, md.Trajectory): X.center_coordinates() return super(MultiSequenceClusterMixin, self).predict(X)
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : array-like shape=(n_samples, n_features) A single timeseries. Returns ------- Y : array, shape=(n_samples,) Index of the cluster that each sample belongs to
Below is the the instruction that describes the task: ### Input: Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : array-like shape=(n_samples, n_features) A single timeseries. Returns ------- Y : array, shape=(n_samples,) Index of the cluster that each sample belongs to ### Response: def partial_predict(self, X, y=None): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : array-like shape=(n_samples, n_features) A single timeseries. Returns ------- Y : array, shape=(n_samples,) Index of the cluster that each sample belongs to """ if isinstance(X, md.Trajectory): X.center_coordinates() return super(MultiSequenceClusterMixin, self).predict(X)
def get_service_inspect(self, stack, service): """查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息 """ url = '{0}/v3/stacks/{1}/services/{2}/inspect'.format(self.host, stack, service) return self.__get(url)
查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
Below is the the instruction that describes the task: ### Input: 查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息 ### Response: def get_service_inspect(self, stack, service): """查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息 """ url = '{0}/v3/stacks/{1}/services/{2}/inspect'.format(self.host, stack, service) return self.__get(url)
def grading_means_passed(self): ''' Information if the given grading means passed. Non-graded assignments are always passed. ''' if self.assignment.is_graded(): if self.grading and self.grading.means_passed: return True else: return False else: return True
Information if the given grading means passed. Non-graded assignments are always passed.
Below is the the instruction that describes the task: ### Input: Information if the given grading means passed. Non-graded assignments are always passed. ### Response: def grading_means_passed(self): ''' Information if the given grading means passed. Non-graded assignments are always passed. ''' if self.assignment.is_graded(): if self.grading and self.grading.means_passed: return True else: return False else: return True
def rot_rads(self, rads): """ Rotate vector by angle in radians.""" new_x = self.x * math.cos(rads) - self.y * math.sin(rads) self.y = self.x * math.sin(rads) + self.y * math.cos(rads) self.x = new_x
Rotate vector by angle in radians.
Below is the the instruction that describes the task: ### Input: Rotate vector by angle in radians. ### Response: def rot_rads(self, rads): """ Rotate vector by angle in radians.""" new_x = self.x * math.cos(rads) - self.y * math.sin(rads) self.y = self.x * math.sin(rads) + self.y * math.cos(rads) self.x = new_x
def tree_iterator(self, visited=None, path=None): ''' Generator function that traverse the dr tree start from this node (self). ''' if visited is None: visited = set() if self not in visited: if path and isinstance(path, list): path.append(self) visited.add(self) yield self if not hasattr(self, 'dterms'): yield for dterm in self.dterms: if hasattr(self, dterm): child = getattr(self, dterm) if hasattr(child, 'dterms') or hasattr(child, 'terms'): for node in child.tree_iterator(visited): yield node
Generator function that traverse the dr tree start from this node (self).
Below is the the instruction that describes the task: ### Input: Generator function that traverse the dr tree start from this node (self). ### Response: def tree_iterator(self, visited=None, path=None): ''' Generator function that traverse the dr tree start from this node (self). ''' if visited is None: visited = set() if self not in visited: if path and isinstance(path, list): path.append(self) visited.add(self) yield self if not hasattr(self, 'dterms'): yield for dterm in self.dterms: if hasattr(self, dterm): child = getattr(self, dterm) if hasattr(child, 'dterms') or hasattr(child, 'terms'): for node in child.tree_iterator(visited): yield node
def battery_voltage(self): """ Returns voltage in mV """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG) voltage_bin = msb << 4 | lsb & 0x0f return voltage_bin * 1.1
Returns voltage in mV
Below is the the instruction that describes the task: ### Input: Returns voltage in mV ### Response: def battery_voltage(self): """ Returns voltage in mV """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG) voltage_bin = msb << 4 | lsb & 0x0f return voltage_bin * 1.1
def convert_to_mb(s): """Convert memory size from GB to MB.""" s = s.upper() try: if s.endswith('G'): return float(s[:-1].strip()) * 1024 elif s.endswith('T'): return float(s[:-1].strip()) * 1024 * 1024 else: return float(s[:-1].strip()) except (IndexError, ValueError, KeyError, TypeError): errmsg = ("Invalid memory format: %s") % s raise exception.SDKInternalError(msg=errmsg)
Convert memory size from GB to MB.
Below is the the instruction that describes the task: ### Input: Convert memory size from GB to MB. ### Response: def convert_to_mb(s): """Convert memory size from GB to MB.""" s = s.upper() try: if s.endswith('G'): return float(s[:-1].strip()) * 1024 elif s.endswith('T'): return float(s[:-1].strip()) * 1024 * 1024 else: return float(s[:-1].strip()) except (IndexError, ValueError, KeyError, TypeError): errmsg = ("Invalid memory format: %s") % s raise exception.SDKInternalError(msg=errmsg)