code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def greater_than_obs_constraints(self): """get the names of the observations that are listed as greater than inequality constraints. Zero- weighted obs are skipped Returns ------- pandas.Series : obsnme of obseravtions that are non-zero weighted ...
get the names of the observations that are listed as greater than inequality constraints. Zero- weighted obs are skipped Returns ------- pandas.Series : obsnme of obseravtions that are non-zero weighted greater than constraints
def knn_impute_with_argpartition( X, missing_mask, k, verbose=False, print_interval=100): """ Fill in the given incomplete matrix using k-nearest neighbor imputation. This version is a simpler algorithm meant primarily for testing but surprisingly it's faster for...
Fill in the given incomplete matrix using k-nearest neighbor imputation. This version is a simpler algorithm meant primarily for testing but surprisingly it's faster for many (but not all) dataset sizes, particularly when most of the columns are missing in any given row. The crucial bottleneck is the c...
def IsEquivalent(self, other): """Determines if 2 operating system artifacts are equivalent. This function compares the operating systems based in order of: * name derived from product * family and version * family Args: other (OperatingSystemArtifact): operating system artifact attribut...
Determines if 2 operating system artifacts are equivalent. This function compares the operating systems based in order of: * name derived from product * family and version * family Args: other (OperatingSystemArtifact): operating system artifact attribute container to compare with....
def _get_group_dataframes(self): """ Get group dataframes Returns ------- out : tuple or generator Group dataframes """ if isinstance(self.data, GroupedDataFrame): grouper = self.data.groupby() # groupby on categorical columns ...
Get group dataframes Returns ------- out : tuple or generator Group dataframes
def matches(): """This resource returns a list of the currently running WvW matches, with the participating worlds included in the result. Further details about a match can be requested using the ``match_details`` function. The response is a list of match objects, each of which contains the followi...
This resource returns a list of the currently running WvW matches, with the participating worlds included in the result. Further details about a match can be requested using the ``match_details`` function. The response is a list of match objects, each of which contains the following properties: wv...
def create(self, container, instances=None, map_name=None, **kwargs): """ Creates container instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance name to create. If not specified, will create all inst...
Creates container instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance name to create. If not specified, will create all instances as specified in the configuration (or just one default instance). :...
def images_grouped_by_type(self): """ :return: A generator yielding 2-tuples of (type, [creators]) where adjacent creators who share the same role are grouped together. """ type = -1 images = [] for wc in self: if wc.type != type: if im...
:return: A generator yielding 2-tuples of (type, [creators]) where adjacent creators who share the same role are grouped together.
def process(self): '''Run all tag processors.''' for tag_proc in self.tag_procs: before_count = self.entry_count self.run_tag_processor(tag_proc) after_count = self.entry_count if self.verbose: print('Inserted %d entries for "%s" tag proce...
Run all tag processors.
def replace_first_key_in_makefile(buf, key, replacement, outfile=None): ''' Replaces first line in 'buf' matching 'key' with 'replacement'. Optionally, writes out this new buffer into 'outfile'. Returns: Buffer after replacement has been done ''' regexp = re.compile(r''' \n\s* # ...
Replaces first line in 'buf' matching 'key' with 'replacement'. Optionally, writes out this new buffer into 'outfile'. Returns: Buffer after replacement has been done
def otp(password, seed, sequence): """ Calculates a one-time password hash using the given password, seed, and sequence number and returns it. Uses the MD4/sixword algorithm as supported by TACACS+ servers. :type password: str :param password: A password. :type seed: str :param seed: ...
Calculates a one-time password hash using the given password, seed, and sequence number and returns it. Uses the MD4/sixword algorithm as supported by TACACS+ servers. :type password: str :param password: A password. :type seed: str :param seed: A cryptographic seed. :type sequence: int ...
def not_unless(*desired_flags): """ Assert that the decorated function can only be called if the desired_flags are active. Note that, unlike :func:`when`, this does **not** trigger the decorated function if the flags match. It **only** raises an exception if the function is called when the fla...
Assert that the decorated function can only be called if the desired_flags are active. Note that, unlike :func:`when`, this does **not** trigger the decorated function if the flags match. It **only** raises an exception if the function is called when the flags do not match. This is primarily for ...
def _convert(self, desired_type: Type[T], obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Apply the converters of the chain in order to produce the desired result. Only the last converter will see the 'desired type', the others will be asked to produce their declared to_typ...
Apply the converters of the chain in order to produce the desired result. Only the last converter will see the 'desired type', the others will be asked to produce their declared to_type. :param desired_type: :param obj: :param logger: :param options: :return:
def default_setup(): """The default API setup for lxc4u This is the API that you access globally from lxc4u. """ service = LXCService lxc_types = dict(LXC=LXC, LXCWithOverlays=LXCWithOverlays, __default__=UnmanagedLXC) loader = LXCLoader(lxc_types, service) manager = LXCManager(...
The default API setup for lxc4u This is the API that you access globally from lxc4u.
def itemcounts(self, **kwargs): '''Returns a dict where the keys are the keys of the container. The values are the *lengths* of the value sequences stored in this container. ''' return {k: len(v) for k, v in self._dict.items()}
Returns a dict where the keys are the keys of the container. The values are the *lengths* of the value sequences stored in this container.
def handle_message(self, msg): """Manage message of different type and in the context of path.""" self.messages.append( { "type": msg.category, "module": msg.module, "obj": msg.obj, "line": msg.line, "column": ms...
Manage message of different type and in the context of path.
def checker(location, receiver): """Construct a function that checks a directory for process configuration The function checks for additions or removals of JSON process configuration files and calls the appropriate receiver methods. :param location: string, the directory to monitor :param rece...
Construct a function that checks a directory for process configuration The function checks for additions or removals of JSON process configuration files and calls the appropriate receiver methods. :param location: string, the directory to monitor :param receiver: IEventReceiver :returns: a fun...
def _mainthread_poll_readable(self): """Searches for readable client sockets. These sockets are then put in a subthread to be handled by _handle_readable """ events = self._recv_selector.select(self.block_time) for key, mask in events: if mask == selectors.EVENT_READ:...
Searches for readable client sockets. These sockets are then put in a subthread to be handled by _handle_readable
def monitor(args): ''' Retrieve status of jobs submitted from a given workspace, as a list of TSV lines sorted by descending order of job submission date''' r = fapi.list_submissions(args.project, args.workspace) fapi._check_response_code(r, 200) statuses = sorted(r.json(), key=lambda k: k['subm...
Retrieve status of jobs submitted from a given workspace, as a list of TSV lines sorted by descending order of job submission date
def unicode2auto(unicode_text, encode_text): """ This function will convert unicode (first argument) text into other encodes by auto find the encode (from available encodes) by using sample encode text in second argument of this function. unicode_text : Pass unicode string which has to conver...
This function will convert unicode (first argument) text into other encodes by auto find the encode (from available encodes) by using sample encode text in second argument of this function. unicode_text : Pass unicode string which has to convert into other encode. encode_text : Pass sample encode ...
def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = ...
(Internal) Append formatted datetime.
def savecsv(filename, datadict, mode="w"): """Save a dictionary of data to CSV.""" if mode == "a" : header = False else: header = True with open(filename, mode) as f: _pd.DataFrame(datadict).to_csv(f, index=False, header=header)
Save a dictionary of data to CSV.
def put(self, resource_id): """Return the JSON representation of a new resource created or updated through an HTTP PUT call. If resource_id is not provided, it is assumed the primary key field is included and a totally new resource is created. Otherwise, the existing resource re...
Return the JSON representation of a new resource created or updated through an HTTP PUT call. If resource_id is not provided, it is assumed the primary key field is included and a totally new resource is created. Otherwise, the existing resource referred to by *resource_id* is updated w...
def setup_menu_actions(self): """Setup and update the menu actions.""" self.recent_notebook_menu.clear() self.recent_notebooks_actions = [] if self.recent_notebooks: for notebook in self.recent_notebooks: name = notebook action = \ ...
Setup and update the menu actions.
def _MergeDifferentId(self): """Tries to merge all possible combinations of entities. This tries to merge every entity in the old schedule with every entity in the new schedule. Unlike _MergeSameId, the ids do not need to match. However, _MergeDifferentId is much slower than _MergeSameId. This met...
Tries to merge all possible combinations of entities. This tries to merge every entity in the old schedule with every entity in the new schedule. Unlike _MergeSameId, the ids do not need to match. However, _MergeDifferentId is much slower than _MergeSameId. This method makes use of various methods lik...
def cudnnSetTensor4dDescriptor(tensorDesc, format, dataType, n, c, h, w): """ Initialize a previously created Tensor 4D object. This function initializes a previously created Tensor4D descriptor object. The strides of the four dimensions are inferred from the format parameter and set in such a way that...
Initialize a previously created Tensor 4D object. This function initializes a previously created Tensor4D descriptor object. The strides of the four dimensions are inferred from the format parameter and set in such a way that the data is contiguous in memory with no padding between dimensions. Paramet...
def _group_matching(tlist, cls): """Groups Tokens that have beginning and end.""" opens = [] tidx_offset = 0 for idx, token in enumerate(list(tlist)): tidx = idx - tidx_offset if token.is_whitespace: # ~50% of tokens will be whitespace. Will checking early # for ...
Groups Tokens that have beginning and end.
def all_address_target_pairs(cls, address_families): """Implementation of `address_target_pairs_from_address_families()` which does no filtering.""" addr_tgt_pairs = [] for af in address_families: addr_tgt_pairs.extend(af.addressables.items()) return addr_tgt_pairs
Implementation of `address_target_pairs_from_address_families()` which does no filtering.
def load_json_file(filepath): """ <Purpose> Deserialize a JSON object from a file containing the object. <Arguments> filepath: Absolute path of JSON file. <Exceptions> securesystemslib.exceptions.FormatError: If 'filepath' is improperly formatted. securesystemslib.exceptions.Error: ...
<Purpose> Deserialize a JSON object from a file containing the object. <Arguments> filepath: Absolute path of JSON file. <Exceptions> securesystemslib.exceptions.FormatError: If 'filepath' is improperly formatted. securesystemslib.exceptions.Error: If 'filepath' cannot be deserialized t...
def _create_ring(self, nodes): """Generate a ketama compatible continuum/ring. """ _weight_sum = 0 for node_conf in self._nodes.values(): _weight_sum += node_conf['weight'] self._weight_sum = _weight_sum _distribution = Counter() _keys = [] _r...
Generate a ketama compatible continuum/ring.
def _cmdline(argv=None): """ Parse command line arguments. By default, sys.argv is parsed. """ parser = ArgumentParser() parser.add_argument("--checkout", default="HEAD", help="branch, tag, or commit to use [HEAD]") parser.add_argument("--name", default=_NAME, ...
Parse command line arguments. By default, sys.argv is parsed.
def get_fpath(self, cachedir=None, cfgstr=None, ext=None): """ Ignore: fname = _fname cfgstr = _cfgstr """ _dpath = self.get_cachedir(cachedir) _fname = self.get_prefix() _cfgstr = self.get_cfgstr() if cfgstr is None else cfgstr _ext = se...
Ignore: fname = _fname cfgstr = _cfgstr
async def build_get_revoc_reg_request(submitter_did: Optional[str], revoc_reg_def_id: str, timestamp: int) -> str: """ Builds a GET_REVOC_REG request. Request to get the accumulated state of the Revocation Registry by ID. The state ...
Builds a GET_REVOC_REG request. Request to get the accumulated state of the Revocation Registry by ID. The state is defined by the given timestamp. :param submitter_did: (Optional) DID of the read request sender (if not provided then default Libindy DID will be used). :param revoc_reg_def_id: ID of the co...
def get_device_name_list(): """Returns a list of device names installed.""" dev_names = ctypes.create_string_buffer(1024) pydaq.DAQmxGetSysDevNames(dev_names, len(dev_names)) return dev_names.value.split(', ')
Returns a list of device names installed.
def register_schemas_dir(self, directory): """Recursively register all json-schemas in a directory. :param directory: directory path. """ for root, dirs, files in os.walk(directory): dir_path = os.path.relpath(root, directory) if dir_path == '.': ...
Recursively register all json-schemas in a directory. :param directory: directory path.
def copy(self, source, destination, recursive=False, use_sudo=False): """ Copy a file or directory """ func = use_sudo and run_as_root or self.run options = '-r ' if recursive else '' func('/bin/cp {0}{1} {2}'.format(options, quote(source), quote(destination)))
Copy a file or directory
def load_fs_mrf_to_syntax_mrf_translation_rules( rulesFile ): ''' Loads rules that can be used to convert from Filosoft's mrf format to syntactic analyzer's format. Returns a dict containing rules. Expects that each line in the input file contains a single rule, and that different parts o...
Loads rules that can be used to convert from Filosoft's mrf format to syntactic analyzer's format. Returns a dict containing rules. Expects that each line in the input file contains a single rule, and that different parts of the rule separated by @ symbols, e.g. 1@_S_ ?@S...
def pip_install_package(source_name, pip_version=None, python_version=None, mode=InstallMode.min_deps, release=False): """Install a pip-compatible python package as a rez package. Args: source_name (str): Name of package or archive/url containing the pip package sourc...
Install a pip-compatible python package as a rez package. Args: source_name (str): Name of package or archive/url containing the pip package source. This is the same as the arg you would pass to the 'pip install' command. pip_version (str or `Version`): Version of pip to use ...
def extents(triangles, areas=None): """ Return the 2D bounding box size of each triangle. Parameters ---------- triangles : (n, 3, 3) float Triangles in space areas : (n,) float Optional area of input triangles Returns ---------- box : (n, 2) float The size of ea...
Return the 2D bounding box size of each triangle. Parameters ---------- triangles : (n, 3, 3) float Triangles in space areas : (n,) float Optional area of input triangles Returns ---------- box : (n, 2) float The size of each triangle's 2D oriented bounding box
def pset(self, n): """ Convert the nodes nsprefixes into a set. @param n: A node. @type n: L{Element} @return: A set of namespaces. @rtype: set """ s = set() for ns in n.nsprefixes.items(): if self.permit(ns): s.add(ns[1...
Convert the nodes nsprefixes into a set. @param n: A node. @type n: L{Element} @return: A set of namespaces. @rtype: set
def run_blast_commands(ncbicommandline_method, **keywords): """Runs blastplus/tblastn search, collects result and pass as a xml temporary file. """ # temporary files for output blast_out_tmp = tempfile.NamedTemporaryFile(mode="w+",delete=False) keywords['out'] = blast_out_tmp.name # unpack query ...
Runs blastplus/tblastn search, collects result and pass as a xml temporary file.
def get_resolve_diff(self, other): """Get the difference between the resolve in this context and another. The difference is described from the point of view of the current context - a newer package means that the package in `other` is newer than the package in `self`. Diffs can...
Get the difference between the resolve in this context and another. The difference is described from the point of view of the current context - a newer package means that the package in `other` is newer than the package in `self`. Diffs can only be compared if their package search path...
def register_xml_mapping(self, clsdict): """ Add XML mappings to the enumeration class state for this member. """ member_to_xml = self._get_or_add_member_to_xml(clsdict) member_to_xml[self.value] = self.xml_value xml_to_member = self._get_or_add_xml_to_member(clsdict) ...
Add XML mappings to the enumeration class state for this member.
def random(self, length=22): """ Generate and return a cryptographically-secure short random string of the specified length. """ random_num = int(binascii.b2a_hex(os.urandom(length)), 16) return self._num_to_string(random_num, pad_to_length=length)[:length]
Generate and return a cryptographically-secure short random string of the specified length.
def initialize(self): """initialize in base class""" self._lb = [b[0] for b in self.bounds] # can be done more efficiently? self._ub = [b[1] for b in self.bounds]
initialize in base class
def cross_lists(*sets): """Return the cross product of the arguments""" wheels = [iter(_) for _ in sets] digits = [next(it) for it in wheels] while True: yield digits[:] for i in range(len(digits)-1, -1, -1): try: digits[i] = next(wheels[i]) br...
Return the cross product of the arguments
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.year = None else: self.year = vals[i] i += 1 if len(vals[i]) == 0: self.mont...
Read values. Args: vals (list): list of strings representing values
def resolve_parameter_refs(self, input): """ Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as !GetAtt, !Sub or !Ref to non-parameters will be left untouched. Result is a dictionary where parameter values are inlined. Don't pass...
Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as !GetAtt, !Sub or !Ref to non-parameters will be left untouched. Result is a dictionary where parameter values are inlined. Don't pass this dictionary directly into transform's output bec...
def _setup_log_prefix(self, plugin_id=''): """Setup custom warning notification.""" self._logger_console_fmtter.prefix = '%s: ' % plugin_id self._logger_console_fmtter.plugin_id = plugin_id self._logger_file_fmtter.prefix = '*' self._logger_file_fmtter.plugin_id = '%s: ' % plugin...
Setup custom warning notification.
def fit_delta_ts(data, livetime, fit_background=True): """Fits gaussians to delta t for each PMT pair. Parameters ---------- data: 2d np.array: x = PMT combinations (465), y = time, entry = frequency livetime: length of data taking in seconds fit_background: if True: fits gaussian with offset, ...
Fits gaussians to delta t for each PMT pair. Parameters ---------- data: 2d np.array: x = PMT combinations (465), y = time, entry = frequency livetime: length of data taking in seconds fit_background: if True: fits gaussian with offset, else without offset Returns ------- numpy arrays ...
def _save_account(self, account, username): """ Called when account is created/updated. With username override. """ # retrieve default project, or use null project if none default_project_name = self._null_project if account.default_project is not None: default_project_name ...
Called when account is created/updated. With username override.
def output(id, url): """ View the files from a job. """ try: experiment = ExperimentClient().get(normalize_job_name(id)) except FloydException: experiment = ExperimentClient().get(id) output_dir_url = "%s/%s/files" % (floyd.floyd_web_host, experiment.name) if url: fl...
View the files from a job.
def fill_zeros(result, x, y, name, fill): """ If this is a reversed op, then flip x,y If we have an integer value (or array in y) and we have 0's, fill them with the fill, return the result. Mask the nan's from x. """ if fill is None or is_float_dtype(result): return result ...
If this is a reversed op, then flip x,y If we have an integer value (or array in y) and we have 0's, fill them with the fill, return the result. Mask the nan's from x.
def set_itunes_subtitle(self): """Parses subtitle from itunes tags and sets value""" try: self.itunes_subtitle = self.soup.find('itunes:subtitle').string except AttributeError: self.itunes_subtitle = None
Parses subtitle from itunes tags and sets value
def stisObsCount(input): """ Input: A stis multiextension file Output: Number of stis science extensions in input """ count = 0 toclose = False if isinstance(input, str): input = fits.open(input) toclose = True for ext in input: if 'extname' in ext.header: ...
Input: A stis multiextension file Output: Number of stis science extensions in input
def validate_email(email): """ Validates an email address Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- email: str Returns ------- bool """ from django.core.validators import validate_email from django.core.exceptions import ValidationErr...
Validates an email address Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- email: str Returns ------- bool
def fix_journal_name(journal, knowledge_base): """Convert journal name to Inspire's short form.""" if not journal: return '', '' if not knowledge_base: return journal, '' if len(journal) < 2: return journal, '' volume = '' if (journal[-1] <= 'Z' and journal[-1] >= 'A') \ ...
Convert journal name to Inspire's short form.
def guest_live_resize_cpus(self, userid, cpu_cnt): """Live resize virtual cpus of guests. :param userid: (str) the userid of the guest to be live resized :param cpu_cnt: (int) The number of virtual cpus that the guest should have in active state after live resize. The value shoul...
Live resize virtual cpus of guests. :param userid: (str) the userid of the guest to be live resized :param cpu_cnt: (int) The number of virtual cpus that the guest should have in active state after live resize. The value should be an integer between 1 and 64.
def seek(self, offset, whence=os.SEEK_SET): """Seeks to an offset within the file-like object. Args: offset (int): offset to seek to. whence (Optional(int)): value that indicates whether offset is an absolute or relative position within the file. Raises: IOError: if the seek fa...
Seeks to an offset within the file-like object. Args: offset (int): offset to seek to. whence (Optional(int)): value that indicates whether offset is an absolute or relative position within the file. Raises: IOError: if the seek failed. OSError: if the seek failed.
def form_invalid(self, form, context=None, **kwargs): """This will return the request with form errors as well as any additional context. """ if not context: context = {} context['errors'] = form.errors return super(ApiFormView, self).render_to_response(conte...
This will return the request with form errors as well as any additional context.
def restore(self, key, ttl, value): """Creates a key associated with a value that is obtained via DUMP.""" return self.execute(b'RESTORE', key, ttl, value)
Creates a key associated with a value that is obtained via DUMP.
def get_node_by_name(self, nodename): """Return the node corresponding with name `nodename` :params nodename: Name of the node :type nodename: str """ nodes = dict((n.name, n) for n in self.get_all_nodes()) try: return nodes[nodename] except KeyError:...
Return the node corresponding with name `nodename` :params nodename: Name of the node :type nodename: str
def __split_nonleaf_node(self, node): """! @brief Performs splitting of the specified non-leaf node. @param[in] node (non_leaf_node): Non-leaf node that should be splitted. @return (list) New pair of non-leaf nodes [non_leaf_node1, non_leaf_node2]. ...
! @brief Performs splitting of the specified non-leaf node. @param[in] node (non_leaf_node): Non-leaf node that should be splitted. @return (list) New pair of non-leaf nodes [non_leaf_node1, non_leaf_node2].
def make_blastcmd_builder( mode, outdir, format_exe=None, blast_exe=None, prefix="ANIBLAST" ): """Returns BLASTcmds object for construction of BLAST commands.""" if mode == "ANIb": # BLAST/formatting executable depends on mode blastcmds = BLASTcmds( BLASTfunctions(construct_makeblastdb_...
Returns BLASTcmds object for construction of BLAST commands.
def annot_boxplot(ax,dmetrics,xoffwithin=0.85,xoff=1.6, yoff=0,annotby='xs', test=False): """ :param dmetrics: hue in index, x in columns #todos #x|y off in % xmin,xmax=ax.get_xlim() (xmax-xmin)+(xmax-xmin)*0.35+xmin """ xlabel=ax.get_xlabel() ...
:param dmetrics: hue in index, x in columns #todos #x|y off in % xmin,xmax=ax.get_xlim() (xmax-xmin)+(xmax-xmin)*0.35+xmin
def gatherInput(**Config): r"""Helps to interactively get user input. """ _type = Config.get('type') while True: try: got = raw_input('%s: ' % getLabel(Config)) except EOFError: got = None if not got and 'default' in Config: return Config['default'] try: return _type(...
r"""Helps to interactively get user input.
def preamble(self, lenient=False): """ Extract the image metadata by reading the initial part of the PNG file up to the start of the ``IDAT`` chunk. All the chunks that precede the ``IDAT`` chunk are read and either processed for metadata or discarded. If the opt...
Extract the image metadata by reading the initial part of the PNG file up to the start of the ``IDAT`` chunk. All the chunks that precede the ``IDAT`` chunk are read and either processed for metadata or discarded. If the optional `lenient` argument evaluates to `True`, c...
def _handle_fetch_response(self, responses): """The callback handling the successful response from the fetch request Delivers the message list to the processor, handles per-message errors (ConsumerFetchSizeTooSmall), triggers another fetch request If the processor is still processing t...
The callback handling the successful response from the fetch request Delivers the message list to the processor, handles per-message errors (ConsumerFetchSizeTooSmall), triggers another fetch request If the processor is still processing the last batch of messages, we defer this process...
def resolve_ports(self, ports): """Resolve NICs not yet bound to bridge(s) If hwaddress provided then returns resolved hwaddress otherwise NIC. """ if not ports: return None hwaddr_to_nic = {} hwaddr_to_ip = {} for nic in list_nics(): # I...
Resolve NICs not yet bound to bridge(s) If hwaddress provided then returns resolved hwaddress otherwise NIC.
def decrypt(self): """Decrypt decrypts the secret and returns the plaintext. Calling decrypt() may incur side effects such as a call to a remote service for decryption. """ if not self._crypter: return b'' try: plaintext = self._crypter.decrypt(self._ciph...
Decrypt decrypts the secret and returns the plaintext. Calling decrypt() may incur side effects such as a call to a remote service for decryption.
def get_portchannel_info_by_intf_output_lacp_actor_max_deskew(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf") config = get_portchannel_info_by_intf output = ET.SubElement(g...
Auto Generated Code
def run_console_rules(self, options_bootstrapper, goals, target_roots): """Runs @console_rules sequentially and interactively by requesting their implicit Goal products. For retryable failures, raises scheduler.ExecutionError. :param list goals: The list of requested goal names as passed on the commandlin...
Runs @console_rules sequentially and interactively by requesting their implicit Goal products. For retryable failures, raises scheduler.ExecutionError. :param list goals: The list of requested goal names as passed on the commandline. :param TargetRoots target_roots: The targets root of the request. :...
def smsc(self, smscNumber): """ Set the default SMSC number to use when sending SMS messages """ if smscNumber != self._smscNumber: if self.alive: self.write('AT+CSCA="{0}"'.format(smscNumber)) self._smscNumber = smscNumber
Set the default SMSC number to use when sending SMS messages
def write(self, out): """Write ICC Profile to the file.""" if not self.rawtagtable: self.rawtagtable = self.rawtagdict.items() tags = tagblock(self.rawtagtable) self.writeHeader(out, 128 + len(tags)) out.write(tags) out.flush() return self
Write ICC Profile to the file.
def list_xattrs(self, path, **kwargs): """Get all of the xattr names for a file or directory. :rtype: list """ return simplejson.loads(_json(self._get(path, 'LISTXATTRS', **kwargs))['XAttrNames'])
Get all of the xattr names for a file or directory. :rtype: list
def parse_logs(log_list, date, machine_name, log_type): """ Parse log file lines in log_type format. """ output = [] count = fail = skip = updated = 0 # Check things are setup correctly try: machine = Machine.objects.get(name=machine_name) except Machine.DoesNotExist: re...
Parse log file lines in log_type format.
def vector(x, y=None, z=0.0): """Return a 3D numpy array representing a vector (of type `numpy.float64`). If `y` is ``None``, assume input is already in the form `[x,y,z]`. """ if y is None: # assume x is already [x,y,z] return np.array(x, dtype=np.float64) return np.array([x, y, z], dtype...
Return a 3D numpy array representing a vector (of type `numpy.float64`). If `y` is ``None``, assume input is already in the form `[x,y,z]`.
def parse(cls, url_path): # type: (str) -> UrlPath """ Parse a string into a URL path (simple eg does not support typing of URL parameters) """ if not url_path: return cls() nodes = [] for node in url_path.rstrip('/').split('/'): # Identif...
Parse a string into a URL path (simple eg does not support typing of URL parameters)
def get_agent_requirement_line(check, version): """ Compose a text line to be used in a requirements.txt file to install a check pinned to a specific version. """ package_name = get_package_name(check) # no manifest if check in ('datadog_checks_base', 'datadog_checks_downloader'): r...
Compose a text line to be used in a requirements.txt file to install a check pinned to a specific version.
def start_list(self): """Start a list.""" self._ordered = False self.start_container(List) self.set_next_paragraph_style('list-paragraph' if self._item_level <= 0 else 'sublist-paragraph')
Start a list.
def call_env_doctree_read(cls, kb_app, sphinx_app: Sphinx, doctree: doctree): """ On doctree-read, do callbacks""" for callback in EventAction.get_callbacks(kb_app, SphinxEvent.DREAD): callback(kb_app, sphinx_ap...
On doctree-read, do callbacks
def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (str(self.name), str(self.description), str(self.type), bool(self.optional), str(self.constraints) if isinstance(self, Constraintable) else "")
Return a tupple of values representing the unicity of the object
def get_thumbnail_of_file(image_name, width): """Return the file contents of the thumbnail of the given file.""" hdr = {'User-Agent': 'Python urllib2'} url = make_thumb_url(image_name, width) req = urllib2.Request(url, headers=hdr) try: logging.debug("Retrieving %s", url) opened = ur...
Return the file contents of the thumbnail of the given file.
def _handle_actionpush(self, length): """Handle the ActionPush action.""" init_pos = self._src.tell() while self._src.tell() < init_pos + length: obj = _make_object("ActionPush") obj.Type = unpack_ui8(self._src) # name and how to read each type pus...
Handle the ActionPush action.
def enable_root_user(self): """ Enables login from any host for the root user and provides the user with a generated root password. """ uri = "/instances/%s/root" % self.id resp, body = self.manager.api.method_post(uri) return body["user"]["password"]
Enables login from any host for the root user and provides the user with a generated root password.
def package_version(): """Get the package version via Git Tag.""" version_path = os.path.join(os.path.dirname(__file__), 'version.py') version = read_version(version_path) write_version(version_path, version) return version
Get the package version via Git Tag.
def add_bucket_key_data(self, bucket, key, data, bucket_type=None): """ Adds a bucket/key/keydata triple to the inputs. :param bucket: the bucket :type bucket: string :param key: the key or list of keys :type key: string :param data: the key-specific data ...
Adds a bucket/key/keydata triple to the inputs. :param bucket: the bucket :type bucket: string :param key: the key or list of keys :type key: string :param data: the key-specific data :type data: string, list, dict, None :param bucket_type: Optional name of a buc...
def restore_package_version_from_recycle_bin(self, package_version_details, feed_id, package_name, package_version): """RestorePackageVersionFromRecycleBin. [Preview API] Restore a package version from the recycle bin to its associated feed. :param :class:`<PyPiRecycleBinPackageVersionDetails> <...
RestorePackageVersionFromRecycleBin. [Preview API] Restore a package version from the recycle bin to its associated feed. :param :class:`<PyPiRecycleBinPackageVersionDetails> <azure.devops.v5_0.py_pi_api.models.PyPiRecycleBinPackageVersionDetails>` package_version_details: Set the 'Deleted' state to 'fa...
def create(tournament, name, **params): """Add a participant to a tournament.""" params.update({"name": name}) return api.fetch_and_parse( "POST", "tournaments/%s/participants" % tournament, "participant", **params)
Add a participant to a tournament.
def make_step_rcont (transition): """Return a ufunc-like step function that is right-continuous. Returns 1 if x >= transition, 0 otherwise. """ if not np.isfinite (transition): raise ValueError ('"transition" argument must be finite number; got %r' % transition) def step_rcont (x): ...
Return a ufunc-like step function that is right-continuous. Returns 1 if x >= transition, 0 otherwise.
def boolean(cls, true_code, false_code=None): """Callback to validate a response code. The returned callback checks whether a given response has a ``status_code`` that is considered good (``true_code``) and raise an appropriate error if not. The optional ``false_code`` allows f...
Callback to validate a response code. The returned callback checks whether a given response has a ``status_code`` that is considered good (``true_code``) and raise an appropriate error if not. The optional ``false_code`` allows for a non-successful status code to return False i...
def delete_namespaced_daemon_set(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_daemon_set # noqa: E501 delete a DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
delete_namespaced_daemon_set # noqa: E501 delete a DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_daemon_set(name, namespace, async_req=True) >>...
def set_maxdays(name, days): ''' Set the maximum age of the password in days :param str name: The username of the account :param int days: The maximum age of the account in days :return: True if successful, False if not :rtype: bool :raises: CommandExecutionError on user not found or any...
Set the maximum age of the password in days :param str name: The username of the account :param int days: The maximum age of the account in days :return: True if successful, False if not :rtype: bool :raises: CommandExecutionError on user not found or any other unknown error CLI Example: ...
def extract_assets(dstore, what): """ Extract an array of assets, optionally filtered by tag. Use it as /extract/assets?taxonomy=RC&taxonomy=MSBC&occupancy=RES """ qdict = parse(what) dic = {} dic1, dic2 = dstore['assetcol/tagcol'].__toh5__() dic.update(dic1) dic.update(dic2) arr...
Extract an array of assets, optionally filtered by tag. Use it as /extract/assets?taxonomy=RC&taxonomy=MSBC&occupancy=RES
def loop_misc(self): """Process miscellaneous network events. Use in place of calling loop() if you wish to call select() or equivalent on. Do not use if you are using the threaded interface loop_start().""" if self._sock is None and self._ssl is None: return MQTT_ERR_NO_CON...
Process miscellaneous network events. Use in place of calling loop() if you wish to call select() or equivalent on. Do not use if you are using the threaded interface loop_start().
def _find_short_paths(self, paths): """ Find short paths of given paths. E.g. if both `/home` and `/home/aoik` exist, only keep `/home`. :param paths: Paths. :return: Set of short paths. """ # Split each path to parts. # E.g. '/h...
Find short paths of given paths. E.g. if both `/home` and `/home/aoik` exist, only keep `/home`. :param paths: Paths. :return: Set of short paths.
def changeLane(self, vehID, laneIndex, duration): """changeLane(string, int, int) -> None Forces a lane change to the lane with the given index; if successful, the lane will be chosen for the given amount of time (in ms). """ self._connection._beginMessage( tc.CMD_SE...
changeLane(string, int, int) -> None Forces a lane change to the lane with the given index; if successful, the lane will be chosen for the given amount of time (in ms).
def element_css_attribute_should_be(self, locator, prop, expected): """Verifies the element identified by `locator` has the expected value for the targeted `prop`. | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | prop | targeted css attribute | background-color...
Verifies the element identified by `locator` has the expected value for the targeted `prop`. | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | prop | targeted css attribute | background-color | | expected | expected value | rgba(0, 128, 0, 1) |
def set_logger(name=None, filename=None, mode='a', level='NOTSET:NOTSET', fmt= '%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelname)-7s] %(message)s', # fmt='[%(levelname)s] %(asctime)s %(message)s', backup_count=5, limit=20480,...
Configure the global logger.
def createSimulate (netParams=None, simConfig=None, output=False): ''' Sequence of commands create, simulate and analyse network ''' from .. import sim (pops, cells, conns, stims, rxd, simData) = sim.create(netParams, simConfig, output=True) sim.simulate() if output: return (pops, cells, conns, st...
Sequence of commands create, simulate and analyse network
def set_emissions(self, scenario): """Set emissions from Pandas DataFrame.""" for section in emissions: for source in emissions[section]: if source not in scenario.columns: continue self._set_timed_array( section, source...
Set emissions from Pandas DataFrame.