Search is not available for this dataset
text
stringlengths
75
104k
def keys(self): """List names of options and positional arguments.""" return self.options.keys() + [p.name for p in self.positional_args]
def values(self): """List values of options and positional arguments.""" return self.options.values() + [p.value for p in self.positional_args]
def items(self): """List values of options and positional arguments.""" return [(p.name, p.value) for p in self.options.values() + self.positional_args]
def getparam(self, key): """Get option or positional argument, by name, index or abbreviation. Abbreviations must be prefixed by a '-' character, like so: ui['-a'] """ try: return self.options[key] except: pass for posarg in self.positiona...
def _add_option(self, option): """Add an Option object to the user interface.""" if option.name in self.options: raise ValueError('name already in use') if option.abbreviation in self.abbreviations: raise ValueError('abbreviation already in use') if option.name in...
def _add_positional_argument(self, posarg): """Append a positional argument to the user interface. Optional positional arguments must be added after the required ones. The user interface can have at most one recurring positional argument, and if present, that argument must be the last...
def read_docs(self, docsfiles): """Read program documentation from a DocParser compatible file. docsfiles is a list of paths to potential docsfiles: parse if present. A string is taken as a list of one item. """ updates = DocParser() for docsfile in _list(docsfiles): ...
def parse_files(self, files=None, sections=None): """Parse configfiles. files <list str>, <str> or None: What files to parse. None means use self.configfiles. New values override old ones. A string value will be interpreted as a list of one item. sections <li...
def _parse_options(self, argv, location): """Parse the options part of an argument list. IN: lsArgs <list str>: List of arguments. Will be altered. location <str>: A user friendly string describing where this data came from. """ observ...
def _parse_positional_arguments(self, argv): """Parse the positional arguments part of an argument list. argv <list str>: List of arguments. Will be altered. """ for posarg in self.positional_args: posarg.parse(argv) if argv: if None in [p.narg...
def parse_argv(self, argv=None, location='Command line.'): """Parse command line arguments. args <list str> or None: The argument list to parse. None means use a copy of sys.argv. argv[0] is ignored. location = '' <str>: A user friendly string describ...
def optionhelp(self, indent=0, maxindent=25, width=79): """Return user friendly help on program options.""" def makelabels(option): labels = '%*s--%s' % (indent, ' ', option.name) if option.abbreviation: labels += ', -' + option.abbreviation return lab...
def posarghelp(self, indent=0, maxindent=25, width=79): """Return user friendly help on positional arguments in the program.""" docs = [] makelabel = lambda posarg: ' ' * indent + posarg.displayname + ': ' helpindent = _autoindent([makelabel(p) for p in self.positional_args], indent, max...
def format_usage(self, usage=None): """Return a formatted usage string. If usage is None, use self.docs['usage'], and if that is also None, generate one. """ if usage is None: usage = self.docs['usage'] if usage is not None: return usage...
def _wrap(self, text, indent=0, width=0): """Textwrap an indented paragraph. ARGS: width = 0 <int>: Maximum allowed page width. 0 means use default from self.iMaxHelpWidth. """ text = _list(text) if not width: width = self.width ...
def _wraptext(self, text, indent=0, width=0): """Shorthand for '\n'.join(self._wrap(par, indent, width) for par in text).""" return '\n'.join(self._wrap(par, indent, width) for par in text)
def _wrapusage(self, usage=None, width=0): """Textwrap usage instructions. ARGS: width = 0 <int>: Maximum allowed page width. 0 means use default from self.iMaxHelpWidth. """ if not width: width = self.width return textwrap.fill('USAGE...
def shorthelp(self, width=0): """Return brief help containing Title and usage instructions. ARGS: width = 0 <int>: Maximum allowed page width. 0 means use default from self.iMaxHelpWidth. """ out = [] out.append(self._wrap(self.docs['title'], widt...
def strsettings(self, indent=0, maxindent=25, width=0): """Return user friendly help on positional arguments. indent is the number of spaces preceeding the text on each line. The indent of the documentation is dependent on the length of the longest label that is short...
def settingshelp(self, width=0): """Return a summary of program options, their values and origins. width is maximum allowed page width, use self.width if 0. """ out = [] out.append(self._wrap(self.docs['title'], width=width)) if self.docs['description']: ...
def launch(self, argv=None, showusageonnoargs=False, width=0, helphint="Use with --help for more information.\n", debug_parser=False): """Do the usual stuff to initiallize the program. Read config files and parse argumen...
def parse(self, file): """Parse text blocks from a file.""" if isinstance(file, basestring): file = open(file) line_number = 0 label = None block = self.untagged for line in file: line_number += 1 line = line.rstrip('\n') if...
def get_format(format): """Get a format object. If format is a format object, return unchanged. If it is a string matching one of the BaseFormat subclasses in the tui.formats module (case insensitive), return an instance of that class. Otherwise assume it'a factory function for Formats (such ...
def parsestr(self, argstr): """Parse arguments found in settings files. argstr is the string that should be parsed. Use e.g. '""' to pass an empty string. if self.nargs > 1 a list of parsed values will be returned. NOTE: formats with nargs == 0 or None probably want to...
def parse_argument(self, arg): """Parse a single argument. Lookup arg in self.specials, or call .to_python() if absent. Raise BadArgument on errors. """ lookup = self.casesensitive and arg or arg.lower() if lookup in self.special: return self.special...
def parse(self, argv): """Pop, parse and return the first self.nargs items from args. if self.nargs > 1 a list of parsed values will be returned. Raise BadNumberOfArguments or BadArgument on errors. NOTE: argv may be modified in place by this method. """ ...
def present(self, value): """Return a user-friendly representation of a value. Lookup value in self.specials, or call .to_literal() if absent. """ for k, v in self.special.items(): if v == value: return k return self.to_literal(value, *self.ar...
def parsestr(self, argstr): """Parse arguments found in settings files. Use the values in self.true for True in settings files, or those in self.false for False, case insensitive. """ argv = shlex.split(argstr, comments=True) if len(argv) != 1: raise...
def parse(self, argv): """Pop, parse and return the first arg from argv. The arg will be .split() based on self.separator and the (optionally stripped) items will be parsed by self.format and returned as a list. Raise BadNumberOfArguments or BadArgument on errors. ...
def present(self, value): """Return a user-friendly representation of a value. Lookup value in self.specials, or call .to_literal() if absent. """ for k, v in self.special.items(): if v == value: return k return self.separator.join(self.format...
def get_separator(self, i): """Return the separator that preceding format i, or '' for i == 0.""" return i and self.separator[min(i - 1, len(self.separator) - 1)] or ''
def parse(self, argv): """Pop, parse and return the first arg from argv. The arg will be repeatedly .split(x, 1) based on self.get_separator() and the (optionally stripped) items will be parsed by self.format and returned as a list. Raise BadNumberOfArguments or BadAr...
def present(self, value): """Return a user-friendly representation of a value. Lookup value in self.specials, or call .to_literal() if absent. """ for k, v in self.special.items(): if v == value: return k return ''.join(self.get_separator(i) +...
def authorize_url(self): """ Return a URL to redirect the user to for OAuth authentication. """ auth_url = OAUTH_ROOT + '/authorize' params = { 'client_id': self.client_id, 'redirect_uri': self.redirect_uri, } return "{}?{}".format(auth_url...
def exchange_token(self, code): """ Exchange the authorization code for an access token. """ access_token_url = OAUTH_ROOT + '/access_token' params = { 'client_id': self.client_id, 'client_secret': self.client_secret, 'redirect_uri': self.redir...
def get_open_port() -> int: """ Gets a PORT that will (probably) be available on the machine. It is possible that in-between the time in which the open PORT of found and when it is used, another process may bind to it instead. :return: the (probably) available PORT """ free_socket = socket.s...
def extract_version_number(string: str) -> str: """ Extracts a version from a string in the form: `.*[0-9]+(_[0-9]+)*.*`, e.g. Irods4_1_9CompatibleController. If the string contains multiple version numbers, the first (from left) is extracted. Will raise a `ValueError` if there is no version number in...
def acquire(self, *args, **kwargs): """ Wraps Lock.acquire """ with self._stat_lock: self._waiting += 1 self._lock.acquire(*args, **kwargs) with self._stat_lock: self._locked = True self._waiting -= 1
def release(self): """ Wraps Lock.release """ self._lock.release() with self._stat_lock: self._locked = False self._last_released = datetime.now()
def default_decoder(self, obj): """Handle a dict that might contain a wrapped state for a custom type.""" typename, marshalled_state = self.unwrap_callback(obj) if typename is None: return obj try: cls, unmarshaller = self.serializer.unmarshallers[typename] ...
def wrap_state_dict(self, typename: str, state) -> Dict[str, Any]: """ Wrap the marshalled state in a dictionary. The returned dictionary has two keys, corresponding to the ``type_key`` and ``state_key`` options. The former holds the type name and the latter holds the marshalled state. ...
def unwrap_state_dict(self, obj: Dict[str, Any]) -> Union[Tuple[str, Any], Tuple[None, None]]: """Unwraps a marshalled state previously wrapped using :meth:`wrap_state_dict`.""" if len(obj) == 2: typename = obj.get(self.type_key) state = obj.get(self.state_key) if typ...
def publish(quiet, dataset_uri): """Enable HTTP access to a dataset. This only works on datasets in some systems. For example, datasets stored in AWS S3 object storage and Microsoft Azure Storage can be published as datasets accessible over HTTP. A published dataset is world readable. """ acces...
def register_custom_type( self, cls: type, marshaller: Optional[Callable[[Any], Any]] = default_marshaller, unmarshaller: Union[Callable[[Any, Any], None], Callable[[Any], Any], None] = default_unmarshaller, *, typename: str = None, wrap_state: bool = ...
def _prompt_for_values(d): """Update the descriptive metadata interactively. Uses values entered by the user. Note that the function keeps recursing whenever a value is another ``CommentedMap`` or a ``list``. The function works as passing dictionaries and lists into a function edits the values in p...
def create(quiet, name, base_uri, symlink_path): """Create a proto dataset.""" _validate_name(name) admin_metadata = dtoolcore.generate_admin_metadata(name) parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri) if parsed_base_uri.scheme == "symlink": if symlink_path is None: ...
def name(dataset_uri, new_name): """ Report / update the name of the dataset. It is only possible to update the name of a proto dataset, i.e. a dataset that has not yet been frozen. """ if new_name != "": _validate_name(new_name) try: dataset = dtoolcore.ProtoDataSe...
def interactive(proto_dataset_uri): """Interactive prompting to populate the readme.""" proto_dataset = dtoolcore.ProtoDataSet.from_uri( uri=proto_dataset_uri, config_path=CONFIG_PATH) # Create an CommentedMap representation of the yaml readme template. readme_template = _get_readme_tem...
def edit(dataset_uri): """Default editor updating of readme content. """ try: dataset = dtoolcore.ProtoDataSet.from_uri( uri=dataset_uri, config_path=CONFIG_PATH ) except dtoolcore.DtoolCoreTypeError: dataset = dtoolcore.DataSet.from_uri( uri=d...
def show(dataset_uri): """Show the descriptive metadata in the readme.""" try: dataset = dtoolcore.ProtoDataSet.from_uri( uri=dataset_uri, config_path=CONFIG_PATH ) except dtoolcore.DtoolCoreTypeError: dataset = dtoolcore.DataSet.from_uri( uri=data...
def write(proto_dataset_uri, input): """Use YAML from a file or stdin to populate the readme. To stream content from stdin use "-", e.g. echo "desc: my data" | dtool readme write <DS_URI> - """ proto_dataset = dtoolcore.ProtoDataSet.from_uri( uri=proto_dataset_uri ) _validate_and_p...
def item(proto_dataset_uri, input_file, relpath_in_dataset): """Add a file to the proto dataset.""" proto_dataset = dtoolcore.ProtoDataSet.from_uri( proto_dataset_uri, config_path=CONFIG_PATH) if relpath_in_dataset == "": relpath_in_dataset = os.path.basename(input_file) proto_da...
def metadata(proto_dataset_uri, relpath_in_dataset, key, value): """Add metadata to a file in the proto dataset.""" proto_dataset = dtoolcore.ProtoDataSet.from_uri( uri=proto_dataset_uri, config_path=CONFIG_PATH) proto_dataset.add_item_metadata( handle=relpath_in_dataset, key...
def freeze(proto_dataset_uri): """Convert a proto dataset into a dataset. This step is carried out after all files have been added to the dataset. Freezing a dataset finalizes it with a stamp marking it as frozen. """ proto_dataset = dtoolcore.ProtoDataSet.from_uri( uri=proto_dataset_uri, ...
def copy(resume, quiet, dataset_uri, dest_base_uri): """DEPRECATED: Copy a dataset to a different location.""" click.secho( "The ``dtool copy`` command is deprecated", fg="red", err=True ) click.secho( "Use ``dtool cp`` instead", fg="red", err=True ) ...
def cp(resume, quiet, dataset_uri, dest_base_uri): """Copy a dataset to a different location.""" _copy(resume, quiet, dataset_uri, dest_base_uri)
def compress(obj, level=6, return_type="bytes"): """Compress anything to bytes or string. :params obj: :params level: :params return_type: if bytes, then return bytes; if str, then return base64.b64encode bytes in utf-8 string. """ if isinstance(obj, binary_type): b = zlib.comp...
def _parsems(value): """Parse a I[.F] seconds value into (seconds, microseconds).""" if "." not in value: return int(value), 0 else: i, f = value.split(".") return int(i), int(f.ljust(6, "0")[:6])
def get_token(self): """ This function breaks the time string into lexical units (tokens), which can be parsed by the parser. Lexical units are demarcated by changes in the character set, so any continuous string of letters is considered one unit, any continuous string of numbers...
def find_probable_year_index(self, tokens): """ attempt to deduce if a pre 100 year was lost due to padded zeros being taken off """ for index, token in enumerate(self): potential_year_tokens = _ymd.find_potential_year_tokens( token, tokens) ...
def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs): """ Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object...
def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, fuzzy_with_tokens=False): """ Private method which performs the heavy lifting of parsing, called from ``parse()``, which passes on its ``kwargs`` to this function. :param timestr: The string...
def tzname_in_python2(namefunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """ def adjust_encoding(*args, **kwargs): name = namefunc(*args, **kwargs) if name is not None and not...
def _validate_fromutc_inputs(f): """ The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``. """ @wraps(f) def fromutc(self, dt): if not isinstance(dt, datetime): raise TypeError("fromutc() requires a ...
def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. ...
def _fold_status(self, dt_utc, dt_wall): """ Determine the fold status of a "wall" datetime, given a representation of the same datetime as a (naive) UTC datetime. This is calculated based on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all datetimes, and tha...
def _fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the da...
def fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the dat...
def fromutc(self, dt): """ Given a datetime in UTC, return local time """ if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") # Get transitions - if there ...
def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. ...
def strip_comment_line_with_symbol(line, start): """Strip comments from line string. """ parts = line.split(start) counts = [len(findall(r'(?:^|[^"\\]|(?:\\\\|\\")+)(")', part)) for part in parts] total = 0 for nr, count in enumerate(counts): total += count if total...
def strip_comments(string, comment_symbols=frozenset(('#', '//'))): """Strip comments from json string. :param string: A string containing json with comments started by comment_symbols. :param comment_symbols: Iterable of symbols that start a line comment (default # or //). :return: The string with the...
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* filename is the timezone tarball from ftp.iana.org/tz. """ tmpdir = tempfile.mkdtemp() zonedir = os.path.join(tmpdir, "zoneinfo") moduledir = os....
def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ first = datetime.datetime(year, month, 1, hour, minute) # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), # Because 7 % 7 = 0 weekdayo...
def valuestodict(key): """Convert a registry key's values to a dictionary.""" dout = {} size = winreg.QueryInfoKey(key)[1] tz_res = None for i in range(size): key_name, value, dtype = winreg.EnumValue(key, i) if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN: ...
def load_name(self, offset): """ Load a timezone name from a DLL offset (integer). >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.load_name(112)) 'Eastern Standard Time' :param offset: A positive integer value referring to a str...
def name_from_string(self, tzname_str): """ Parse strings as returned from the Windows registry into the time zone name as defined in the registry. >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.name_from_string('@tzres.dll,-251')) 'Dateline...
def transitions(self, year): """ For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. ...
def get_zonefile_instance(new_instance=False): """ This is a convenience function which provides a :class:`ZoneInfoFile` instance using the data provided by the ``dateutil`` package. By default, it caches a single instance of the ZoneInfoFile object and returns that. :param new_instance: If...
def gettz(name): """ This retrieves a time zone from the local zoneinfo tarball that is packaged with dateutil. :param name: An IANA-style time zone name, as found in the zoneinfo file. :return: Returns a :class:`dateutil.tz.tzfile` time zone object. .. warning:: It is...
def gettz_db_metadata(): """ Get the zonefile metadata See `zonefile_metadata`_ :returns: A dictionary with the database metadata .. deprecated:: 2.6 See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, query the attribute ``zoneinfo.ZoneInfoFile.metadata``. ...
def get_config(jid): """Get the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS. If the JID does not match any rule, ``False`` is returned. """ acls = getattr(settings, 'XMPP_HTTP_UPLOAD_ACCESS', (('.*', False), )) for regex, config in acls: if isinstance(regex, six.strin...
def datetime_exists(dt, tz=None): """ Given a datetime and a time zone, determine whether or not a given datetime would fall in a gap. :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with...
def datetime_ambiguous(dt, tz=None): """ Given a datetime and a time zone, determine whether or not a given datetime is ambiguous (i.e if there are two times differentiated only by their DST status). :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` ...
def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. ...
def _set_tzdata(self, tzobj): """ Set the time zone data of this object from a _tzfile object """ # Copy the relevant attributes over as private attributes for attr in _tzfile.attrs: setattr(self, '_' + attr, getattr(tzobj, attr))
def fromutc(self, dt): """ The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. :param dt: A :py:class:`datetime.datetime` object. :raises TypeError: Raised if ``dt`` is not a :py:class:`datetime.datetime` object. :raises ValueError: ...
def is_ambiguous(self, dt, idx=None): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. ...
def transitions(self, year): """ For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. ...
def get(self, tzid=None): """ Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. :param tzid: If there is exactly one time zone available, omitting ``tzid`` or passing :py:const:`None` value returns it. Otherwise a valid key (which can be retrieve...
def normalized(self): """ Return a version of this object represented entirely using integer values for the relative attributes. >>> relativedelta(days=1.5, hours=2).normalized() relativedelta(days=1, hours=14) :return: Returns a :class:`dateutil.relativedel...
def get_algorithm(alg: str) -> Callable: """ :param alg: The name of the requested `JSON Web Algorithm <https://tools.ietf.org/html/rfc7519#ref-JWA>`_. `RFC7518 <https://tools.ietf.org/html/rfc7518#section-3.2>`_ is related. :type alg: str :return: The requested algorithm. :rtype: Callable :rais...
def _hash(secret: bytes, data: bytes, alg: str) -> bytes: """ Create a new HMAC hash. :param secret: The secret used when hashing data. :type secret: bytes :param data: The data to hash. :type data: bytes :param alg: The algorithm to use when hashing `data`. :type alg: str :return: ...
def encode(secret: Union[str, bytes], payload: dict = None, alg: str = default_alg, header: dict = None) -> str: """ :param secret: The secret used to encode the token. :type secret: Union[str, bytes] :param payload: The payload to be encoded in the token. :type payload: dict :param a...
def decode(secret: Union[str, bytes], token: Union[str, bytes], alg: str = default_alg) -> Tuple[dict, dict]: """ Decodes the given token's header and payload and validates the signature. :param secret: The secret used to decode the token. Must match the secret used when creating the tok...
def compare_signature(expected: Union[str, bytes], actual: Union[str, bytes]) -> bool: """ Compares the given signatures. :param expected: The expected signature. :type expected: Union[str, bytes] :param actual: The actual signature. :type actual: Union[str, bytes] :re...
def compare_token(expected: Union[str, bytes], actual: Union[str, bytes]) -> bool: """ Compares the given tokens. :param expected: The expected token. :type expected: Union[str, bytes] :param actual: The actual token. :type actual: Union[str, bytes] :return: Do the tokens ...
def header(self) -> dict: """ :return: Token header. :rtype: dict """ header = {} if isinstance(self._header, dict): header = self._header.copy() header.update(self._header) header.update({ 'type': 'JWT', 'alg': self...
def valid(self, time: int = None) -> bool: """ Is the token valid? This method only checks the timestamps within the token and compares them against the current time if none is provided. :param time: The timestamp to validate against :type time: Union[int, None] :return:...
def _pop_claims_from_payload(self): """ Check for registered claims in the payload and move them to the registered_claims property, overwriting any extant claims. """ claims_in_payload = [k for k in self.payload.keys() if k in registered_claims.values...