index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
37,787
salesforce_bulk.salesforce_bulk
parse_error_result_xml
null
def parse_error_result_xml(self, error_xml): return { 'fields': [x.text for x in error_xml.findall('{%s}fields' % self.jobNS)], 'message': error_xml.find('{%s}message' % self.jobNS).text, 'statusCode': error_xml.find('{%s}statusCode' % self.jobNS).text, }
(self, error_xml)
37,788
salesforce_bulk.salesforce_bulk
parse_response
null
def parse_response(self, resp): if resp.headers['Content-Type'] == 'application/json': return resp.json() tree = ET.fromstring(resp.content) if nsclean.sub("", tree.tag) == 'batchInfoList': results = [] for subtree in tree: result = {} results.append(result) for child in subtree: result[nsclean.sub("", child.tag)] = child.text return results result = {} for child in tree: result[nsclean.sub("", child.tag)] = child.text return result
(self, resp)
37,789
salesforce_bulk.salesforce_bulk
post_batch
null
def post_batch(self, job_id, data_generator): job_content_type = self.job_content_types[job_id] http_content_type = job_to_http_content_type[job_content_type] uri = self.endpoint + "/job/%s/batch" % job_id headers = self.headers(content_type=http_content_type) resp = requests.post(uri, data=data_generator, headers=headers) self.check_status(resp) result = self.parse_response(resp) batch_id = result['id'] self.batches[batch_id] = job_id return batch_id
(self, job_id, data_generator)
37,790
salesforce_bulk.salesforce_bulk
post_mapping_file
null
def post_mapping_file(self, job_id, mapping_data): job_content_type = 'CSV' http_content_type = job_to_http_content_type[job_content_type] uri = self.endpoint + "/job/%s/spec" % job_id headers = self.headers(content_type=http_content_type) resp = requests.post(uri, data=mapping_data, headers=headers) self.check_status(resp) if resp.status_code != 201: raise Exception("Unable to upload mapping file")
(self, job_id, mapping_data)
37,791
salesforce_bulk.salesforce_bulk
query
null
def query(self, job_id, soql, contentType='CSV'): if job_id is None: job_id = self.create_job( re.search(re.compile(r"from (\w+)", re.I), soql).group(1), "query", contentType=contentType) job_content_type = self.job_content_types.get(job_id, contentType) http_content_type = job_to_http_content_type[job_content_type] headers = self.headers(content_type=http_content_type) uri = self.endpoint + "/job/%s/batch" % job_id resp = requests.post(uri, data=soql, headers=headers) self.check_status(resp) result = self.parse_response(resp) batch_id = result['id'] self.batches[batch_id] = job_id return batch_id
(self, job_id, soql, contentType='CSV')
37,792
salesforce_bulk.salesforce_bulk
raise_error
null
def raise_error(self, message, status_code=None): if status_code: message = "[{0}] {1}".format(status_code, message) raise BulkApiError(message, status_code=status_code)
(self, message, status_code=None)
37,793
salesforce_bulk.salesforce_bulk
wait_for_batch
null
def wait_for_batch(self, job_id, batch_id, timeout=60 * 10, sleep_interval=10): waited = 0 while not self.is_batch_done(batch_id, job_id) and waited < timeout: time.sleep(sleep_interval) waited += sleep_interval
(self, job_id, batch_id, timeout=600, sleep_interval=10)
37,794
salesforce_bulk.salesforce_bulk
UploadResult
UploadResult(id, success, created, error)
from salesforce_bulk.salesforce_bulk import UploadResult
(id, success, created, error)
37,796
namedtuple_UploadResult
__new__
Create new instance of UploadResult(id, success, created, error)
from builtins import function
(_cls, id, success, created, error)
37,799
collections
_replace
Return a new UploadResult object replacing specified fields with new values
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) """ # Validate the field names. At the user's option, either generate an error # message or automatically replace the field name with a valid name. if isinstance(field_names, str): field_names = field_names.replace(',', ' ').split() field_names = list(map(str, field_names)) typename = _sys.intern(str(typename)) if rename: seen = set() for index, name in enumerate(field_names): if (not name.isidentifier() or _iskeyword(name) or name.startswith('_') or name in seen): field_names[index] = f'_{index}' seen.add(name) for name in [typename] + field_names: if type(name) is not str: raise TypeError('Type names and field names must be strings') if not name.isidentifier(): raise ValueError('Type names and field names must be valid ' f'identifiers: {name!r}') if _iskeyword(name): raise ValueError('Type names and field names cannot be a ' f'keyword: {name!r}') seen = set() for name in field_names: if name.startswith('_') and not rename: raise ValueError('Field names cannot start with an underscore: ' f'{name!r}') if name in seen: raise ValueError(f'Encountered duplicate field name: {name!r}') seen.add(name) field_defaults = {} if defaults is not None: defaults = tuple(defaults) if len(defaults) > len(field_names): raise TypeError('Got more default values than field names') field_defaults = dict(reversed(list(zip(reversed(field_names), reversed(defaults))))) # Variables used in the methods and docstrings field_names = tuple(map(_sys.intern, field_names)) num_fields = len(field_names) arg_list = ', '.join(field_names) if num_fields == 1: arg_list += ',' repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')' tuple_new = tuple.__new__ _dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip # Create all the named tuple methods to be added to the class namespace namespace = { '_tuple_new': tuple_new, '__builtins__': {}, '__name__': f'namedtuple_{typename}', } code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))' __new__ = eval(code, namespace) __new__.__name__ = '__new__' __new__.__doc__ = f'Create new instance of {typename}({arg_list})' if defaults is not None: __new__.__defaults__ = defaults @classmethod def _make(cls, iterable): result = tuple_new(cls, iterable) if _len(result) != num_fields: raise TypeError(f'Expected {num_fields} arguments, got {len(result)}') return result _make.__func__.__doc__ = (f'Make a new {typename} object from a sequence ' 'or iterable') def _replace(self, /, **kwds): result = self._make(_map(kwds.pop, field_names, self)) if kwds: raise ValueError(f'Got unexpected field names: {list(kwds)!r}') return result _replace.__doc__ = (f'Return a new {typename} object replacing specified ' 'fields with new values') def __repr__(self): 'Return a nicely formatted representation string' return self.__class__.__name__ + repr_fmt % self def _asdict(self): 'Return a new dict which maps field names to their values.' return _dict(_zip(self._fields, self)) def __getnewargs__(self): 'Return self as a plain tuple. Used by copy and pickle.' return _tuple(self) # Modify function metadata to help with introspection and debugging for method in ( __new__, _make.__func__, _replace, __repr__, _asdict, __getnewargs__, ): method.__qualname__ = f'{typename}.{method.__name__}' # Build-up the class namespace dictionary # and use type() to build the result class class_namespace = { '__doc__': f'{typename}({arg_list})', '__slots__': (), '_fields': field_names, '_field_defaults': field_defaults, '__new__': __new__, '_make': _make, '_replace': _replace, '__repr__': __repr__, '_asdict': _asdict, '__getnewargs__': __getnewargs__, '__match_args__': field_names, } for index, name in enumerate(field_names): doc = _sys.intern(f'Alias for field number {index}') class_namespace[name] = _tuplegetter(index, doc) result = type(typename, (tuple,), class_namespace) # For pickling to work, the __module__ variable needs to be set to the frame # where the named tuple is created. Bypass this step in environments where # sys._getframe is not defined (Jython for example) or sys._getframe is not # defined for arguments greater than 0 (IronPython), or where the user has # specified a particular module. if module is None: try: module = _sys._getframe(1).f_globals.get('__name__', '__main__') except (AttributeError, ValueError): pass if module is not None: result.__module__ = module return result
(self, /, **kwds)
37,804
pygeohash.geohash
decode
Decode geohash, returning two float with latitude and longitude containing only relevant digits and with trailing zeroes removed.
def decode(geohash): """ Decode geohash, returning two float with latitude and longitude containing only relevant digits and with trailing zeroes removed. """ lat, lon, lat_err, lon_err = decode_exactly(geohash) # Format to the number of decimals that are known lats = "%.*f" % (max(1, int(round(-log10(lat_err)))) - 1, lat) lons = "%.*f" % (max(1, int(round(-log10(lon_err)))) - 1, lon) if '.' in lats: lats = lats.rstrip('0') if '.' in lons: lons = lons.rstrip('0') return float(lats), float(lons)
(geohash)
37,805
pygeohash.geohash
decode_exactly
Decode the geohash to its exact values, including the error margins of the result. Returns four float values: latitude, longitude, the plus/minus error for latitude (as a positive number) and the plus/minus error for longitude (as a positive number).
def decode_exactly(geohash): """ Decode the geohash to its exact values, including the error margins of the result. Returns four float values: latitude, longitude, the plus/minus error for latitude (as a positive number) and the plus/minus error for longitude (as a positive number). """ lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0) lat_err, lon_err = 90.0, 180.0 is_even = True for c in geohash: cd = __decodemap[c] for mask in [16, 8, 4, 2, 1]: if is_even: # adds longitude info lon_err /= 2 if cd & mask: lon_interval = ((lon_interval[0]+lon_interval[1])/2, lon_interval[1]) else: lon_interval = (lon_interval[0], (lon_interval[0]+lon_interval[1])/2) else: # adds latitude info lat_err /= 2 if cd & mask: lat_interval = ((lat_interval[0]+lat_interval[1])/2, lat_interval[1]) else: lat_interval = (lat_interval[0], (lat_interval[0]+lat_interval[1])/2) is_even = not is_even lat = (lat_interval[0] + lat_interval[1]) / 2 lon = (lon_interval[0] + lon_interval[1]) / 2 return lat, lon, lat_err, lon_err
(geohash)
37,807
pygeohash.stats
eastern
Takes in an iterable of geohashes and returns the easternmost position of the group as a geohash. :param geohashes: :return:
def eastern(geohashes): """ Takes in an iterable of geohashes and returns the easternmost position of the group as a geohash. :param geohashes: :return: """ latlons = [decode(x) for x in geohashes] latlons = sorted(latlons, key=lambda x: x[1], reverse=True) return encode(latlons[0][0], latlons[0][1])
(geohashes)
37,808
pygeohash.geohash
encode
Encode a position given in float arguments latitude, longitude to a geohash which will have the character count precision.
def encode(latitude, longitude, precision=12): """ Encode a position given in float arguments latitude, longitude to a geohash which will have the character count precision. """ lat_interval = (-90.0, 90.0) lon_interval = (-180.0, 180.0) geohash = [] bits = [16, 8, 4, 2, 1] bit = 0 ch = 0 even = True while len(geohash) < precision: if even: mid = (lon_interval[0] + lon_interval[1]) / 2 if longitude > mid: ch |= bits[bit] lon_interval = (mid, lon_interval[1]) else: lon_interval = (lon_interval[0], mid) else: mid = (lat_interval[0] + lat_interval[1]) / 2 if latitude > mid: ch |= bits[bit] lat_interval = (mid, lat_interval[1]) else: lat_interval = (lat_interval[0], mid) even = not even if bit < 4: bit += 1 else: geohash += __base32[ch] bit = 0 ch = 0 return ''.join(geohash)
(latitude, longitude, precision=12)
37,810
pygeohash.distances
geohash_approximate_distance
Returns the approximate great-circle distance between two geohashes in meters. :param geohash_1: :param geohash_2: :return:
def geohash_approximate_distance(geohash_1, geohash_2, check_validity=False): """ Returns the approximate great-circle distance between two geohashes in meters. :param geohash_1: :param geohash_2: :return: """ if check_validity: if len([x for x in geohash_1 if x in __base32]) != len(geohash_1): raise ValueError('Geohash 1: %s is not a valid geohash' % (geohash_1, )) if len([x for x in geohash_2 if x in __base32]) != len(geohash_2): raise ValueError('Geohash 2: %s is not a valid geohash' % (geohash_2, )) # normalize the geohashes to the length of the shortest len_1 = len(geohash_1) len_2 = len(geohash_2) if len_1 > len_2: geohash_1 = geohash_1[:len_2] elif len_2 > len_1: geohash_2 = geohash_2[:len_1] # find how many leading characters are matching matching = 0 for g1, g2 in zip(geohash_1, geohash_2): if g1 == g2: matching += 1 else: break # we only have precision metrics up to 10 characters if matching > 10: matching = 10 return _PRECISION[matching]
(geohash_1, geohash_2, check_validity=False)
37,811
pygeohash.distances
geohash_haversine_distance
converts the geohashes to lat/lon and then calculates the haversine great circle distance in meters. :param geohash_1: :param geohash_2: :return:
def geohash_haversine_distance(geohash_1, geohash_2): """ converts the geohashes to lat/lon and then calculates the haversine great circle distance in meters. :param geohash_1: :param geohash_2: :return: """ lat_1, lon_1 = decode(geohash_1) lat_2, lon_2 = decode(geohash_2) R = 6371000 phi_1 = math.radians(lat_1) phi_2 = math.radians(lat_2) delta_phi = math.radians(lat_2-lat_1) delta_lambda = math.radians(lon_2-lon_1) a = math.sin(delta_phi/2.0) * math.sin(delta_phi/2.0) + math.cos(phi_1) * math.cos(phi_2) * math.sin(delta_lambda/2) * math.sin(delta_lambda/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) return R * c
(geohash_1, geohash_2)
37,812
pygeohash.stats
mean
Takes in an iterable of geohashes and returns the mean position of the group as a geohash. :param geohashes: :return:
def mean(geohashes): """ Takes in an iterable of geohashes and returns the mean position of the group as a geohash. :param geohashes: :return: """ latlons = [decode(x) for x in geohashes] count = len(latlons) return encode(float(sum([x[0] for x in latlons])) / count, float(sum([x[1] for x in latlons])) / count)
(geohashes)
37,813
pygeohash.stats
northern
Takes in an iterable of geohashes and returns the northernmost position of the group as a geohash. :param geohashes: :return:
def northern(geohashes): """ Takes in an iterable of geohashes and returns the northernmost position of the group as a geohash. :param geohashes: :return: """ latlons = [decode(x) for x in geohashes] latlons = sorted(latlons, key=lambda x: x[0], reverse=True) return encode(latlons[0][0], latlons[0][1])
(geohashes)
37,814
pygeohash.stats
southern
Takes in an iterable of geohashes and returns the southernmost position of the group as a geohash. :param geohashes: :return:
def southern(geohashes): """ Takes in an iterable of geohashes and returns the southernmost position of the group as a geohash. :param geohashes: :return: """ latlons = [decode(x) for x in geohashes] latlons = sorted(latlons, key=lambda x: x[0], reverse=False) return encode(latlons[0][0], latlons[0][1])
(geohashes)
37,816
pygeohash.stats
std
Calculates the standard deviation of a set of geohashes (in meters) :param geohashes: :return:
def std(geohashes): """ Calculates the standard deviation of a set of geohashes (in meters) :param geohashes: :return: """ return math.sqrt(variance(geohashes))
(geohashes)
37,817
pygeohash.stats
variance
Calculates the variance of a set of geohashes (in meters) :param geohashes: :return:
def variance(geohashes): """ Calculates the variance of a set of geohashes (in meters) :param geohashes: :return: """ mean_v = mean(geohashes) dists = [geohash_haversine_distance(x, mean_v) for x in geohashes] var = sum([x ** 2 for x in dists]) / float(len(dists)) return var
(geohashes)
37,818
pygeohash.stats
western
Takes in an iterable of geohashes and returns the westernmost position of the group as a geohash. :param geohashes: :return:
def western(geohashes): """ Takes in an iterable of geohashes and returns the westernmost position of the group as a geohash. :param geohashes: :return: """ latlons = [decode(x) for x in geohashes] latlons = sorted(latlons, key=lambda x: x[1], reverse=False) return encode(latlons[0][0], latlons[0][1])
(geohashes)
37,819
pep562
Pep562
Backport of PEP 562 <https://pypi.org/search/?q=pep562>. Wraps the module in a class that exposes the mechanics to override `__dir__` and `__getattr__`. The given module will be searched for overrides of `__dir__` and `__getattr__` and use them when needed.
class Pep562(object): """ Backport of PEP 562 <https://pypi.org/search/?q=pep562>. Wraps the module in a class that exposes the mechanics to override `__dir__` and `__getattr__`. The given module will be searched for overrides of `__dir__` and `__getattr__` and use them when needed. """ def __init__(self, name): """Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7.""" self._module = sys.modules[name] self._get_attr = getattr(self._module, '__getattr__', None) self._get_dir = getattr(self._module, '__dir__', None) sys.modules[name] = self def __dir__(self): """Return the overridden `dir` if one was provided, else apply `dir` to the module.""" return self._get_dir() if self._get_dir else dir(self._module) def __getattr__(self, name): """Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.""" try: return getattr(self._module, name) except AttributeError: if self._get_attr: return self._get_attr(name) raise
(name)
37,820
pep562
__dir__
Return the overridden `dir` if one was provided, else apply `dir` to the module.
def __dir__(self): """Return the overridden `dir` if one was provided, else apply `dir` to the module.""" return self._get_dir() if self._get_dir else dir(self._module)
(self)
37,821
pep562
__getattr__
Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.
def __getattr__(self, name): """Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.""" try: return getattr(self._module, name) except AttributeError: if self._get_attr: return self._get_attr(name) raise
(self, name)
37,822
pep562
__init__
Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7.
def __init__(self, name): """Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7.""" self._module = sys.modules[name] self._get_attr = getattr(self._module, '__getattr__', None) self._get_dir = getattr(self._module, '__dir__', None) sys.modules[name] = self
(self, name)
37,823
pep562
Version
Get the version (PEP 440). A biased approach to the PEP 440 semantic version. Provides a tuple structure which is sorted for comparisons `v1 > v2` etc. (major, minor, micro, release type, pre-release build, post-release build, development release build) Release types are named in is such a way they are comparable with ease. Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get development status for setup files. How it works (currently): - You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`. - To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`. The dot is used to ensure all development specifiers are sorted before `alpha`. You can specify a `dev` number for development builds, but do not have to as implicit development releases are allowed. - You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not allow implicit prereleases. - You can optionally set `post` to a value greater than zero to make the build a post release. While post releases are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically does not allow implicit post releases. - It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`. Acceptable version releases: ``` Version(1, 0, 0, "final") 1.0 Version(1, 2, 0, "final") 1.2 Version(1, 2, 3, "final") 1.2.3 Version(1, 2, 0, ".dev-alpha", pre=4) 1.2a4 Version(1, 2, 0, ".dev-beta", pre=4) 1.2b4 Version(1, 2, 0, ".dev-candidate", pre=4) 1.2rc4 Version(1, 2, 0, "final", post=1) 1.2.post1 Version(1, 2, 3, ".dev") 1.2.3.dev0 Version(1, 2, 3, ".dev", dev=1) 1.2.3.dev1 ```
class Version(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])): """ Get the version (PEP 440). A biased approach to the PEP 440 semantic version. Provides a tuple structure which is sorted for comparisons `v1 > v2` etc. (major, minor, micro, release type, pre-release build, post-release build, development release build) Release types are named in is such a way they are comparable with ease. Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get development status for setup files. How it works (currently): - You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`. - To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`. The dot is used to ensure all development specifiers are sorted before `alpha`. You can specify a `dev` number for development builds, but do not have to as implicit development releases are allowed. - You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not allow implicit prereleases. - You can optionally set `post` to a value greater than zero to make the build a post release. While post releases are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically does not allow implicit post releases. - It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`. Acceptable version releases: ``` Version(1, 0, 0, "final") 1.0 Version(1, 2, 0, "final") 1.2 Version(1, 2, 3, "final") 1.2.3 Version(1, 2, 0, ".dev-alpha", pre=4) 1.2a4 Version(1, 2, 0, ".dev-beta", pre=4) 1.2b4 Version(1, 2, 0, ".dev-candidate", pre=4) 1.2rc4 Version(1, 2, 0, "final", post=1) 1.2.post1 Version(1, 2, 3, ".dev") 1.2.3.dev0 Version(1, 2, 3, ".dev", dev=1) 1.2.3.dev1 ``` """ def __new__(cls, major, minor, micro, release="final", pre=0, post=0, dev=0): """Validate version info.""" # Ensure all parts are positive integers. for value in (major, minor, micro, pre, post): if not (isinstance(value, int) and value >= 0): raise ValueError("All version parts except 'release' should be integers.") if release not in REL_MAP: raise ValueError("'{}' is not a valid release type.".format(release)) # Ensure valid pre-release (we do not allow implicit pre-releases). if ".dev-candidate" < release < "final": if pre == 0: raise ValueError("Implicit pre-releases not allowed.") elif dev: raise ValueError("Version is not a development release.") elif post: raise ValueError("Post-releases are not allowed with pre-releases.") # Ensure valid development or development/pre release elif release < "alpha": if release > ".dev" and pre == 0: raise ValueError("Implicit pre-release not allowed.") elif post: raise ValueError("Post-releases are not allowed with pre-releases.") # Ensure a valid normal release else: if pre: raise ValueError("Version is not a pre-release.") elif dev: raise ValueError("Version is not a development release.") return super(Version, cls).__new__(cls, major, minor, micro, release, pre, post, dev) def _is_pre(self): """Is prerelease.""" return self.pre > 0 def _is_dev(self): """Is development.""" return bool(self.release < "alpha") def _is_post(self): """Is post.""" return self.post > 0 def _get_dev_status(self): # pragma: no cover """Get development status string.""" return DEV_STATUS[self.release] def _get_canonical(self): """Get the canonical output string.""" # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed.. if self.micro == 0 and self.major != 0: ver = "{}.{}".format(self.major, self.minor) else: ver = "{}.{}.{}".format(self.major, self.minor, self.micro) if self._is_pre(): ver += '{}{}'.format(REL_MAP[self.release], self.pre) if self._is_post(): ver += ".post{}".format(self.post) if self._is_dev(): ver += ".dev{}".format(self.dev) return ver
(major, minor, micro, release='final', pre=0, post=0, dev=0)
37,825
pep562
__new__
Validate version info.
def __new__(cls, major, minor, micro, release="final", pre=0, post=0, dev=0): """Validate version info.""" # Ensure all parts are positive integers. for value in (major, minor, micro, pre, post): if not (isinstance(value, int) and value >= 0): raise ValueError("All version parts except 'release' should be integers.") if release not in REL_MAP: raise ValueError("'{}' is not a valid release type.".format(release)) # Ensure valid pre-release (we do not allow implicit pre-releases). if ".dev-candidate" < release < "final": if pre == 0: raise ValueError("Implicit pre-releases not allowed.") elif dev: raise ValueError("Version is not a development release.") elif post: raise ValueError("Post-releases are not allowed with pre-releases.") # Ensure valid development or development/pre release elif release < "alpha": if release > ".dev" and pre == 0: raise ValueError("Implicit pre-release not allowed.") elif post: raise ValueError("Post-releases are not allowed with pre-releases.") # Ensure a valid normal release else: if pre: raise ValueError("Version is not a pre-release.") elif dev: raise ValueError("Version is not a development release.") return super(Version, cls).__new__(cls, major, minor, micro, release, pre, post, dev)
(cls, major, minor, micro, release='final', pre=0, post=0, dev=0)
37,828
pep562
_get_canonical
Get the canonical output string.
def _get_canonical(self): """Get the canonical output string.""" # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed.. if self.micro == 0 and self.major != 0: ver = "{}.{}".format(self.major, self.minor) else: ver = "{}.{}.{}".format(self.major, self.minor, self.micro) if self._is_pre(): ver += '{}{}'.format(REL_MAP[self.release], self.pre) if self._is_post(): ver += ".post{}".format(self.post) if self._is_dev(): ver += ".dev{}".format(self.dev) return ver
(self)
37,829
pep562
_get_dev_status
Get development status string.
def _get_dev_status(self): # pragma: no cover """Get development status string.""" return DEV_STATUS[self.release]
(self)
37,830
pep562
_is_dev
Is development.
def _is_dev(self): """Is development.""" return bool(self.release < "alpha")
(self)
37,831
pep562
_is_post
Is post.
def _is_post(self): """Is post.""" return self.post > 0
(self)
37,832
pep562
_is_pre
Is prerelease.
def _is_pre(self): """Is prerelease.""" return self.pre > 0
(self)
37,833
collections
_replace
Return a new Version object replacing specified fields with new values
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) """ # Validate the field names. At the user's option, either generate an error # message or automatically replace the field name with a valid name. if isinstance(field_names, str): field_names = field_names.replace(',', ' ').split() field_names = list(map(str, field_names)) typename = _sys.intern(str(typename)) if rename: seen = set() for index, name in enumerate(field_names): if (not name.isidentifier() or _iskeyword(name) or name.startswith('_') or name in seen): field_names[index] = f'_{index}' seen.add(name) for name in [typename] + field_names: if type(name) is not str: raise TypeError('Type names and field names must be strings') if not name.isidentifier(): raise ValueError('Type names and field names must be valid ' f'identifiers: {name!r}') if _iskeyword(name): raise ValueError('Type names and field names cannot be a ' f'keyword: {name!r}') seen = set() for name in field_names: if name.startswith('_') and not rename: raise ValueError('Field names cannot start with an underscore: ' f'{name!r}') if name in seen: raise ValueError(f'Encountered duplicate field name: {name!r}') seen.add(name) field_defaults = {} if defaults is not None: defaults = tuple(defaults) if len(defaults) > len(field_names): raise TypeError('Got more default values than field names') field_defaults = dict(reversed(list(zip(reversed(field_names), reversed(defaults))))) # Variables used in the methods and docstrings field_names = tuple(map(_sys.intern, field_names)) num_fields = len(field_names) arg_list = ', '.join(field_names) if num_fields == 1: arg_list += ',' repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')' tuple_new = tuple.__new__ _dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip # Create all the named tuple methods to be added to the class namespace namespace = { '_tuple_new': tuple_new, '__builtins__': {}, '__name__': f'namedtuple_{typename}', } code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))' __new__ = eval(code, namespace) __new__.__name__ = '__new__' __new__.__doc__ = f'Create new instance of {typename}({arg_list})' if defaults is not None: __new__.__defaults__ = defaults @classmethod def _make(cls, iterable): result = tuple_new(cls, iterable) if _len(result) != num_fields: raise TypeError(f'Expected {num_fields} arguments, got {len(result)}') return result _make.__func__.__doc__ = (f'Make a new {typename} object from a sequence ' 'or iterable') def _replace(self, /, **kwds): result = self._make(_map(kwds.pop, field_names, self)) if kwds: raise ValueError(f'Got unexpected field names: {list(kwds)!r}') return result _replace.__doc__ = (f'Return a new {typename} object replacing specified ' 'fields with new values') def __repr__(self): 'Return a nicely formatted representation string' return self.__class__.__name__ + repr_fmt % self def _asdict(self): 'Return a new dict which maps field names to their values.' return _dict(_zip(self._fields, self)) def __getnewargs__(self): 'Return self as a plain tuple. Used by copy and pickle.' return _tuple(self) # Modify function metadata to help with introspection and debugging for method in ( __new__, _make.__func__, _replace, __repr__, _asdict, __getnewargs__, ): method.__qualname__ = f'{typename}.{method.__name__}' # Build-up the class namespace dictionary # and use type() to build the result class class_namespace = { '__doc__': f'{typename}({arg_list})', '__slots__': (), '_fields': field_names, '_field_defaults': field_defaults, '__new__': __new__, '_make': _make, '_replace': _replace, '__repr__': __repr__, '_asdict': _asdict, '__getnewargs__': __getnewargs__, '__match_args__': field_names, } for index, name in enumerate(field_names): doc = _sys.intern(f'Alias for field number {index}') class_namespace[name] = _tuplegetter(index, doc) result = type(typename, (tuple,), class_namespace) # For pickling to work, the __module__ variable needs to be set to the frame # where the named tuple is created. Bypass this step in environments where # sys._getframe is not defined (Jython for example) or sys._getframe is not # defined for arguments greater than 0 (IronPython), or where the user has # specified a particular module. if module is None: try: module = _sys._getframe(1).f_globals.get('__name__', '__main__') except (AttributeError, ValueError): pass if module is not None: result.__module__ = module return result
(self, /, **kwds)
37,835
pep562
parse_version
Parse version into a comparable Version tuple.
def parse_version(ver): """Parse version into a comparable Version tuple.""" m = RE_VER.match(ver) if m is None: raise ValueError("'{}' is not a valid version".format(ver)) # Handle major, minor, micro major = int(m.group('major')) minor = int(m.group('minor')) if m.group('minor') else 0 micro = int(m.group('micro')) if m.group('micro') else 0 # Handle pre releases if m.group('type'): release = PRE_REL_MAP[m.group('type')] pre = int(m.group('pre')) else: release = "final" pre = 0 # Handle development releases dev = m.group('dev') if m.group('dev') else 0 if m.group('dev'): dev = int(m.group('dev')) release = '.dev-' + release if pre else '.dev' else: dev = 0 # Handle post post = int(m.group('post')) if m.group('post') else 0 return Version(major, minor, micro, release, pre, post, dev)
(ver)
37,836
pep562
pep562
Helper function to apply PEP 562.
def pep562(module_name): """Helper function to apply PEP 562.""" if sys.version_info < (3, 7): Pep562(module_name)
(module_name)
37,840
pytimeir.main
get_events
Get events from start_year to end_year
def get_events(start_year, end_year=None): """ Get events from start_year to end_year """ if end_year is None: end_year = start_year events = [] for year in range(start_year, end_year + 1): for month in range(1, 13): events.append(EventsExtractor(year, month).get_events()) events = pd.concat(events) return events
(start_year, end_year=None)
37,841
pytimeir.main
get_holidays
Get holidays from start_year to end_year
def get_holidays(start_year, end_year=None): """ Get holidays from start_year to end_year """ if end_year is None: end_year = start_year df = get_events(start_year, end_year) df = df[df['is_holiday']].reset_index(drop=True) return df
(start_year, end_year=None)
37,848
beautysh
Beautify
Class to handle both module and non-module calls.
class Beautify: """Class to handle both module and non-module calls.""" def __init__(self): """Set tab as space and it's value to 4.""" self.tab_str = " " self.tab_size = 4 self.backup = False self.check_only = False self.apply_function_style = None # default is no change based on function style self.color = True def read_file(self, fp): """Read input file.""" with open(fp) as f: return f.read() def write_file(self, fp, data): """Write output to a file.""" with open(fp, "w", newline="\n") as f: f.write(data) def detect_function_style(self, test_record): """Returns the index for the function declaration style detected in the given string or None if no function declarations are detected.""" index = 0 # IMPORTANT: apply regex sequentially and stop on the first match: for regex in FUNCTION_STYLE_REGEX: if re.search(regex, test_record): return index index += 1 return None def change_function_style(self, stripped_record, func_decl_style): """Converts a function definition syntax from the 'func_decl_style' to the one that has been set in self.apply_function_style and returns the string with the converted syntax.""" if func_decl_style is None: return stripped_record if self.apply_function_style is None: # user does not want to enforce any specific function style return stripped_record regex = FUNCTION_STYLE_REGEX[func_decl_style] replacement = FUNCTION_STYLE_REPLACEMENT[self.apply_function_style] changed_record = re.sub(regex, replacement, stripped_record) return changed_record.strip() def get_test_record(self, source_line): """Takes the given Bash source code line and simplifies it by removing stuff that is not useful for the purpose of indentation level calculation""" # first of all, get rid of escaped special characters like single/double quotes # that may impact later "collapse" attempts test_record = source_line.replace("\\'", "") test_record = test_record.replace('\\"', "") # collapse multiple quotes between ' ... ' test_record = re.sub(r"\'.*?\'", "", test_record) # collapse multiple quotes between " ... " test_record = re.sub(r'".*?"', "", test_record) # collapse multiple quotes between ` ... ` test_record = re.sub(r"`.*?`", "", test_record) # collapse multiple quotes between \` ... ' (weird case) test_record = re.sub(r"\\`.*?\'", "", test_record) # strip out any escaped single characters test_record = re.sub(r"\\.", "", test_record) # remove '#' comments test_record = re.sub(r"(\A|\s)(#.*)", "", test_record, 1) return test_record def beautify_string(self, data, path=""): """Beautify string (file part).""" tab = 0 case_level = 0 prev_line_had_continue = False continue_line = False started_multiline_quoted_string = False ended_multiline_quoted_string = False open_brackets = 0 in_here_doc = False defer_ext_quote = False in_ext_quote = False ext_quote_string = "" here_string = "" output = [] line = 1 formatter = True for record in re.split("\n", data): record = record.rstrip() stripped_record = record.strip() # preserve blank lines if not stripped_record: output.append(stripped_record) continue # ensure space before ;; terminators in case statements if case_level: stripped_record = re.sub(r"(\S);;", r"\1 ;;", stripped_record) test_record = self.get_test_record(stripped_record) # detect whether this line ends with line continuation character: prev_line_had_continue = continue_line continue_line = True if (re.search(r"\\$", stripped_record) is not None) else False inside_multiline_quoted_string = ( prev_line_had_continue and continue_line and started_multiline_quoted_string ) if not continue_line and prev_line_had_continue and started_multiline_quoted_string: # remove contents of strings initiated on previous lines and # that are ending on this line: [test_record, num_subs] = re.subn(r'^[^"]*"', "", test_record) ended_multiline_quoted_string = True if num_subs > 0 else False else: ended_multiline_quoted_string = False if ( (in_here_doc) or (inside_multiline_quoted_string) or (ended_multiline_quoted_string) ): # pass on with no changes output.append(record) # now test for here-doc termination string if re.search(here_string, test_record) and not re.search(r"<<", test_record): in_here_doc = False else: # not in here doc or inside multiline-quoted if continue_line: if prev_line_had_continue: # this line is not STARTING a multiline-quoted string... # we may be in the middle of such a multiline string # though started_multiline_quoted_string = False else: # remove contents of strings initiated on current line # but that continue on next line (in particular we need # to ignore brackets they may contain!) [test_record, num_subs] = re.subn(r'"[^"]*?\\$', "", test_record) started_multiline_quoted_string = True if num_subs > 0 else False else: # this line is not STARTING a multiline-quoted string started_multiline_quoted_string = False if (re.search(r"<<-?", test_record)) and not (re.search(r".*<<<", test_record)): here_string = re.sub( r'.*<<-?\s*[\'|"]?([_|\w]+)[\'|"]?.*', r"\1", stripped_record, 1 ) in_here_doc = len(here_string) > 0 if in_ext_quote: if re.search(ext_quote_string, test_record): # provide line after quotes test_record = re.sub(r".*%s(.*)" % ext_quote_string, r"\1", test_record, 1) in_ext_quote = False else: # not in ext quote if re.search(r'(\A|\s)(\'|")', test_record): # apply only after this line has been processed defer_ext_quote = True ext_quote_string = re.sub(r'.*([\'"]).*', r"\1", test_record, 1) # provide line before quote test_record = re.sub(r"(.*)%s.*" % ext_quote_string, r"\1", test_record, 1) if in_ext_quote or not formatter: # pass on unchanged output.append(record) if re.search(r"#\s*@formatter:on", stripped_record): formatter = True continue else: # not in ext quote if re.search(r"#\s*@formatter:off", stripped_record): formatter = False output.append(record) continue # multi-line conditions are often meticulously formatted if open_brackets: output.append(record) else: inc = len(re.findall(r"(\s|\A|;)(case|then|do)(;|\Z|\s)", test_record)) inc += len(re.findall(r"(\{|\(|\[)", test_record)) outc = len( re.findall( r"(\s|\A|;)(esac|fi|done|elif)(;|\)|\||\Z|\s)", test_record, ) ) outc += len(re.findall(r"(\}|\)|\])", test_record)) if re.search(r"\besac\b", test_record): if case_level == 0: sys.stderr.write( 'File %s: error: "esac" before "case" in ' "line %d.\n" % (path, line) ) else: outc += 1 case_level -= 1 # special handling for bad syntax within case ... esac if re.search(r"\bcase\b", test_record): inc += 1 case_level += 1 choice_case = 0 if case_level: if re.search(r"\A[^(]*\)", test_record): inc += 1 choice_case = -1 # detect functions func_decl_style = self.detect_function_style(test_record) if func_decl_style is not None: stripped_record = self.change_function_style( stripped_record, func_decl_style ) # an ad-hoc solution for the "else" or "elif ... then" keywords else_case = (0, -1)[ re.search(r"^(else|elif\s.*?;\s+?then)", test_record) is not None ] net = inc - outc tab += min(net, 0) # while 'tab' is preserved across multiple lines, # 'extab' is not and is used for some adjustments: extab = tab + else_case + choice_case if ( prev_line_had_continue and not open_brackets and not ended_multiline_quoted_string ): extab += 1 extab = max(0, extab) output.append((self.tab_str * self.tab_size * extab) + stripped_record) tab += max(net, 0) if defer_ext_quote: in_ext_quote = True defer_ext_quote = False # count open brackets for line continuation open_brackets += len(re.findall(r"\[", test_record)) open_brackets -= len(re.findall(r"\]", test_record)) line += 1 error = tab != 0 if error: sys.stderr.write("File %s: error: indent/outdent mismatch: %d.\n" % (path, tab)) return "\n".join(output), error def beautify_file(self, path): """Beautify bash script file.""" error = False if path == "-": data = sys.stdin.read() result, error = self.beautify_string(data, "(stdin)") sys.stdout.write(result) else: # named file data = self.read_file(path) result, error = self.beautify_string(data, path) if data != result: if self.check_only: if not error: # we want to return 0 (success) only if the given file is already # well formatted: error = result != data if error: self.print_diff(data, result) else: if self.backup: self.write_file(path + ".bak", data) self.write_file(path, result) return error def color_diff(self, diff): for line in diff: if line.startswith("+"): yield Fore.GREEN + line + Fore.RESET elif line.startswith("-"): yield Fore.RED + line + Fore.RESET elif line.startswith("^"): yield Fore.BLUE + line + Fore.RESET else: yield line def print_diff(self, original: str, formatted: str): original_lines = original.splitlines() formatted_lines = formatted.splitlines() delta = difflib.unified_diff( original_lines, formatted_lines, "original", "formatted", lineterm="" ) if self.color: delta = self.color_diff(delta) print("\n".join(delta)) def print_help(self, parser): parser.print_help() sys.stdout.write( "\nBash function styles that can be specified via --force-function-style are:\n" ) sys.stdout.write( " fnpar: function keyword, open/closed parentheses, e.g. function foo()\n" ) sys.stdout.write( " fnonly: function keyword, no open/closed parentheses, e.g. function foo\n" ) sys.stdout.write(" paronly: no function keyword, open/closed parentheses, e.g. foo()\n") sys.stdout.write("\n") def parse_function_style(self, style_name): # map the user-provided function style to our range 0-2 if style_name == "fnpar": return 0 elif style_name == "fnonly": return 1 elif style_name == "paronly": return 2 return None def get_version(self): try: return pkg_resources.require("beautysh")[0].version except pkg_resources.DistributionNotFound: return "Not Available" def main(self): """Main beautifying function.""" error = False parser = argparse.ArgumentParser( description="A Bash beautifier for the masses, version {}".format(self.get_version()), add_help=False, ) parser.add_argument( "--indent-size", "-i", nargs=1, type=int, default=4, help="Sets the number of spaces to be used in " "indentation.", ) parser.add_argument( "--backup", "-b", action="store_true", help="Beautysh will create a backup file in the " "same path as the original.", ) parser.add_argument( "--check", "-c", action="store_true", help="Beautysh will just check the files without doing " "any in-place beautify.", ) parser.add_argument( "--tab", "-t", action="store_true", help="Sets indentation to tabs instead of spaces.", ) parser.add_argument( "--force-function-style", "-s", nargs=1, help="Force a specific Bash function formatting. See below for more info.", ) parser.add_argument( "--version", "-v", action="store_true", help="Prints the version and exits." ) parser.add_argument("--help", "-h", action="store_true", help="Print this help message.") parser.add_argument( "files", metavar="FILE", nargs="*", help="Files to be beautified. This is mandatory. " "If - is provided as filename, then beautysh reads " "from stdin and writes on stdout.", ) args = parser.parse_args() if (len(sys.argv) < 2) or args.help: self.print_help(parser) exit() if args.version: sys.stdout.write("%s\n" % self.get_version()) exit() if type(args.indent_size) is list: args.indent_size = args.indent_size[0] if not args.files: sys.stdout.write("Please provide at least one input file\n") exit() self.tab_size = args.indent_size self.backup = args.backup self.check_only = args.check if args.tab: self.tab_size = 1 self.tab_str = "\t" if type(args.force_function_style) is list: provided_style = self.parse_function_style(args.force_function_style[0]) if provided_style is None: sys.stdout.write("Invalid value for the function style. See --help for details.\n") exit() self.apply_function_style = provided_style if "NO_COLOR" in os.environ: self.color = False for path in args.files: error |= self.beautify_file(path) sys.exit((0, 1)[error])
()
37,849
beautysh
__init__
Set tab as space and it's value to 4.
def __init__(self): """Set tab as space and it's value to 4.""" self.tab_str = " " self.tab_size = 4 self.backup = False self.check_only = False self.apply_function_style = None # default is no change based on function style self.color = True
(self)
37,850
beautysh
beautify_file
Beautify bash script file.
def beautify_file(self, path): """Beautify bash script file.""" error = False if path == "-": data = sys.stdin.read() result, error = self.beautify_string(data, "(stdin)") sys.stdout.write(result) else: # named file data = self.read_file(path) result, error = self.beautify_string(data, path) if data != result: if self.check_only: if not error: # we want to return 0 (success) only if the given file is already # well formatted: error = result != data if error: self.print_diff(data, result) else: if self.backup: self.write_file(path + ".bak", data) self.write_file(path, result) return error
(self, path)
37,851
beautysh
beautify_string
Beautify string (file part).
def beautify_string(self, data, path=""): """Beautify string (file part).""" tab = 0 case_level = 0 prev_line_had_continue = False continue_line = False started_multiline_quoted_string = False ended_multiline_quoted_string = False open_brackets = 0 in_here_doc = False defer_ext_quote = False in_ext_quote = False ext_quote_string = "" here_string = "" output = [] line = 1 formatter = True for record in re.split("\n", data): record = record.rstrip() stripped_record = record.strip() # preserve blank lines if not stripped_record: output.append(stripped_record) continue # ensure space before ;; terminators in case statements if case_level: stripped_record = re.sub(r"(\S);;", r"\1 ;;", stripped_record) test_record = self.get_test_record(stripped_record) # detect whether this line ends with line continuation character: prev_line_had_continue = continue_line continue_line = True if (re.search(r"\\$", stripped_record) is not None) else False inside_multiline_quoted_string = ( prev_line_had_continue and continue_line and started_multiline_quoted_string ) if not continue_line and prev_line_had_continue and started_multiline_quoted_string: # remove contents of strings initiated on previous lines and # that are ending on this line: [test_record, num_subs] = re.subn(r'^[^"]*"', "", test_record) ended_multiline_quoted_string = True if num_subs > 0 else False else: ended_multiline_quoted_string = False if ( (in_here_doc) or (inside_multiline_quoted_string) or (ended_multiline_quoted_string) ): # pass on with no changes output.append(record) # now test for here-doc termination string if re.search(here_string, test_record) and not re.search(r"<<", test_record): in_here_doc = False else: # not in here doc or inside multiline-quoted if continue_line: if prev_line_had_continue: # this line is not STARTING a multiline-quoted string... # we may be in the middle of such a multiline string # though started_multiline_quoted_string = False else: # remove contents of strings initiated on current line # but that continue on next line (in particular we need # to ignore brackets they may contain!) [test_record, num_subs] = re.subn(r'"[^"]*?\\$', "", test_record) started_multiline_quoted_string = True if num_subs > 0 else False else: # this line is not STARTING a multiline-quoted string started_multiline_quoted_string = False if (re.search(r"<<-?", test_record)) and not (re.search(r".*<<<", test_record)): here_string = re.sub( r'.*<<-?\s*[\'|"]?([_|\w]+)[\'|"]?.*', r"\1", stripped_record, 1 ) in_here_doc = len(here_string) > 0 if in_ext_quote: if re.search(ext_quote_string, test_record): # provide line after quotes test_record = re.sub(r".*%s(.*)" % ext_quote_string, r"\1", test_record, 1) in_ext_quote = False else: # not in ext quote if re.search(r'(\A|\s)(\'|")', test_record): # apply only after this line has been processed defer_ext_quote = True ext_quote_string = re.sub(r'.*([\'"]).*', r"\1", test_record, 1) # provide line before quote test_record = re.sub(r"(.*)%s.*" % ext_quote_string, r"\1", test_record, 1) if in_ext_quote or not formatter: # pass on unchanged output.append(record) if re.search(r"#\s*@formatter:on", stripped_record): formatter = True continue else: # not in ext quote if re.search(r"#\s*@formatter:off", stripped_record): formatter = False output.append(record) continue # multi-line conditions are often meticulously formatted if open_brackets: output.append(record) else: inc = len(re.findall(r"(\s|\A|;)(case|then|do)(;|\Z|\s)", test_record)) inc += len(re.findall(r"(\{|\(|\[)", test_record)) outc = len( re.findall( r"(\s|\A|;)(esac|fi|done|elif)(;|\)|\||\Z|\s)", test_record, ) ) outc += len(re.findall(r"(\}|\)|\])", test_record)) if re.search(r"\besac\b", test_record): if case_level == 0: sys.stderr.write( 'File %s: error: "esac" before "case" in ' "line %d.\n" % (path, line) ) else: outc += 1 case_level -= 1 # special handling for bad syntax within case ... esac if re.search(r"\bcase\b", test_record): inc += 1 case_level += 1 choice_case = 0 if case_level: if re.search(r"\A[^(]*\)", test_record): inc += 1 choice_case = -1 # detect functions func_decl_style = self.detect_function_style(test_record) if func_decl_style is not None: stripped_record = self.change_function_style( stripped_record, func_decl_style ) # an ad-hoc solution for the "else" or "elif ... then" keywords else_case = (0, -1)[ re.search(r"^(else|elif\s.*?;\s+?then)", test_record) is not None ] net = inc - outc tab += min(net, 0) # while 'tab' is preserved across multiple lines, # 'extab' is not and is used for some adjustments: extab = tab + else_case + choice_case if ( prev_line_had_continue and not open_brackets and not ended_multiline_quoted_string ): extab += 1 extab = max(0, extab) output.append((self.tab_str * self.tab_size * extab) + stripped_record) tab += max(net, 0) if defer_ext_quote: in_ext_quote = True defer_ext_quote = False # count open brackets for line continuation open_brackets += len(re.findall(r"\[", test_record)) open_brackets -= len(re.findall(r"\]", test_record)) line += 1 error = tab != 0 if error: sys.stderr.write("File %s: error: indent/outdent mismatch: %d.\n" % (path, tab)) return "\n".join(output), error
(self, data, path='')
37,852
beautysh
change_function_style
Converts a function definition syntax from the 'func_decl_style' to the one that has been set in self.apply_function_style and returns the string with the converted syntax.
def change_function_style(self, stripped_record, func_decl_style): """Converts a function definition syntax from the 'func_decl_style' to the one that has been set in self.apply_function_style and returns the string with the converted syntax.""" if func_decl_style is None: return stripped_record if self.apply_function_style is None: # user does not want to enforce any specific function style return stripped_record regex = FUNCTION_STYLE_REGEX[func_decl_style] replacement = FUNCTION_STYLE_REPLACEMENT[self.apply_function_style] changed_record = re.sub(regex, replacement, stripped_record) return changed_record.strip()
(self, stripped_record, func_decl_style)
37,853
beautysh
color_diff
null
def color_diff(self, diff): for line in diff: if line.startswith("+"): yield Fore.GREEN + line + Fore.RESET elif line.startswith("-"): yield Fore.RED + line + Fore.RESET elif line.startswith("^"): yield Fore.BLUE + line + Fore.RESET else: yield line
(self, diff)
37,854
beautysh
detect_function_style
Returns the index for the function declaration style detected in the given string or None if no function declarations are detected.
def detect_function_style(self, test_record): """Returns the index for the function declaration style detected in the given string or None if no function declarations are detected.""" index = 0 # IMPORTANT: apply regex sequentially and stop on the first match: for regex in FUNCTION_STYLE_REGEX: if re.search(regex, test_record): return index index += 1 return None
(self, test_record)
37,855
beautysh
get_test_record
Takes the given Bash source code line and simplifies it by removing stuff that is not useful for the purpose of indentation level calculation
def get_test_record(self, source_line): """Takes the given Bash source code line and simplifies it by removing stuff that is not useful for the purpose of indentation level calculation""" # first of all, get rid of escaped special characters like single/double quotes # that may impact later "collapse" attempts test_record = source_line.replace("\\'", "") test_record = test_record.replace('\\"', "") # collapse multiple quotes between ' ... ' test_record = re.sub(r"\'.*?\'", "", test_record) # collapse multiple quotes between " ... " test_record = re.sub(r'".*?"', "", test_record) # collapse multiple quotes between ` ... ` test_record = re.sub(r"`.*?`", "", test_record) # collapse multiple quotes between \` ... ' (weird case) test_record = re.sub(r"\\`.*?\'", "", test_record) # strip out any escaped single characters test_record = re.sub(r"\\.", "", test_record) # remove '#' comments test_record = re.sub(r"(\A|\s)(#.*)", "", test_record, 1) return test_record
(self, source_line)
37,856
beautysh
get_version
null
def get_version(self): try: return pkg_resources.require("beautysh")[0].version except pkg_resources.DistributionNotFound: return "Not Available"
(self)
37,857
beautysh
main
Main beautifying function.
def main(self): """Main beautifying function.""" error = False parser = argparse.ArgumentParser( description="A Bash beautifier for the masses, version {}".format(self.get_version()), add_help=False, ) parser.add_argument( "--indent-size", "-i", nargs=1, type=int, default=4, help="Sets the number of spaces to be used in " "indentation.", ) parser.add_argument( "--backup", "-b", action="store_true", help="Beautysh will create a backup file in the " "same path as the original.", ) parser.add_argument( "--check", "-c", action="store_true", help="Beautysh will just check the files without doing " "any in-place beautify.", ) parser.add_argument( "--tab", "-t", action="store_true", help="Sets indentation to tabs instead of spaces.", ) parser.add_argument( "--force-function-style", "-s", nargs=1, help="Force a specific Bash function formatting. See below for more info.", ) parser.add_argument( "--version", "-v", action="store_true", help="Prints the version and exits." ) parser.add_argument("--help", "-h", action="store_true", help="Print this help message.") parser.add_argument( "files", metavar="FILE", nargs="*", help="Files to be beautified. This is mandatory. " "If - is provided as filename, then beautysh reads " "from stdin and writes on stdout.", ) args = parser.parse_args() if (len(sys.argv) < 2) or args.help: self.print_help(parser) exit() if args.version: sys.stdout.write("%s\n" % self.get_version()) exit() if type(args.indent_size) is list: args.indent_size = args.indent_size[0] if not args.files: sys.stdout.write("Please provide at least one input file\n") exit() self.tab_size = args.indent_size self.backup = args.backup self.check_only = args.check if args.tab: self.tab_size = 1 self.tab_str = "\t" if type(args.force_function_style) is list: provided_style = self.parse_function_style(args.force_function_style[0]) if provided_style is None: sys.stdout.write("Invalid value for the function style. See --help for details.\n") exit() self.apply_function_style = provided_style if "NO_COLOR" in os.environ: self.color = False for path in args.files: error |= self.beautify_file(path) sys.exit((0, 1)[error])
(self)
37,858
beautysh
parse_function_style
null
def parse_function_style(self, style_name): # map the user-provided function style to our range 0-2 if style_name == "fnpar": return 0 elif style_name == "fnonly": return 1 elif style_name == "paronly": return 2 return None
(self, style_name)
37,859
beautysh
print_diff
null
def print_diff(self, original: str, formatted: str): original_lines = original.splitlines() formatted_lines = formatted.splitlines() delta = difflib.unified_diff( original_lines, formatted_lines, "original", "formatted", lineterm="" ) if self.color: delta = self.color_diff(delta) print("\n".join(delta))
(self, original: str, formatted: str)
37,860
beautysh
print_help
null
def print_help(self, parser): parser.print_help() sys.stdout.write( "\nBash function styles that can be specified via --force-function-style are:\n" ) sys.stdout.write( " fnpar: function keyword, open/closed parentheses, e.g. function foo()\n" ) sys.stdout.write( " fnonly: function keyword, no open/closed parentheses, e.g. function foo\n" ) sys.stdout.write(" paronly: no function keyword, open/closed parentheses, e.g. foo()\n") sys.stdout.write("\n")
(self, parser)
37,861
beautysh
read_file
Read input file.
def read_file(self, fp): """Read input file.""" with open(fp) as f: return f.read()
(self, fp)
37,862
beautysh
write_file
Write output to a file.
def write_file(self, fp, data): """Write output to a file.""" with open(fp, "w", newline="\n") as f: f.write(data)
(self, fp, data)
37,863
mdformat_beautysh
format_bash
null
def format_bash(unformatted: str, _info_str: str) -> str: result, err = Beautify().beautify_string(unformatted) if err: return unformatted return result
(unformatted: str, _info_str: str) -> str
37,864
mbstrdecoder._mbstrdecoder
MultiByteStrDecoder
Reference: https://docs.python.org/3/library/codecs.html
class MultiByteStrDecoder: """ Reference: https://docs.python.org/3/library/codecs.html """ __CODECS = [ "utf_7", "utf_8", "utf_8_sig", "utf_16", "utf_16_be", "utf_16_le", "utf_32", "utf_32_be", "utf_32_le", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500", "cp720", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", "cp874", "cp875", "cp932", "cp949", "cp950", "cp1006", "cp1026", "cp1140", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "euc_jp", "euc_jis_2004", "euc_jisx0213", "euc_kr", "gb2312", "gbk", "gb18030", "hz", "iso2022_jp", "iso2022_jp_1", "iso2022_jp_2", "iso2022_jp_2004", "iso2022_jp_3", "iso2022_jp_ext", "iso2022_kr", "latin_1", "iso8859_2", "iso8859_3", "iso8859_4", "iso8859_5", "iso8859_6", "iso8859_7", "iso8859_8", "iso8859_9", "iso8859_10", "iso8859_11", "iso8859_13", "iso8859_14", "iso8859_15", "iso8859_16", "johab", "koi8_r", "koi8_u", "mac_cyrillic", "mac_greek", "mac_iceland", "mac_latin2", "mac_roman", "mac_turkish", "ptcp154", "shift_jis", "shift_jis_2004", "shift_jisx0213", "base64_codec", "bz2_codec", "hex_codec", "idna", "mbcs", "palmos", "punycode", "quopri_codec", "raw_unicode_escape", "rot_13", "string_escape", "unicode_escape", "unicode_internal", "uu_codec", "zlib_codec", ] __RE_UTF7 = re.compile(b("[+].*?[-]")) @property def unicode_str(self) -> str: return self.__unicode_str @property def codec(self) -> Optional[str]: return self.__codec def __init__(self, value, codec_candidates: Optional[Sequence[str]] = None) -> None: self.__encoded_str = value self.__codec: Optional[str] = None if codec_candidates is None: self.__codec_candidate_list: List[str] = [] else: self.__codec_candidate_list = list(codec_candidates) self.__validate_str() self.__unicode_str = self.__to_unicode() def __repr__(self) -> str: return f"codec={self.codec:s}, unicode={self.unicode_str:s}" def __validate_str(self) -> None: if isinstance(self.__encoded_str, (str, bytes)): return raise ValueError(f"value must be a string: actual={type(self.__encoded_str)}") def __is_buffer(self) -> bool: return isinstance(self.__encoded_str, memoryview) def __is_multibyte_utf7(self, encoded_str) -> bool: if self.__codec != "utf_7": return False utf7_symbol_count = encoded_str.count(b("+")) if utf7_symbol_count <= 0: return False if utf7_symbol_count != encoded_str.count(b("-")): return False return utf7_symbol_count == len(self.__RE_UTF7.findall(encoded_str)) def __get_encoded_str(self) -> str: if self.__is_buffer(): return str(self.__encoded_str) return self.__encoded_str @staticmethod def __detect_encoding_helper(encoded_str) -> Optional[str]: import chardet try: detect = chardet.detect(encoded_str) except TypeError: detect = {} # type: ignore detect_encoding = detect.get("encoding") confidence = detect.get("confidence") if detect_encoding not in ["ascii", "utf-8"] and confidence and confidence > 0.7: # utf7 tend to be misrecognized as ascii return detect_encoding return None def __get_codec_candidate_list(self, encoded_str) -> List[str]: codec_candidate_list = copy.deepcopy(self.__CODECS) detect_encoding = self.__detect_encoding_helper(encoded_str) if detect_encoding: try: codec_candidate_list.remove(detect_encoding) except ValueError: pass codec_candidate_list.insert(0, detect_encoding) for codec_candidate in self.__codec_candidate_list: try: codec_candidate_list.remove(codec_candidate) except ValueError: pass return self.__codec_candidate_list + codec_candidate_list def __to_unicode(self): encoded_str = self.__get_encoded_str() if encoded_str == b"": self.__codec = "unicode" return "" for codec in self.__get_codec_candidate_list(encoded_str): if not codec: continue try: self.__codec = to_codec_name(codec) decoded_str = encoded_str.decode(codec) break except UnicodeDecodeError: self.__codec = None continue except AttributeError: if isinstance(encoded_str, str): # already a unicode string (python 3) self.__codec = "unicode" if not encoded_str: return encoded_str return encoded_str self.__codec = None try: return f"{encoded_str}" except UnicodeDecodeError: # some of the objects that cannot convertible to a string # may reach this line raise TypeError("argument must be a string") else: self.__codec = None try: message = f"unknown codec: encoded_str={encoded_str}" except UnicodeDecodeError: message = f"unknown codec: value-type={type(encoded_str)}" raise UnicodeDecodeError(message) if self.codec == "utf_7": return self.__process_utf7(encoded_str, decoded_str) return decoded_str def __process_utf7(self, encoded_str, decoded_str) -> str: if not encoded_str: self.__codec = "unicode" return encoded_str if self.__is_multibyte_utf7(encoded_str): try: decoded_str.encode("ascii") self.__codec = "ascii" return encoded_str.decode("ascii") except UnicodeEncodeError: return decoded_str self.__codec = "ascii" return encoded_str.decode("ascii")
(value, codec_candidates: Optional[Sequence[str]] = None) -> None
37,865
mbstrdecoder._mbstrdecoder
__detect_encoding_helper
null
@staticmethod def __detect_encoding_helper(encoded_str) -> Optional[str]: import chardet try: detect = chardet.detect(encoded_str) except TypeError: detect = {} # type: ignore detect_encoding = detect.get("encoding") confidence = detect.get("confidence") if detect_encoding not in ["ascii", "utf-8"] and confidence and confidence > 0.7: # utf7 tend to be misrecognized as ascii return detect_encoding return None
(encoded_str) -> Optional[str]
37,866
mbstrdecoder._mbstrdecoder
__get_codec_candidate_list
null
def __get_codec_candidate_list(self, encoded_str) -> List[str]: codec_candidate_list = copy.deepcopy(self.__CODECS) detect_encoding = self.__detect_encoding_helper(encoded_str) if detect_encoding: try: codec_candidate_list.remove(detect_encoding) except ValueError: pass codec_candidate_list.insert(0, detect_encoding) for codec_candidate in self.__codec_candidate_list: try: codec_candidate_list.remove(codec_candidate) except ValueError: pass return self.__codec_candidate_list + codec_candidate_list
(self, encoded_str) -> List[str]
37,867
mbstrdecoder._mbstrdecoder
__get_encoded_str
null
def __get_encoded_str(self) -> str: if self.__is_buffer(): return str(self.__encoded_str) return self.__encoded_str
(self) -> str
37,868
mbstrdecoder._mbstrdecoder
__is_buffer
null
def __is_buffer(self) -> bool: return isinstance(self.__encoded_str, memoryview)
(self) -> bool
37,869
mbstrdecoder._mbstrdecoder
__is_multibyte_utf7
null
def __is_multibyte_utf7(self, encoded_str) -> bool: if self.__codec != "utf_7": return False utf7_symbol_count = encoded_str.count(b("+")) if utf7_symbol_count <= 0: return False if utf7_symbol_count != encoded_str.count(b("-")): return False return utf7_symbol_count == len(self.__RE_UTF7.findall(encoded_str))
(self, encoded_str) -> bool
37,870
mbstrdecoder._mbstrdecoder
__process_utf7
null
def __process_utf7(self, encoded_str, decoded_str) -> str: if not encoded_str: self.__codec = "unicode" return encoded_str if self.__is_multibyte_utf7(encoded_str): try: decoded_str.encode("ascii") self.__codec = "ascii" return encoded_str.decode("ascii") except UnicodeEncodeError: return decoded_str self.__codec = "ascii" return encoded_str.decode("ascii")
(self, encoded_str, decoded_str) -> str
37,871
mbstrdecoder._mbstrdecoder
__to_unicode
null
def __to_unicode(self): encoded_str = self.__get_encoded_str() if encoded_str == b"": self.__codec = "unicode" return "" for codec in self.__get_codec_candidate_list(encoded_str): if not codec: continue try: self.__codec = to_codec_name(codec) decoded_str = encoded_str.decode(codec) break except UnicodeDecodeError: self.__codec = None continue except AttributeError: if isinstance(encoded_str, str): # already a unicode string (python 3) self.__codec = "unicode" if not encoded_str: return encoded_str return encoded_str self.__codec = None try: return f"{encoded_str}" except UnicodeDecodeError: # some of the objects that cannot convertible to a string # may reach this line raise TypeError("argument must be a string") else: self.__codec = None try: message = f"unknown codec: encoded_str={encoded_str}" except UnicodeDecodeError: message = f"unknown codec: value-type={type(encoded_str)}" raise UnicodeDecodeError(message) if self.codec == "utf_7": return self.__process_utf7(encoded_str, decoded_str) return decoded_str
(self)
37,872
mbstrdecoder._mbstrdecoder
__validate_str
null
def __validate_str(self) -> None: if isinstance(self.__encoded_str, (str, bytes)): return raise ValueError(f"value must be a string: actual={type(self.__encoded_str)}")
(self) -> NoneType
37,873
mbstrdecoder._mbstrdecoder
__init__
null
def __init__(self, value, codec_candidates: Optional[Sequence[str]] = None) -> None: self.__encoded_str = value self.__codec: Optional[str] = None if codec_candidates is None: self.__codec_candidate_list: List[str] = [] else: self.__codec_candidate_list = list(codec_candidates) self.__validate_str() self.__unicode_str = self.__to_unicode()
(self, value, codec_candidates: Optional[Sequence[str]] = None) -> NoneType
37,874
mbstrdecoder._mbstrdecoder
__repr__
null
def __repr__(self) -> str: return f"codec={self.codec:s}, unicode={self.unicode_str:s}"
(self) -> str
37,878
mbstrdecoder._func
detect_file_encoding
null
def detect_file_encoding(file_path) -> Optional[str]: from chardet.universaldetector import UniversalDetector if not os.path.isfile(file_path) or is_binary_ext_path(file_path) or is_fifo(file_path): return None detector = UniversalDetector() READ_SIZE = 4 * 1024 try: with open(file_path, mode="rb") as f: while True: binary = f.read(READ_SIZE) if not binary: break detector.feed(binary) if detector.done: break except OSError: return None finally: detector.close() return to_codec_name(detector.result.get("encoding"))
(file_path) -> Optional[str]
37,879
pulumi_ovh.get_installation_templates
AwaitableGetInstallationTemplatesResult
null
class AwaitableGetInstallationTemplatesResult(GetInstallationTemplatesResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetInstallationTemplatesResult( id=self.id, results=self.results)
(id=None, results=None)
37,880
pulumi_ovh.get_installation_templates
__await__
null
def __await__(self): if False: yield self return GetInstallationTemplatesResult( id=self.id, results=self.results)
(self)
37,881
pulumi._types
eq_fn
null
def _process_class( cls: type, signifier_attr: str, is_input: bool = False, setter: bool = False ): # Get properties. props = _properties_from_annotations(cls) # Clean-up class attributes. for name in props: # If the class attribute (which is the default value for this prop) # exists and is of type 'Property', delete the class attribute so # it is not set at all in the post-processed class. if isinstance(getattr(cls, name, None), _Property): delattr(cls, name) # Mark this class with the signifier and save the properties. setattr(cls, signifier_attr, True) # Create Python properties. for name, prop in props.items(): setattr(cls, name, _create_py_property(name, prop.name, prop.type, setter)) # Add an __init__() method if the class doesn't have one. if "__init__" not in cls.__dict__: if cls.__module__ in sys.modules: globals = sys.modules[cls.__module__].__dict__ else: globals = {} init_fn = _init_fn( props, globals, issubclass(cls, dict), not is_input and hasattr(cls, _TRANSLATE_PROPERTY), ) setattr(cls, "__init__", init_fn) # Add an __eq__() method if the class doesn't have one. # There's no need for a __ne__ method, since Python will call __eq__ and negate it. if "__eq__" not in cls.__dict__: if issubclass(cls, dict): def eq_fn(self, other): return type(other) is type(self) and getattr(dict, "__eq__")( other, self ) else: def eq_fn(self, other): return type(other) is type(self) and other.__dict__ == self.__dict__ setattr(cls, "__eq__", eq_fn)
(self, other)
37,882
pulumi_ovh.get_installation_templates
__init__
null
def __init__(__self__, id=None, results=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if results and not isinstance(results, list): raise TypeError("Expected argument 'results' to be a list") pulumi.set(__self__, "results", results)
(__self__, id=None, results=None)
37,883
pulumi_ovh.get_server
AwaitableGetServerResult
null
class AwaitableGetServerResult(GetServerResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetServerResult( server_urn=self.server_urn, boot_id=self.boot_id, boot_script=self.boot_script, commercial_range=self.commercial_range, datacenter=self.datacenter, display_name=self.display_name, enabled_public_vnis=self.enabled_public_vnis, enabled_vrack_aggregation_vnis=self.enabled_vrack_aggregation_vnis, enabled_vrack_vnis=self.enabled_vrack_vnis, id=self.id, ip=self.ip, ips=self.ips, link_speed=self.link_speed, monitoring=self.monitoring, name=self.name, os=self.os, professional_use=self.professional_use, rack=self.rack, rescue_mail=self.rescue_mail, reverse=self.reverse, root_device=self.root_device, server_id=self.server_id, service_name=self.service_name, state=self.state, support_level=self.support_level, vnis=self.vnis)
(server_urn=None, boot_id=None, boot_script=None, commercial_range=None, datacenter=None, display_name=None, enabled_public_vnis=None, enabled_vrack_aggregation_vnis=None, enabled_vrack_vnis=None, id=None, ip=None, ips=None, link_speed=None, monitoring=None, name=None, os=None, professional_use=None, rack=None, rescue_mail=None, reverse=None, root_device=None, server_id=None, service_name=None, state=None, support_level=None, vnis=None)
37,884
pulumi_ovh.get_server
__await__
null
def __await__(self): if False: yield self return GetServerResult( server_urn=self.server_urn, boot_id=self.boot_id, boot_script=self.boot_script, commercial_range=self.commercial_range, datacenter=self.datacenter, display_name=self.display_name, enabled_public_vnis=self.enabled_public_vnis, enabled_vrack_aggregation_vnis=self.enabled_vrack_aggregation_vnis, enabled_vrack_vnis=self.enabled_vrack_vnis, id=self.id, ip=self.ip, ips=self.ips, link_speed=self.link_speed, monitoring=self.monitoring, name=self.name, os=self.os, professional_use=self.professional_use, rack=self.rack, rescue_mail=self.rescue_mail, reverse=self.reverse, root_device=self.root_device, server_id=self.server_id, service_name=self.service_name, state=self.state, support_level=self.support_level, vnis=self.vnis)
(self)
37,886
pulumi_ovh.get_server
__init__
null
def __init__(__self__, server_urn=None, boot_id=None, boot_script=None, commercial_range=None, datacenter=None, display_name=None, enabled_public_vnis=None, enabled_vrack_aggregation_vnis=None, enabled_vrack_vnis=None, id=None, ip=None, ips=None, link_speed=None, monitoring=None, name=None, os=None, professional_use=None, rack=None, rescue_mail=None, reverse=None, root_device=None, server_id=None, service_name=None, state=None, support_level=None, vnis=None): if server_urn and not isinstance(server_urn, str): raise TypeError("Expected argument 'server_urn' to be a str") pulumi.set(__self__, "server_urn", server_urn) if boot_id and not isinstance(boot_id, int): raise TypeError("Expected argument 'boot_id' to be a int") pulumi.set(__self__, "boot_id", boot_id) if boot_script and not isinstance(boot_script, str): raise TypeError("Expected argument 'boot_script' to be a str") pulumi.set(__self__, "boot_script", boot_script) if commercial_range and not isinstance(commercial_range, str): raise TypeError("Expected argument 'commercial_range' to be a str") pulumi.set(__self__, "commercial_range", commercial_range) if datacenter and not isinstance(datacenter, str): raise TypeError("Expected argument 'datacenter' to be a str") pulumi.set(__self__, "datacenter", datacenter) if display_name and not isinstance(display_name, str): raise TypeError("Expected argument 'display_name' to be a str") pulumi.set(__self__, "display_name", display_name) if enabled_public_vnis and not isinstance(enabled_public_vnis, list): raise TypeError("Expected argument 'enabled_public_vnis' to be a list") pulumi.set(__self__, "enabled_public_vnis", enabled_public_vnis) if enabled_vrack_aggregation_vnis and not isinstance(enabled_vrack_aggregation_vnis, list): raise TypeError("Expected argument 'enabled_vrack_aggregation_vnis' to be a list") pulumi.set(__self__, "enabled_vrack_aggregation_vnis", enabled_vrack_aggregation_vnis) if enabled_vrack_vnis and not isinstance(enabled_vrack_vnis, list): raise TypeError("Expected argument 'enabled_vrack_vnis' to be a list") pulumi.set(__self__, "enabled_vrack_vnis", enabled_vrack_vnis) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if ip and not isinstance(ip, str): raise TypeError("Expected argument 'ip' to be a str") pulumi.set(__self__, "ip", ip) if ips and not isinstance(ips, list): raise TypeError("Expected argument 'ips' to be a list") pulumi.set(__self__, "ips", ips) if link_speed and not isinstance(link_speed, int): raise TypeError("Expected argument 'link_speed' to be a int") pulumi.set(__self__, "link_speed", link_speed) if monitoring and not isinstance(monitoring, bool): raise TypeError("Expected argument 'monitoring' to be a bool") pulumi.set(__self__, "monitoring", monitoring) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if os and not isinstance(os, str): raise TypeError("Expected argument 'os' to be a str") pulumi.set(__self__, "os", os) if professional_use and not isinstance(professional_use, bool): raise TypeError("Expected argument 'professional_use' to be a bool") pulumi.set(__self__, "professional_use", professional_use) if rack and not isinstance(rack, str): raise TypeError("Expected argument 'rack' to be a str") pulumi.set(__self__, "rack", rack) if rescue_mail and not isinstance(rescue_mail, str): raise TypeError("Expected argument 'rescue_mail' to be a str") pulumi.set(__self__, "rescue_mail", rescue_mail) if reverse and not isinstance(reverse, str): raise TypeError("Expected argument 'reverse' to be a str") pulumi.set(__self__, "reverse", reverse) if root_device and not isinstance(root_device, str): raise TypeError("Expected argument 'root_device' to be a str") pulumi.set(__self__, "root_device", root_device) if server_id and not isinstance(server_id, int): raise TypeError("Expected argument 'server_id' to be a int") pulumi.set(__self__, "server_id", server_id) if service_name and not isinstance(service_name, str): raise TypeError("Expected argument 'service_name' to be a str") pulumi.set(__self__, "service_name", service_name) if state and not isinstance(state, str): raise TypeError("Expected argument 'state' to be a str") pulumi.set(__self__, "state", state) if support_level and not isinstance(support_level, str): raise TypeError("Expected argument 'support_level' to be a str") pulumi.set(__self__, "support_level", support_level) if vnis and not isinstance(vnis, list): raise TypeError("Expected argument 'vnis' to be a list") pulumi.set(__self__, "vnis", vnis)
(__self__, server_urn=None, boot_id=None, boot_script=None, commercial_range=None, datacenter=None, display_name=None, enabled_public_vnis=None, enabled_vrack_aggregation_vnis=None, enabled_vrack_vnis=None, id=None, ip=None, ips=None, link_speed=None, monitoring=None, name=None, os=None, professional_use=None, rack=None, rescue_mail=None, reverse=None, root_device=None, server_id=None, service_name=None, state=None, support_level=None, vnis=None)
37,887
pulumi_ovh.get_servers
AwaitableGetServersResult
null
class AwaitableGetServersResult(GetServersResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetServersResult( id=self.id, results=self.results)
(id=None, results=None)
37,888
pulumi_ovh.get_servers
__await__
null
def __await__(self): if False: yield self return GetServersResult( id=self.id, results=self.results)
(self)
37,891
pulumi_ovh.get_vrack_networks
AwaitableGetVrackNetworksResult
null
class AwaitableGetVrackNetworksResult(GetVrackNetworksResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetVrackNetworksResult( id=self.id, results=self.results, service_name=self.service_name, subnet=self.subnet, vlan_id=self.vlan_id)
(id=None, results=None, service_name=None, subnet=None, vlan_id=None)
37,892
pulumi_ovh.get_vrack_networks
__await__
null
def __await__(self): if False: yield self return GetVrackNetworksResult( id=self.id, results=self.results, service_name=self.service_name, subnet=self.subnet, vlan_id=self.vlan_id)
(self)
37,894
pulumi_ovh.get_vrack_networks
__init__
null
def __init__(__self__, id=None, results=None, service_name=None, subnet=None, vlan_id=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if results and not isinstance(results, list): raise TypeError("Expected argument 'results' to be a list") pulumi.set(__self__, "results", results) if service_name and not isinstance(service_name, str): raise TypeError("Expected argument 'service_name' to be a str") pulumi.set(__self__, "service_name", service_name) if subnet and not isinstance(subnet, str): raise TypeError("Expected argument 'subnet' to be a str") pulumi.set(__self__, "subnet", subnet) if vlan_id and not isinstance(vlan_id, int): raise TypeError("Expected argument 'vlan_id' to be a int") pulumi.set(__self__, "vlan_id", vlan_id)
(__self__, id=None, results=None, service_name=None, subnet=None, vlan_id=None)
37,895
pulumi_ovh.get_installation_templates
GetInstallationTemplatesResult
A collection of values returned by getInstallationTemplates.
class GetInstallationTemplatesResult: """ A collection of values returned by getInstallationTemplates. """ def __init__(__self__, id=None, results=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if results and not isinstance(results, list): raise TypeError("Expected argument 'results' to be a list") pulumi.set(__self__, "results", results) @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter def results(self) -> Sequence[str]: """ The list of installation templates IDs available for dedicated servers. """ return pulumi.get(self, "results")
(id=None, results=None)
37,898
pulumi_ovh.get_server
GetServerResult
A collection of values returned by getServer.
class GetServerResult: """ A collection of values returned by getServer. """ def __init__(__self__, server_urn=None, boot_id=None, boot_script=None, commercial_range=None, datacenter=None, display_name=None, enabled_public_vnis=None, enabled_vrack_aggregation_vnis=None, enabled_vrack_vnis=None, id=None, ip=None, ips=None, link_speed=None, monitoring=None, name=None, os=None, professional_use=None, rack=None, rescue_mail=None, reverse=None, root_device=None, server_id=None, service_name=None, state=None, support_level=None, vnis=None): if server_urn and not isinstance(server_urn, str): raise TypeError("Expected argument 'server_urn' to be a str") pulumi.set(__self__, "server_urn", server_urn) if boot_id and not isinstance(boot_id, int): raise TypeError("Expected argument 'boot_id' to be a int") pulumi.set(__self__, "boot_id", boot_id) if boot_script and not isinstance(boot_script, str): raise TypeError("Expected argument 'boot_script' to be a str") pulumi.set(__self__, "boot_script", boot_script) if commercial_range and not isinstance(commercial_range, str): raise TypeError("Expected argument 'commercial_range' to be a str") pulumi.set(__self__, "commercial_range", commercial_range) if datacenter and not isinstance(datacenter, str): raise TypeError("Expected argument 'datacenter' to be a str") pulumi.set(__self__, "datacenter", datacenter) if display_name and not isinstance(display_name, str): raise TypeError("Expected argument 'display_name' to be a str") pulumi.set(__self__, "display_name", display_name) if enabled_public_vnis and not isinstance(enabled_public_vnis, list): raise TypeError("Expected argument 'enabled_public_vnis' to be a list") pulumi.set(__self__, "enabled_public_vnis", enabled_public_vnis) if enabled_vrack_aggregation_vnis and not isinstance(enabled_vrack_aggregation_vnis, list): raise TypeError("Expected argument 'enabled_vrack_aggregation_vnis' to be a list") pulumi.set(__self__, "enabled_vrack_aggregation_vnis", enabled_vrack_aggregation_vnis) if enabled_vrack_vnis and not isinstance(enabled_vrack_vnis, list): raise TypeError("Expected argument 'enabled_vrack_vnis' to be a list") pulumi.set(__self__, "enabled_vrack_vnis", enabled_vrack_vnis) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if ip and not isinstance(ip, str): raise TypeError("Expected argument 'ip' to be a str") pulumi.set(__self__, "ip", ip) if ips and not isinstance(ips, list): raise TypeError("Expected argument 'ips' to be a list") pulumi.set(__self__, "ips", ips) if link_speed and not isinstance(link_speed, int): raise TypeError("Expected argument 'link_speed' to be a int") pulumi.set(__self__, "link_speed", link_speed) if monitoring and not isinstance(monitoring, bool): raise TypeError("Expected argument 'monitoring' to be a bool") pulumi.set(__self__, "monitoring", monitoring) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if os and not isinstance(os, str): raise TypeError("Expected argument 'os' to be a str") pulumi.set(__self__, "os", os) if professional_use and not isinstance(professional_use, bool): raise TypeError("Expected argument 'professional_use' to be a bool") pulumi.set(__self__, "professional_use", professional_use) if rack and not isinstance(rack, str): raise TypeError("Expected argument 'rack' to be a str") pulumi.set(__self__, "rack", rack) if rescue_mail and not isinstance(rescue_mail, str): raise TypeError("Expected argument 'rescue_mail' to be a str") pulumi.set(__self__, "rescue_mail", rescue_mail) if reverse and not isinstance(reverse, str): raise TypeError("Expected argument 'reverse' to be a str") pulumi.set(__self__, "reverse", reverse) if root_device and not isinstance(root_device, str): raise TypeError("Expected argument 'root_device' to be a str") pulumi.set(__self__, "root_device", root_device) if server_id and not isinstance(server_id, int): raise TypeError("Expected argument 'server_id' to be a int") pulumi.set(__self__, "server_id", server_id) if service_name and not isinstance(service_name, str): raise TypeError("Expected argument 'service_name' to be a str") pulumi.set(__self__, "service_name", service_name) if state and not isinstance(state, str): raise TypeError("Expected argument 'state' to be a str") pulumi.set(__self__, "state", state) if support_level and not isinstance(support_level, str): raise TypeError("Expected argument 'support_level' to be a str") pulumi.set(__self__, "support_level", support_level) if vnis and not isinstance(vnis, list): raise TypeError("Expected argument 'vnis' to be a list") pulumi.set(__self__, "vnis", vnis) @property @pulumi.getter(name="ServerURN") def server_urn(self) -> str: """ URN of the dedicated server instance """ return pulumi.get(self, "server_urn") @property @pulumi.getter(name="bootId") def boot_id(self) -> int: """ Boot id of the server """ return pulumi.get(self, "boot_id") @property @pulumi.getter(name="bootScript") def boot_script(self) -> str: """ Boot script of the server """ return pulumi.get(self, "boot_script") @property @pulumi.getter(name="commercialRange") def commercial_range(self) -> str: """ Dedicated server commercial range """ return pulumi.get(self, "commercial_range") @property @pulumi.getter def datacenter(self) -> str: """ Dedicated datacenter localisation (bhs1,bhs2,...) """ return pulumi.get(self, "datacenter") @property @pulumi.getter(name="displayName") def display_name(self) -> str: """ Dedicated server display name """ return pulumi.get(self, "display_name") @property @pulumi.getter(name="enabledPublicVnis") def enabled_public_vnis(self) -> Sequence[str]: """ List of enabled public VNI uuids """ return pulumi.get(self, "enabled_public_vnis") @property @pulumi.getter(name="enabledVrackAggregationVnis") def enabled_vrack_aggregation_vnis(self) -> Sequence[str]: """ List of enabled vrack_aggregation VNI uuids """ return pulumi.get(self, "enabled_vrack_aggregation_vnis") @property @pulumi.getter(name="enabledVrackVnis") def enabled_vrack_vnis(self) -> Sequence[str]: """ List of enabled vrack VNI uuids """ return pulumi.get(self, "enabled_vrack_vnis") @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter def ip(self) -> str: """ Dedicated server ip (IPv4) """ return pulumi.get(self, "ip") @property @pulumi.getter def ips(self) -> Sequence[str]: """ Dedicated server ip blocks """ return pulumi.get(self, "ips") @property @pulumi.getter(name="linkSpeed") def link_speed(self) -> int: """ Link speed of the server """ return pulumi.get(self, "link_speed") @property @pulumi.getter def monitoring(self) -> bool: """ Icmp monitoring state """ return pulumi.get(self, "monitoring") @property @pulumi.getter def name(self) -> str: """ User defined VirtualNetworkInterface name """ return pulumi.get(self, "name") @property @pulumi.getter def os(self) -> str: """ Operating system """ return pulumi.get(self, "os") @property @pulumi.getter(name="professionalUse") def professional_use(self) -> bool: """ Does this server have professional use option """ return pulumi.get(self, "professional_use") @property @pulumi.getter def rack(self) -> str: """ Rack id of the server """ return pulumi.get(self, "rack") @property @pulumi.getter(name="rescueMail") def rescue_mail(self) -> str: """ Rescue mail of the server """ return pulumi.get(self, "rescue_mail") @property @pulumi.getter def reverse(self) -> str: """ Dedicated server reverse """ return pulumi.get(self, "reverse") @property @pulumi.getter(name="rootDevice") def root_device(self) -> str: """ Root device of the server """ return pulumi.get(self, "root_device") @property @pulumi.getter(name="serverId") def server_id(self) -> int: """ Server id """ return pulumi.get(self, "server_id") @property @pulumi.getter(name="serviceName") def service_name(self) -> str: return pulumi.get(self, "service_name") @property @pulumi.getter def state(self) -> str: """ Error, hacked, hackedBlocked, ok """ return pulumi.get(self, "state") @property @pulumi.getter(name="supportLevel") def support_level(self) -> str: """ Dedicated server support level (critical, fastpath, gs, pro) """ return pulumi.get(self, "support_level") @property @pulumi.getter def vnis(self) -> Sequence['outputs.GetServerVniResult']: """ The list of Virtualnetworkinterface associated with this server """ return pulumi.get(self, "vnis")
(server_urn=None, boot_id=None, boot_script=None, commercial_range=None, datacenter=None, display_name=None, enabled_public_vnis=None, enabled_vrack_aggregation_vnis=None, enabled_vrack_vnis=None, id=None, ip=None, ips=None, link_speed=None, monitoring=None, name=None, os=None, professional_use=None, rack=None, rescue_mail=None, reverse=None, root_device=None, server_id=None, service_name=None, state=None, support_level=None, vnis=None)
37,901
pulumi_ovh.get_servers
GetServersResult
A collection of values returned by getServers.
class GetServersResult: """ A collection of values returned by getServers. """ def __init__(__self__, id=None, results=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if results and not isinstance(results, list): raise TypeError("Expected argument 'results' to be a list") pulumi.set(__self__, "results", results) @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter def results(self) -> Sequence[str]: """ The list of dedicated servers IDs associated with your OVHcloud Account. """ return pulumi.get(self, "results")
(id=None, results=None)
37,904
pulumi_ovh.get_vrack_networks
GetVrackNetworksResult
A collection of values returned by getVrackNetworks.
class GetVrackNetworksResult: """ A collection of values returned by getVrackNetworks. """ def __init__(__self__, id=None, results=None, service_name=None, subnet=None, vlan_id=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if results and not isinstance(results, list): raise TypeError("Expected argument 'results' to be a list") pulumi.set(__self__, "results", results) if service_name and not isinstance(service_name, str): raise TypeError("Expected argument 'service_name' to be a str") pulumi.set(__self__, "service_name", service_name) if subnet and not isinstance(subnet, str): raise TypeError("Expected argument 'subnet' to be a str") pulumi.set(__self__, "subnet", subnet) if vlan_id and not isinstance(vlan_id, int): raise TypeError("Expected argument 'vlan_id' to be a int") pulumi.set(__self__, "vlan_id", vlan_id) @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter def results(self) -> Sequence[int]: """ The list of vrack network ids. """ return pulumi.get(self, "results") @property @pulumi.getter(name="serviceName") def service_name(self) -> str: return pulumi.get(self, "service_name") @property @pulumi.getter def subnet(self) -> Optional[str]: return pulumi.get(self, "subnet") @property @pulumi.getter(name="vlanId") def vlan_id(self) -> Optional[int]: return pulumi.get(self, "vlan_id")
(id=None, results=None, service_name=None, subnet=None, vlan_id=None)
37,907
pulumi_ovh.provider
Provider
null
class Provider(pulumi.ProviderResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application_key: Optional[pulumi.Input[str]] = None, application_secret: Optional[pulumi.Input[str]] = None, client_id: Optional[pulumi.Input[str]] = None, client_secret: Optional[pulumi.Input[str]] = None, consumer_key: Optional[pulumi.Input[str]] = None, endpoint: Optional[pulumi.Input[str]] = None, __props__=None): """ The provider type for the ovh package. By default, resources use package-wide configuration settings, however an explicit `Provider` instance may be created and passed during resource construction to achieve fine-grained programmatic control over provider settings. See the [documentation](https://www.pulumi.com/docs/reference/programming-model/#providers) for more information. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] application_key: The OVH API Application Key :param pulumi.Input[str] application_secret: The OVH API Application Secret :param pulumi.Input[str] client_id: OAuth 2.0 application's ID :param pulumi.Input[str] client_secret: OAuth 2.0 application's secret :param pulumi.Input[str] consumer_key: The OVH API Consumer Key :param pulumi.Input[str] endpoint: The OVH API endpoint to target (ex: "ovh-eu") """ ... @overload def __init__(__self__, resource_name: str, args: Optional[ProviderArgs] = None, opts: Optional[pulumi.ResourceOptions] = None): """ The provider type for the ovh package. By default, resources use package-wide configuration settings, however an explicit `Provider` instance may be created and passed during resource construction to achieve fine-grained programmatic control over provider settings. See the [documentation](https://www.pulumi.com/docs/reference/programming-model/#providers) for more information. :param str resource_name: The name of the resource. :param ProviderArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ProviderArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application_key: Optional[pulumi.Input[str]] = None, application_secret: Optional[pulumi.Input[str]] = None, client_id: Optional[pulumi.Input[str]] = None, client_secret: Optional[pulumi.Input[str]] = None, consumer_key: Optional[pulumi.Input[str]] = None, endpoint: Optional[pulumi.Input[str]] = None, __props__=None): opts = pulumi.ResourceOptions.merge(_utilities.get_resource_opts_defaults(), opts) if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ProviderArgs.__new__(ProviderArgs) if application_key is None: application_key = _utilities.get_env('OVH_APPLICATION_KEY') __props__.__dict__["application_key"] = application_key if application_secret is None: application_secret = _utilities.get_env('OVH_APPLICATION_SECRET') __props__.__dict__["application_secret"] = None if application_secret is None else pulumi.Output.secret(application_secret) __props__.__dict__["client_id"] = client_id __props__.__dict__["client_secret"] = client_secret if consumer_key is None: consumer_key = _utilities.get_env('OVH_CONSUMER_KEY') __props__.__dict__["consumer_key"] = consumer_key if endpoint is None: endpoint = _utilities.get_env('OVH_ENDPOINT') __props__.__dict__["endpoint"] = endpoint secret_opts = pulumi.ResourceOptions(additional_secret_outputs=["applicationSecret"]) opts = pulumi.ResourceOptions.merge(opts, secret_opts) super(Provider, __self__).__init__( 'ovh', resource_name, __props__, opts) @property @pulumi.getter(name="applicationKey") def application_key(self) -> pulumi.Output[Optional[str]]: """ The OVH API Application Key """ return pulumi.get(self, "application_key") @property @pulumi.getter(name="applicationSecret") def application_secret(self) -> pulumi.Output[Optional[str]]: """ The OVH API Application Secret """ return pulumi.get(self, "application_secret") @property @pulumi.getter(name="clientId") def client_id(self) -> pulumi.Output[Optional[str]]: """ OAuth 2.0 application's ID """ return pulumi.get(self, "client_id") @property @pulumi.getter(name="clientSecret") def client_secret(self) -> pulumi.Output[Optional[str]]: """ OAuth 2.0 application's secret """ return pulumi.get(self, "client_secret") @property @pulumi.getter(name="consumerKey") def consumer_key(self) -> pulumi.Output[Optional[str]]: """ The OVH API Consumer Key """ return pulumi.get(self, "consumer_key") @property @pulumi.getter def endpoint(self) -> pulumi.Output[Optional[str]]: """ The OVH API endpoint to target (ex: "ovh-eu") """ return pulumi.get(self, "endpoint")
(resource_name: str, *args, **kwargs)
37,908
pulumi_ovh.provider
__init__
null
def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ProviderArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs)
(__self__, resource_name: str, *args, **kwargs)
37,909
pulumi.resource
_get_providers
Fetches the correct provider and providers for this resource. provider is the first option that does not return none 1. opts.provider 2. a matching provider in opts.providers 3. a matching provider inherited from opts.parent providers is found by combining (in descending order of priority) 1. opts_providers 2. self_providers 3. provider Does not mutate self.
def _get_providers( self, t: str, pkg: Optional[str], opts: ResourceOptions ) -> Tuple[Optional["ProviderResource"], Mapping[str, "ProviderResource"]]: """ Fetches the correct provider and providers for this resource. provider is the first option that does not return none 1. opts.provider 2. a matching provider in opts.providers 3. a matching provider inherited from opts.parent providers is found by combining (in descending order of priority) 1. opts_providers 2. self_providers 3. provider Does not mutate self. """ if isinstance(opts.providers, Sequence): opts_providers = {p.package: p for p in opts.providers} elif opts.providers: opts_providers = {**opts.providers} else: opts_providers = {} # The provider provided by opts.providers ambient_provider: Optional[ProviderResource] = None if pkg and pkg in opts_providers: ambient_provider = opts_providers[pkg] # The provider supplied by the parent # Cast is safe because the `and` will resolve to only None or the result # of get_provider (which is Optional[ProviderResource]). This holds as # long as Resource does not impliment __bool__. parent_provider = cast( Optional[ProviderResource], opts.parent and opts.parent.get_provider(t) ) provider = ambient_provider or parent_provider if opts.provider: # If an explicit provider was passed in, # its package may or may not match the package we're looking for. provider_pkg = opts.provider.package if pkg == provider_pkg: # Explicit provider takes precedence over parent or ambient providers. provider = opts.provider # Regardless of whether it matches, # we still want to keep the provider in the # providers map, so that it can be used for child resources. if provider_pkg in opts_providers: message = f"There is a conflict between the `provider` field ({provider_pkg}) and a member of the `providers` map" depreciation = "This will become an error in a future version. See https://github.com/pulumi/pulumi/issues/8799 for more details" warnings.warn(f"{message} for resource {t}. " + depreciation) log.warn(f"{message}. {depreciation}", resource=self) else: opts_providers[provider_pkg] = opts.provider # opts_providers takes priority over self._providers providers = {**self._providers, **opts_providers} return provider, providers
(self, t: str, pkg: Optional[str], opts: pulumi.resource.ResourceOptions) -> Tuple[Optional[pulumi.resource.ProviderResource], Mapping[str, pulumi.resource.ProviderResource]]
37,910
pulumi_ovh.provider
_internal_init
null
def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, application_key: Optional[pulumi.Input[str]] = None, application_secret: Optional[pulumi.Input[str]] = None, client_id: Optional[pulumi.Input[str]] = None, client_secret: Optional[pulumi.Input[str]] = None, consumer_key: Optional[pulumi.Input[str]] = None, endpoint: Optional[pulumi.Input[str]] = None, __props__=None): opts = pulumi.ResourceOptions.merge(_utilities.get_resource_opts_defaults(), opts) if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ProviderArgs.__new__(ProviderArgs) if application_key is None: application_key = _utilities.get_env('OVH_APPLICATION_KEY') __props__.__dict__["application_key"] = application_key if application_secret is None: application_secret = _utilities.get_env('OVH_APPLICATION_SECRET') __props__.__dict__["application_secret"] = None if application_secret is None else pulumi.Output.secret(application_secret) __props__.__dict__["client_id"] = client_id __props__.__dict__["client_secret"] = client_secret if consumer_key is None: consumer_key = _utilities.get_env('OVH_CONSUMER_KEY') __props__.__dict__["consumer_key"] = consumer_key if endpoint is None: endpoint = _utilities.get_env('OVH_ENDPOINT') __props__.__dict__["endpoint"] = endpoint secret_opts = pulumi.ResourceOptions(additional_secret_outputs=["applicationSecret"]) opts = pulumi.ResourceOptions.merge(opts, secret_opts) super(Provider, __self__).__init__( 'ovh', resource_name, __props__, opts)
(__self__, resource_name: str, opts: Optional[pulumi.resource.ResourceOptions] = None, application_key: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, application_secret: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, client_id: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, client_secret: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, consumer_key: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, endpoint: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, __props__=None)
37,911
pulumi.resource
get_provider
Fetches the provider for the given module member, if this resource has been provided a specific provider for the given module member. Returns None if no provider was provided. :param str module_member: The requested module member. :return: The :class:`ProviderResource` associated with the given module member, or None if one does not exist. :rtype: Optional[ProviderResource]
def get_provider(self, module_member: str) -> Optional["ProviderResource"]: """ Fetches the provider for the given module member, if this resource has been provided a specific provider for the given module member. Returns None if no provider was provided. :param str module_member: The requested module member. :return: The :class:`ProviderResource` associated with the given module member, or None if one does not exist. :rtype: Optional[ProviderResource] """ pkg = _pkg_from_type(module_member) if pkg is None: return None return self._providers.get(pkg)
(self, module_member: str) -> Optional[pulumi.resource.ProviderResource]
37,912
pulumi.resource
translate_input_property
Provides subclasses of Resource an opportunity to translate names of input properties into a format of their choosing before sending those properties to the Pulumi engine. If the `props` passed to `__init__` is an input type (decorated with `@input_type`), the type/name metadata of `props` will be used to translate names instead of calling this method. :param str prop: A property name. :return: A potentially transformed property name. :rtype: str
def translate_input_property(self, prop: str) -> str: """ Provides subclasses of Resource an opportunity to translate names of input properties into a format of their choosing before sending those properties to the Pulumi engine. If the `props` passed to `__init__` is an input type (decorated with `@input_type`), the type/name metadata of `props` will be used to translate names instead of calling this method. :param str prop: A property name. :return: A potentially transformed property name. :rtype: str """ return prop
(self, prop: str) -> str
37,913
pulumi.resource
translate_output_property
Provides subclasses of Resource an opportunity to translate names of output properties into a format of their choosing before writing those properties to the resource object. If the `props` passed to `__init__` is an input type (decorated with `@input_type`), the type/name metadata of the resource will be used to translate names instead of calling this method. :param str prop: A property name. :return: A potentially transformed property name. :rtype: str
def translate_output_property(self, prop: str) -> str: """ Provides subclasses of Resource an opportunity to translate names of output properties into a format of their choosing before writing those properties to the resource object. If the `props` passed to `__init__` is an input type (decorated with `@input_type`), the type/name metadata of the resource will be used to translate names instead of calling this method. :param str prop: A property name. :return: A potentially transformed property name. :rtype: str """ return prop
(self, prop: str) -> str
37,914
pulumi_ovh.provider
ProviderArgs
null
class ProviderArgs: def __init__(__self__, *, application_key: Optional[pulumi.Input[str]] = None, application_secret: Optional[pulumi.Input[str]] = None, client_id: Optional[pulumi.Input[str]] = None, client_secret: Optional[pulumi.Input[str]] = None, consumer_key: Optional[pulumi.Input[str]] = None, endpoint: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a Provider resource. :param pulumi.Input[str] application_key: The OVH API Application Key :param pulumi.Input[str] application_secret: The OVH API Application Secret :param pulumi.Input[str] client_id: OAuth 2.0 application's ID :param pulumi.Input[str] client_secret: OAuth 2.0 application's secret :param pulumi.Input[str] consumer_key: The OVH API Consumer Key :param pulumi.Input[str] endpoint: The OVH API endpoint to target (ex: "ovh-eu") """ if application_key is None: application_key = _utilities.get_env('OVH_APPLICATION_KEY') if application_key is not None: pulumi.set(__self__, "application_key", application_key) if application_secret is None: application_secret = _utilities.get_env('OVH_APPLICATION_SECRET') if application_secret is not None: pulumi.set(__self__, "application_secret", application_secret) if client_id is not None: pulumi.set(__self__, "client_id", client_id) if client_secret is not None: pulumi.set(__self__, "client_secret", client_secret) if consumer_key is None: consumer_key = _utilities.get_env('OVH_CONSUMER_KEY') if consumer_key is not None: pulumi.set(__self__, "consumer_key", consumer_key) if endpoint is None: endpoint = _utilities.get_env('OVH_ENDPOINT') if endpoint is not None: pulumi.set(__self__, "endpoint", endpoint) @property @pulumi.getter(name="applicationKey") def application_key(self) -> Optional[pulumi.Input[str]]: """ The OVH API Application Key """ return pulumi.get(self, "application_key") @application_key.setter def application_key(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "application_key", value) @property @pulumi.getter(name="applicationSecret") def application_secret(self) -> Optional[pulumi.Input[str]]: """ The OVH API Application Secret """ return pulumi.get(self, "application_secret") @application_secret.setter def application_secret(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "application_secret", value) @property @pulumi.getter(name="clientId") def client_id(self) -> Optional[pulumi.Input[str]]: """ OAuth 2.0 application's ID """ return pulumi.get(self, "client_id") @client_id.setter def client_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "client_id", value) @property @pulumi.getter(name="clientSecret") def client_secret(self) -> Optional[pulumi.Input[str]]: """ OAuth 2.0 application's secret """ return pulumi.get(self, "client_secret") @client_secret.setter def client_secret(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "client_secret", value) @property @pulumi.getter(name="consumerKey") def consumer_key(self) -> Optional[pulumi.Input[str]]: """ The OVH API Consumer Key """ return pulumi.get(self, "consumer_key") @consumer_key.setter def consumer_key(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "consumer_key", value) @property @pulumi.getter def endpoint(self) -> Optional[pulumi.Input[str]]: """ The OVH API endpoint to target (ex: "ovh-eu") """ return pulumi.get(self, "endpoint") @endpoint.setter def endpoint(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "endpoint", value)
(*, application_key: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, application_secret: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, client_id: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, client_secret: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, consumer_key: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, endpoint: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None)
37,916
pulumi_ovh.provider
__init__
The set of arguments for constructing a Provider resource. :param pulumi.Input[str] application_key: The OVH API Application Key :param pulumi.Input[str] application_secret: The OVH API Application Secret :param pulumi.Input[str] client_id: OAuth 2.0 application's ID :param pulumi.Input[str] client_secret: OAuth 2.0 application's secret :param pulumi.Input[str] consumer_key: The OVH API Consumer Key :param pulumi.Input[str] endpoint: The OVH API endpoint to target (ex: "ovh-eu")
def __init__(__self__, *, application_key: Optional[pulumi.Input[str]] = None, application_secret: Optional[pulumi.Input[str]] = None, client_id: Optional[pulumi.Input[str]] = None, client_secret: Optional[pulumi.Input[str]] = None, consumer_key: Optional[pulumi.Input[str]] = None, endpoint: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a Provider resource. :param pulumi.Input[str] application_key: The OVH API Application Key :param pulumi.Input[str] application_secret: The OVH API Application Secret :param pulumi.Input[str] client_id: OAuth 2.0 application's ID :param pulumi.Input[str] client_secret: OAuth 2.0 application's secret :param pulumi.Input[str] consumer_key: The OVH API Consumer Key :param pulumi.Input[str] endpoint: The OVH API endpoint to target (ex: "ovh-eu") """ if application_key is None: application_key = _utilities.get_env('OVH_APPLICATION_KEY') if application_key is not None: pulumi.set(__self__, "application_key", application_key) if application_secret is None: application_secret = _utilities.get_env('OVH_APPLICATION_SECRET') if application_secret is not None: pulumi.set(__self__, "application_secret", application_secret) if client_id is not None: pulumi.set(__self__, "client_id", client_id) if client_secret is not None: pulumi.set(__self__, "client_secret", client_secret) if consumer_key is None: consumer_key = _utilities.get_env('OVH_CONSUMER_KEY') if consumer_key is not None: pulumi.set(__self__, "consumer_key", consumer_key) if endpoint is None: endpoint = _utilities.get_env('OVH_ENDPOINT') if endpoint is not None: pulumi.set(__self__, "endpoint", endpoint)
(__self__, *, application_key: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, application_secret: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, client_id: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, client_secret: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, consumer_key: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None, endpoint: Union[str, Awaitable[str], ForwardRef('Output[T]'), NoneType] = None)
37,925
pulumi_ovh.get_installation_templates
get_installation_templates
Use this data source to get the list of installation templates available for dedicated servers. ## Example Usage <!--Start PulumiCodeChooser --> ```python import pulumi import pulumi_ovh as ovh templates = ovh.get_installation_templates() ``` <!--End PulumiCodeChooser -->
def get_installation_templates(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetInstallationTemplatesResult: """ Use this data source to get the list of installation templates available for dedicated servers. ## Example Usage <!--Start PulumiCodeChooser --> ```python import pulumi import pulumi_ovh as ovh templates = ovh.get_installation_templates() ``` <!--End PulumiCodeChooser --> """ __args__ = dict() opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('ovh:index/getInstallationTemplates:getInstallationTemplates', __args__, opts=opts, typ=GetInstallationTemplatesResult).value return AwaitableGetInstallationTemplatesResult( id=pulumi.get(__ret__, 'id'), results=pulumi.get(__ret__, 'results'))
(opts: Optional[pulumi.invoke.InvokeOptions] = None) -> pulumi_ovh.get_installation_templates.AwaitableGetInstallationTemplatesResult
37,926
pulumi_ovh._utilities
lifted_func
null
def lift_output_func(func: typing.Any) -> typing.Callable[[_F], _F]: """Decorator internally used on {fn}_output lifted function versions to implement them automatically from the un-lifted function.""" func_sig = inspect.signature(func) def lifted_func(*args, opts=None, **kwargs): bound_args = func_sig.bind(*args, **kwargs) # Convert tuple to list, see pulumi/pulumi#8172 args_list = list(bound_args.args) return pulumi.Output.from_input({ 'args': args_list, 'kwargs': bound_args.kwargs }).apply(lambda resolved_args: func(*resolved_args['args'], opts=opts, **resolved_args['kwargs'])) return (lambda _: lifted_func)
(*args, opts=None, **kwargs)
37,927
pulumi_ovh.get_server
get_server
Use this data source to retrieve information about a dedicated server associated with your OVHcloud Account. ## Example Usage <!--Start PulumiCodeChooser --> ```python import pulumi import pulumi_ovh as ovh server = ovh.get_server(service_name="XXXXXX") ``` <!--End PulumiCodeChooser --> :param str service_name: The service_name of your dedicated server.
def get_server(service_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetServerResult: """ Use this data source to retrieve information about a dedicated server associated with your OVHcloud Account. ## Example Usage <!--Start PulumiCodeChooser --> ```python import pulumi import pulumi_ovh as ovh server = ovh.get_server(service_name="XXXXXX") ``` <!--End PulumiCodeChooser --> :param str service_name: The service_name of your dedicated server. """ __args__ = dict() __args__['serviceName'] = service_name opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('ovh:index/getServer:getServer', __args__, opts=opts, typ=GetServerResult).value return AwaitableGetServerResult( server_urn=pulumi.get(__ret__, 'server_urn'), boot_id=pulumi.get(__ret__, 'boot_id'), boot_script=pulumi.get(__ret__, 'boot_script'), commercial_range=pulumi.get(__ret__, 'commercial_range'), datacenter=pulumi.get(__ret__, 'datacenter'), display_name=pulumi.get(__ret__, 'display_name'), enabled_public_vnis=pulumi.get(__ret__, 'enabled_public_vnis'), enabled_vrack_aggregation_vnis=pulumi.get(__ret__, 'enabled_vrack_aggregation_vnis'), enabled_vrack_vnis=pulumi.get(__ret__, 'enabled_vrack_vnis'), id=pulumi.get(__ret__, 'id'), ip=pulumi.get(__ret__, 'ip'), ips=pulumi.get(__ret__, 'ips'), link_speed=pulumi.get(__ret__, 'link_speed'), monitoring=pulumi.get(__ret__, 'monitoring'), name=pulumi.get(__ret__, 'name'), os=pulumi.get(__ret__, 'os'), professional_use=pulumi.get(__ret__, 'professional_use'), rack=pulumi.get(__ret__, 'rack'), rescue_mail=pulumi.get(__ret__, 'rescue_mail'), reverse=pulumi.get(__ret__, 'reverse'), root_device=pulumi.get(__ret__, 'root_device'), server_id=pulumi.get(__ret__, 'server_id'), service_name=pulumi.get(__ret__, 'service_name'), state=pulumi.get(__ret__, 'state'), support_level=pulumi.get(__ret__, 'support_level'), vnis=pulumi.get(__ret__, 'vnis'))
(service_name: Optional[str] = None, opts: Optional[pulumi.invoke.InvokeOptions] = None) -> pulumi_ovh.get_server.AwaitableGetServerResult
37,929
pulumi_ovh.get_servers
get_servers
Use this data source to get the list of dedicated servers associated with your OVHcloud Account. ## Example Usage <!--Start PulumiCodeChooser --> ```python import pulumi import pulumi_ovh as ovh servers = ovh.get_servers() ``` <!--End PulumiCodeChooser -->
def get_servers(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetServersResult: """ Use this data source to get the list of dedicated servers associated with your OVHcloud Account. ## Example Usage <!--Start PulumiCodeChooser --> ```python import pulumi import pulumi_ovh as ovh servers = ovh.get_servers() ``` <!--End PulumiCodeChooser --> """ __args__ = dict() opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('ovh:index/getServers:getServers', __args__, opts=opts, typ=GetServersResult).value return AwaitableGetServersResult( id=pulumi.get(__ret__, 'id'), results=pulumi.get(__ret__, 'results'))
(opts: Optional[pulumi.invoke.InvokeOptions] = None) -> pulumi_ovh.get_servers.AwaitableGetServersResult
37,931
pulumi_ovh.get_vrack_networks
get_vrack_networks
Use this data source to get the list of Vrack network ids available for your IPLoadbalancer associated with your OVHcloud account. ## Example Usage <!--Start PulumiCodeChooser --> ```python import pulumi import pulumi_ovh as ovh lb_networks = ovh.get_vrack_networks(service_name="XXXXXX", subnet="10.0.0.0/24") ``` <!--End PulumiCodeChooser --> :param str service_name: The internal name of your IP load balancing :param str subnet: Filters networks on the subnet. :param int vlan_id: Filters networks on the vlan id.
def get_vrack_networks(service_name: Optional[str] = None, subnet: Optional[str] = None, vlan_id: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVrackNetworksResult: """ Use this data source to get the list of Vrack network ids available for your IPLoadbalancer associated with your OVHcloud account. ## Example Usage <!--Start PulumiCodeChooser --> ```python import pulumi import pulumi_ovh as ovh lb_networks = ovh.get_vrack_networks(service_name="XXXXXX", subnet="10.0.0.0/24") ``` <!--End PulumiCodeChooser --> :param str service_name: The internal name of your IP load balancing :param str subnet: Filters networks on the subnet. :param int vlan_id: Filters networks on the vlan id. """ __args__ = dict() __args__['serviceName'] = service_name __args__['subnet'] = subnet __args__['vlanId'] = vlan_id opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('ovh:index/getVrackNetworks:getVrackNetworks', __args__, opts=opts, typ=GetVrackNetworksResult).value return AwaitableGetVrackNetworksResult( id=pulumi.get(__ret__, 'id'), results=pulumi.get(__ret__, 'results'), service_name=pulumi.get(__ret__, 'service_name'), subnet=pulumi.get(__ret__, 'subnet'), vlan_id=pulumi.get(__ret__, 'vlan_id'))
(service_name: Optional[str] = None, subnet: Optional[str] = None, vlan_id: Optional[int] = None, opts: Optional[pulumi.invoke.InvokeOptions] = None) -> pulumi_ovh.get_vrack_networks.AwaitableGetVrackNetworksResult
37,944
justdays.day
Day
null
class Day: def __init__(self, *args): """Day can be intialized with:""" if len(args) == 3: """Three arguments: year, month, day""" dt = datetime(*args) elif len(args) == 2: # year, week """Two arguments: year, week. Day with be the Monday of that week""" dt = datetime.strptime(f"{args[0]} {args[1]} 1", "%Y %W %w") elif len(args) == 0: """No arguments: today""" dt = datetime.today() elif isinstance(args[0], str): """One argument: string in format YYYY-MM-DD""" y, m, d = args[0].split("-") dt = datetime(int(y), int(m), int(d)) elif isinstance(args[0], (date, datetime)): """One argument: datetime or date""" dt = args[0] else: raise f"Invalid type passed to Day class: {args[0]} with type {type(args[0])}" self.str = dt.strftime(DATE_FORMAT) self.d, self.m, self.y = dt.day, dt.month, dt.year def __str__(self) -> str: return self.str def __repr__(self) -> str: return f"Day({self.str})" def __hash__(self): return hash(self.str) def __lt__(self, other) -> bool: return str(self) < str(other) def __gt__(self, other) -> bool: return str(self) > str(other) def __le__(self, other) -> bool: return str(self) <= str(other) def __ge__(self, other) -> bool: return str(self) >= str(other) def __eq__(self, other) -> bool: return str(self) == str(other) def __add__(self, other): if type(other) == int: return self.plus_days(other) elif type(other) == str: return str(self) + other else: raise TypeError(f"Cannot add Day to {type(other)}") def __radd__(self, other): if type(other) == int: return self.plus_days(other) elif type(other) == str: return other + str(self) else: raise TypeError(f"Cannot add Day to {type(other)}") def __sub__(self, other) -> int | Day: """ Days can be substracted from each other Or you can subtstract a number to go back as many days """ if type(other) == Day: return (self.as_datetime() - other.as_datetime()).days elif type(other) == int: return self.plus_days(-other) else: raise TypeError(f"Cannot substract {type(other)} from Day") def as_datetime(self) -> datetime: return datetime(self.y, self.m, self.d) def as_date(self) -> date: return date(self.y, self.m, self.d) def as_unix_timestamp(self) -> int: """Returns the unix timestamp of the day""" return int(self.as_datetime().timestamp()) def strftime(self, date_format: str) -> str: """Works just like the strftime from datetime""" return self.as_datetime().strftime(date_format) def next(self) -> Day: """Returns the next day""" return self.plus_days(1) def next_weekday(self) -> Day: """Returns the first day in the future that is on a weekday""" day = self.plus_days(1) while day.day_of_week() >= 5: day = day.plus_days(1) return day def previous_weekday(self) -> Day: """Returns the first day in the future that is on a weekday""" day = self.plus_days(-1) while day.day_of_week() >= 5: day = day.plus_days(-1) return day def prev(self) -> Day: """Return the previous day""" return self.plus_days(-1) def plus_days(self, increment) -> Day: """Returns a new Day object increment days further in the future""" return Day(self.as_datetime() + timedelta(days=increment)) def plus_weeks(self, increment) -> Day: """Returns a new Day object increment weeks further in the future""" return Day(self.as_datetime() + relativedelta(weeks=increment)) # relativedelta def plus_months(self, increment) -> Day: """Returns a new Day object increment months further in the future""" return Day( self.as_datetime() + relativedelta(months=increment) ) # relativedelta def is_weekday(self) -> bool: """Returns True if day is a weekday (Monday to Friday)""" return self.as_datetime().weekday() < 5 def is_weekend(self) -> bool: """Returns True of day is a Saturday or Sunday.""" return self.as_datetime().weekday() >= 5 def day_of_week(self) -> int: """Return day of the week, where Monday == 0 ... Sunday == 6.""" return self.as_datetime().weekday() def week_number(self) -> int: """Return the week number of the year.""" if sys.version_info[1] >= 9: return self.as_datetime().isocalendar().week return self.as_datetime().isocalendar()[1] def day_of_year(self) -> int: """Day of the year is a number between 1 and 365/366, January 1st is day 1""" return self.as_datetime().timetuple().tm_yday def fraction_of_the_year_past(self) -> float: """Returns a fraction of how much of the year is past including the current day""" is_leap_year = self.y % 4 == 0 and (self.y % 100 != 0 or self.y % 400 == 0) return self.day_of_year() / (366 if is_leap_year else 365) def last_monday(self) -> Day: """Returns the last day that was a Monday or the day itself if it is a Monday""" return self.plus_days(-self.as_datetime().weekday()) def last_day_of_month(self) -> Day: """Returns the last day of the month""" return Day(self.y, self.m, calendar.monthrange(self.y, self.m)[1])
(*args)
37,945
justdays.day
__add__
null
def __add__(self, other): if type(other) == int: return self.plus_days(other) elif type(other) == str: return str(self) + other else: raise TypeError(f"Cannot add Day to {type(other)}")
(self, other)
37,946
justdays.day
__eq__
null
def __eq__(self, other) -> bool: return str(self) == str(other)
(self, other) -> bool
37,947
justdays.day
__ge__
null
def __ge__(self, other) -> bool: return str(self) >= str(other)
(self, other) -> bool