code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'Tests a manifest version number'
field_name = '<em:version>' if source == 'install.rdf' else 'version'
err.metadata['version'] = value
# May not be longer than 32 characters
if len(value) > 32:
err.error(
('metadata_helpers', '_test_version', 'too_long'),
'The va... | def validate_version(err, value, source) | Tests a manifest version number | 4.23092 | 3.963203 | 1.067551 |
url = self.base_url + '/device'
try:
r = requests.get(url, params={'pin': pin}, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | def get_device(self, pin=None) | Query the status of a specific pin (or all configured pins if pin is ommitted) | 3.770489 | 3.511003 | 1.073907 |
url = self.base_url + '/status'
try:
r = requests.get(url, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | def get_status(self) | Query the device status. Returns JSON of the device internal state | 3.696629 | 3.399431 | 1.087426 |
url = self.base_url + '/device'
payload = {
"pin": pin,
"state": state
}
if momentary is not None:
payload["momentary"] = momentary
if times is not None:
payload["times"] = times
if pause is not None:
... | def put_device(self, pin, state, momentary=None, times=None, pause=None) | Actuate a device pin | 2.038998 | 2.02471 | 1.007057 |
url = self.base_url + '/settings'
payload = {
"sensors": sensors,
"actuators": actuators,
"dht_sensors": dht_sensors,
"ds18b20_sensors": ds18b20_sensors,
"token": auth_token,
"apiUrl": endpoint
}
if blink ... | def put_settings(self, sensors=[], actuators=[], auth_token=None,
endpoint=None, blink=None, discovery=None,
dht_sensors=[], ds18b20_sensors=[]) | Sync settings to the Konnected device | 1.964196 | 2.038383 | 0.963605 |
full_type, params = cgi.parse_header(mime_type)
# Java URLConnection class sends an Accept header that includes a
# single '*'. Turn it into a legal wildcard.
if full_type == '*':
full_type = '*/*'
type_parts = full_type.split('/') if '/' in full_type else None
if not type_parts or... | def parse_mime_type(mime_type) | Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', ... | 4.434294 | 4.590735 | 0.965922 |
(type, subtype, params) = parse_mime_type(range)
params.setdefault('q', params.pop('Q', None)) # q is case insensitive
try:
if not params['q'] or not 0 <= float(params['q']) <= 1:
params['q'] = '1'
except ValueError: # from float()
params['q'] = '1'
return (type, ... | def parse_media_range(range) | Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q'... | 3.333076 | 3.143474 | 1.060316 |
best_fitness = -1
best_fit_q = 0
(target_type, target_subtype, target_params) = \
parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
# check if the type and the subtype match
type_match = (
type in (target_type, '*') or
targe... | def quality_and_fitness_parsed(mime_type, parsed_ranges) | Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) i... | 2.953473 | 2.796834 | 1.056006 |
parsed_ranges = [parse_media_range(r) for r in ranges.split(',')]
return quality_parsed(mime_type, parsed_ranges) | def quality(mime_type, ranges) | Return the quality ('q') of a mime-type against a list of media-ranges.
Returns the quality 'q' of a mime-type when compared against the
media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
... | 4.34878 | 4.96236 | 0.876353 |
split_header = _filter_blank(header.split(','))
parsed_header = [parse_media_range(r) for r in split_header]
weighted_matches = []
pos = 0
for mime_type in supported:
weighted_matches.append((
quality_and_fitness_parsed(mime_type, parsed_header),
pos,
... | def best_match(supported, header) | Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a li... | 5.012523 | 4.586439 | 1.092901 |
pkg = 'cnxml2html'
package = ''.join(['.' + x for x in __name__.split('.')[:-1]])[1:]
if package != '':
pkg = package + '.' + pkg
path = pkg_resources.resource_filename(pkg, filename)
xml = etree.parse(path)
return etree.XSLT(xml) | def makeXsl(filename) | Helper that creates a XSLT stylesheet | 4.875995 | 4.671247 | 1.043832 |
xml = etree.parse(collxml_file)
xslt = makeXsl('collxml2xhtml.xsl')
xml = xslt(xml)
return xml | def transform_collxml(collxml_file) | Given a collxml file (collection.xml) this returns an HTML version of it
(including "include" anchor links to the modules) | 6.578645 | 6.563468 | 1.002312 |
xml = etree.parse(cnxml_file)
xslt = makeXsl('cnxml2xhtml.xsl')
xml = xslt(xml)
return xml | def transform_cnxml(cnxml_file) | Given a module cnxml file (index.cnxml) this returns an HTML version of it | 6.59582 | 6.497998 | 1.015054 |
collxml_file = open(os.path.join(collection_dir, 'collection.xml'))
collxml_html = transform_collxml(collxml_file)
# For each included module, parse and convert it
for node in INCLUDE_XPATH(collxml_html):
href = node.attrib['href']
module = href.split('@')[0]
# version = N... | def transform_collection(collection_dir) | Given an unzipped collection generate a giant HTML file representing
the entire collection (including loading and converting individual modules) | 3.653385 | 3.578989 | 1.020787 |
return TOption(cls.from_dict(d,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if d is not None else None) | def from_optional_dict(cls, d: Optional[dict],
force_snake_case: bool=True,force_cast: bool=False, restrict: bool=True) -> TOption[T] | From dict to optional instance.
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
... | 2.10939 | 3.074613 | 0.686067 |
return TList([cls.from_dict(d,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) for d in ds]) | def from_dicts(cls, ds: List[dict],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TList[T] | From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
... | 1.894673 | 3.446809 | 0.549689 |
return TOption(cls.from_dicts(ds,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if ds is not None else None) | def from_optional_dicts(cls, ds: Optional[List[dict]],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TOption[TList[T]] | From list of dict to optional list of instance.
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of ins... | 2.203955 | 3.535883 | 0.623311 |
return TDict({k: cls.from_dict(v,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) for k, v in ds.items()}) | def from_dicts_by_key(cls, ds: dict,
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TDict[T] | From dict of dict to dict of instance
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
... | 1.904539 | 3.025374 | 0.629522 |
return TOption(cls.from_dicts_by_key(ds,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if ds is not None else None) | def from_optional_dicts_by_key(cls, ds: Optional[dict],
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TOption[TDict[T]] | From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of ins... | 2.134035 | 3.500343 | 0.609664 |
return cls.from_dict(util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_json(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T | From json string to instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
... | 2.505701 | 3.582203 | 0.699486 |
return cls.from_dict(util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_jsonf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T | From json file path to instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if ... | 2.157906 | 2.661945 | 0.81065 |
return cls.from_dicts(util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_json_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T] | From json string to list of instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
... | 2.803299 | 4.538066 | 0.61773 |
return cls.from_dicts(util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_jsonf_to_list(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T] | From json file path to list of instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parame... | 2.537761 | 3.080138 | 0.823912 |
return cls.from_dict(util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_yaml(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T | From yaml string to instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
... | 2.44321 | 3.587142 | 0.681102 |
return cls.from_dict(util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_yamlf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T | From yaml file path to instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if ... | 2.181956 | 2.661164 | 0.819925 |
return cls.from_dicts(util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_yaml_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T] | From yaml string to list of instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
... | 2.716811 | 4.438637 | 0.612082 |
return cls.from_dicts(util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_yamlf_to_list(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T] | From yaml file path to list of instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parame... | 2.520297 | 3.066814 | 0.821796 |
return cls.from_dicts(util.load_csvf(fpath, fieldnames, encoding),
force_snake_case=force_snake_case,
force_cast=True,
restrict=restrict) | def from_csvf(cls, fpath: str, fieldnames: Optional[Sequence[str]]=None, encoding: str='utf8',
force_snake_case: bool=True, restrict: bool=True) -> TList[T] | From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if not included in the file
:param encoding: Csv file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param res... | 3.396938 | 4.39615 | 0.772708 |
return cls.from_dict(util.load_json_url(url),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | def from_json_url(cls, url: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T | From url which returns json to instance
:param url: Url which returns json
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance | 2.364511 | 2.968165 | 0.796624 |
return TOption(self[index]) if len(self) > index else TOption(None) | def get(self, index: int) -> TOption[T] | :param index:
Usage:
>>> TList([1, 2, 3, 4, 5]).get(3)
Option --> 4
>>> TList([1, 2, 3, 4, 5]).get(5)
Option --> None | 5.007649 | 6.984972 | 0.716918 |
return TList([func(x, i) for i, x in enumerate(self)]) | def emap(self, func) | :param func:
:type func: T, int -> U
:rtype: TList[U]
Usage:
>>> TList([10, 20, 30, 40, 50]).emap(lambda x, i: (x+1, i))
[(11, 0), (21, 1), (31, 2), (41, 3), (51, 4)] | 7.173242 | 4.454674 | 1.610273 |
r = TList()
for x in self:
if not func(x):
return r
else:
r.append(x)
return r | def head_while(self, func: Callable[[T], bool]) -> 'TList[T]' | :param func:
:type func: T -> bool
Usage:
>>> TList([1, 2, 30, 4, 50]).head_while(lambda x: x < 10)
[1, 2] | 2.610655 | 4.23243 | 0.616822 |
rs = TList()
for e in self:
if e not in rs:
rs.append(e)
return rs | def uniq(self) -> 'TList[T]' | Usage:
>>> TList([1, 2, 3, 2, 1]).uniq()
[1, 2, 3] | 2.81346 | 5.101192 | 0.55153 |
rs = TList()
for e in self:
if func(e) not in rs.map(func):
rs.append(e)
return rs | def uniq_by(self, func: Callable[[T], Any]) -> 'TList[T]' | Usage:
>>> TList([1, 2, 3, -2, -1]).uniq_by(lambda x: x**2)
[1, 2, 3] | 3.648276 | 5.052746 | 0.722038 |
ret = TDict()
for v in self:
k = to_key(v)
ret.setdefault(k, TList())
ret[k].append(v)
return ret | def group_by(self, to_key) | :param to_key:
:type to_key: T -> unicode
:rtype: TDict[TList[T]]
Usage:
>>> TList([1, 2, 3, 4, 5]).group_by(lambda x: x % 2).to_json()
'{"0": [2,4],"1": [1,3,5]}' | 3.080285 | 2.67149 | 1.153021 |
return TDict({to_key(x): x for x in self}) | def key_by(self, to_key: Callable[[T], str]) -> 'TDict[T]' | :param to_key: value -> key
Usage:
>>> TList(['a1', 'b2', 'c3']).key_by(lambda x: x[0]).to_json()
'{"a": "a1","b": "b2","c": "c3"}'
>>> TList([1, 2, 3, 4, 5]).key_by(lambda x: x % 2).to_json()
'{"0": 4,"1": 5}' | 4.171081 | 4.798302 | 0.869283 |
return TList(sorted(self, key=func, reverse=reverse)) | def order_by(self, func, reverse=False) | :param func:
:type func: T -> any
:param reverse: Sort by descend order if True, else by ascend
:type reverse: bool
:rtype: TList[T]
Usage:
>>> TList([12, 25, 31, 40, 57]).order_by(lambda x: x % 10)
[40, 31, 12, 25, 57]
>>> TList([12, 25, 31,... | 5.888999 | 5.302896 | 1.110525 |
return values + self if first else self + values | def concat(self, values, first=False) | :param values:
:type values: TList[T]
:param first:
:type first: bool
:rtype: TList[T]
Usage:
>>> TList([1, 2]).concat(TList([3, 4]))
[1, 2, 3, 4]
>>> TList([1, 2]).concat(TList([3, 4]), first=True)
[3, 4, 1, 2] | 18.369572 | 15.259247 | 1.203832 |
for x in self:
if func(x):
return TOption(x)
return TOption(None) | def find(self, func: Callable[[T], bool]) -> TOption[T] | Usage:
>>> TList([1, 2, 3, 4, 5]).find(lambda x: x > 3)
Option --> 4
>>> TList([1, 2, 3, 4, 5]).find(lambda x: x > 6)
Option --> None | 3.41364 | 5.609149 | 0.608584 |
return TOption(self[key]) if key in self else TOption(None) | def get(self, key: K) -> TOption[T] | :param key:
Usage:
>>> TDict(k1=1, k2=2, k3=3).get("k2")
Option --> 2
>>> TDict(k1=1, k2=2, k3=3).get("unknown")
Option --> None | 5.075057 | 7.736765 | 0.655966 |
return TList([func(k, v) for k, v in self.items()]) | def map(self, func) | :param func:
:type func: (K, T) -> U
:rtype: TList[U]
Usage:
>>> sorted(TDict(k1=1, k2=2, k3=3).map(lambda k, v: v*2))
[2, 4, 6] | 6.458414 | 4.148875 | 1.556666 |
return TDict({k: func(v) for k, v in self.items()}) | def map_values(self, func) | :param func:
:type func: T -> U
:rtype: TDict[U]
Usage:
>>> TDict(k1=1, k2=2, k3=3).map_values(lambda x: x*2) == {
... "k1": 2,
... "k2": 4,
... "k3": 6
... }
True | 4.80308 | 4.120495 | 1.165656 |
return TDict({k: func(k, v) for k, v in self.items()}) | def map_values2(self, func) | :param func:
:type func: (K, T) -> U
:rtype: TDict[U]
Usage:
>>> TDict(k1=1, k2=2, k3=3).map_values2(lambda k, v: f'{k} -> {v*2}') == {
... "k1": "k1 -> 2",
... "k2": "k2 -> 4",
... "k3": "k3 -> 6"
... }
True | 5.143313 | 3.62362 | 1.419385 |
return TList([v for k, v in self.items() if func(k, v)]) | def filter(self, func) | :param func:
:type func: (K, T) -> bool
:rtype: TList[T]
Usage:
>>> TDict(k1=1, k2=2, k3=3).filter(lambda k, v: v < 2)
[1] | 5.176886 | 3.821753 | 1.354584 |
return TList([v for k, v in self.items() if not func(k, v)]) | def reject(self, func) | :param func:
:type func: (K, T) -> bool
:rtype: TList[T]
Usage:
>>> TDict(k1=1, k2=2, k3=3).reject(lambda k, v: v < 3)
[3] | 5.499981 | 3.729806 | 1.474602 |
for k, v in self.items():
if func(k, v):
return TOption(v)
return TOption(None) | def find(self, func: Callable[[K, T], bool]) -> TOption[T] | Usage:
>>> TDict(k1=1, k2=2, k3=3).find(lambda k, v: v == 2)
Option --> 2
>>> TDict(k1=1, k2=2, k3=3).find(lambda k, v: v == 4)
Option --> None | 2.804732 | 3.867593 | 0.725188 |
return all([func(k, v) for k, v in self.items()]) | def all(self, func) | :param func:
:type func: (K, T) -> bool
:rtype: bool
Usage:
>>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 0)
True
>>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 1)
False | 4.943496 | 4.351054 | 1.136161 |
return any([func(k, v) for k, v in self.items()]) | def any(self, func) | :param func:
:type func: (K, T) -> bool
:rtype: bool
Usage:
>>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 2)
True
>>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 3)
False | 4.924037 | 4.662519 | 1.056089 |
return TDict({k: v for k, v in self.items() if func(k, v)}) | def pick_by(self, func: Callable[[K, T], bool]) -> 'TDict[T]' | Usage:
>>> TDict(k1=1, k2=2, k3=3).pick_by(lambda k, v: v > 2)
{'k3': 3} | 2.410111 | 3.148238 | 0.765543 |
# self.document.append("<!-- storeSectionState(): " + str(len(self.header_stack)) + " open section tags. " + str(self.header_stack) + "-->\n")
try:
# special case. we are not processing an OOo XML start tag which we
# are going to insert <section> before. we have rea... | def storeSectionState(self, level) | Takes a header tagname (e.g. 'h1') and adjusts the
stack that remembers the headers seen. | 5.168852 | 4.975003 | 1.038965 |
iSectionsClosed = self.storeSectionState(level)
self.document.append("</section>\n" * iSectionsClosed) | def endSections(self, level=u'0') | Closes all sections of level >= sectnum. Defaults to closing all open sections | 22.469213 | 23.014566 | 0.976304 |
return traverse_dict(self._dict, ignore_none, force_value, ignore_empty) | def to_dict(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> dict | From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which inherited if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Dict
... | 6.451053 | 9.078491 | 0.710586 |
return traverse_list(self, ignore_none, force_value, ignore_empty) | def to_dicts(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> List[dict] | From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which inherited if True
:param ignore_empty: Properties which is empty are excluded if True
:return: List[Di... | 6.034365 | 14.02236 | 0.430339 |
return util.dump_json(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), indent) | def to_json(self, indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str | From instance to json string
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Huma... | 9.194562 | 14.045955 | 0.654606 |
return util.save_jsonf(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), fpath, encoding, indent) | def to_jsonf(self, fpath: str, encoding: str='utf8', indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str | From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return:... | 7.752807 | 9.895345 | 0.78348 |
return self.to_json(4, ignore_none, ignore_empty) | def to_pretty_json(self, ignore_none: bool=True, ignore_empty: bool=False) -> str | From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_d... | 7.222677 | 9.249372 | 0.780883 |
return util.dump_yaml(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty)) | def to_yaml(self, ignore_none: bool=True, ignore_empty: bool=False) -> str | From instance to yaml string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Yaml string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... | 10.264136 | 16.876337 | 0.608197 |
return util.save_yamlf(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), fpath, encoding) | def to_yamlf(self, fpath: str, encoding: str='utf8', ignore_none: bool=True, ignore_empty: bool=False) -> str | From instance to yaml file
:param ignore_none: Properties which is None are excluded if True
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:return: Yaml file path | 9.268528 | 10.871523 | 0.852551 |
return util.dump_csv(traverse(self, force_value=True), fieldnames, with_header, crlf, tsv) | def to_csv(self, fieldnames: Sequence[str], with_header: bool=False, crlf: bool=False, tsv: bool=False) -> str | From sequence of text to csv string
:param fieldnames: Order of columns by property name
:param with_header: Add headers at the first line if True
:param crlf: Add CRLF line break at the end of line if True, else add LF
:param tsv: Use tabs as separator if True, else use comma
:... | 10.41974 | 16.050077 | 0.649202 |
return util.save_csvf(traverse(self, force_value=True), fieldnames, fpath, encoding, with_header, crlf, tsv) | def to_csvf(self, fpath: str, fieldnames: Sequence[str], encoding: str='utf8',
with_header: bool=False, crlf: bool=False, tsv: bool=False) -> str | From instance to yaml file
:param fpath: Csv file path
:param fieldnames: Order of columns by property name
:param encoding: Csv file encoding
:param with_header: Add headers at the first line if True
:param crlf: Add CRLF line break at the end of line if True, else add LF
... | 8.597618 | 11.145555 | 0.771394 |
return util.dump_table(traverse(self, force_value=True), fieldnames) | def to_table(self, fieldnames: Sequence[str]) -> str | From sequence of text to csv string
:param fieldnames: Order of columns by property name
:return: Table string
Usage:
>>> from owlmixin.samples import Human
>>> humans = Human.from_dicts([
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... | 31.859518 | 51.019337 | 0.62446 |
tree = etree.fromstring(html, etree.HTMLParser())
for el in tree.xpath('//u'):
el.tag = 'em'
c = el.attrib.get('class', '').split()
if 'underline' not in c:
c.append('underline')
el.attrib['class'] = ' '.join(c)
return tohtml(tree) | def _pre_tidy(html) | This method transforms a few things before tidy runs. When we get rid
of tidy, this can go away. | 3.101879 | 3.319633 | 0.934404 |
tree = etree.fromstring(html)
ems = tree.xpath(
"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]",
namespaces={'xh': 'http://www.w3.org/1999/xhtml'})
for el in ems:
c = el.attrib.get('class', '').split()
c.remove('underline')
el.tag = '{http:... | def _post_tidy(html) | This method transforms post tidy. Will go away when tidy goes away. | 2.883671 | 2.88166 | 1.000698 |
path = pkg_resources.resource_filename('rhaptos.cnxmlutils.xsl', filename)
xml = etree.parse(path)
return etree.XSLT(xml) | def _make_xsl(filename) | Helper that creates a XSLT stylesheet | 8.185149 | 8.211335 | 0.996811 |
xslt = _make_xsl(xsl_filename)
xml = xslt(xml, **kwargs)
return xml | def _transform(xsl_filename, xml, **kwargs) | Transforms the xml using the specifiec xsl file. | 4.396005 | 4.400965 | 0.998873 |
xpath_math_script = etree.XPath(
'//x:script[@type="math/mml"]',
namespaces={'x': 'http://www.w3.org/1999/xhtml'})
math_script_list = xpath_math_script(xml)
for mathscript in math_script_list:
math = mathscript.text
# some browsers double escape like e.g. Firefox... | def _unescape_math(xml) | Unescapes Math from Mathjax to MathML. | 3.028484 | 2.863292 | 1.057693 |
source = _string2io(cnxml_source)
xml = etree.parse(source)
# Run the CNXML to HTML transform
xml = _transform('cnxml-to-html5.xsl', xml,
version='"{}"'.format(version))
xml = XHTML_MODULE_BODY_XPATH(xml)
return etree.tostring(xml[0]) | def cnxml_to_html(cnxml_source) | Transform the CNXML source to HTML | 8.406373 | 8.151644 | 1.031249 |
xml = _tidy2xhtml5(html_source)
for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE):
xml = transform(xml)
return xml | def aloha_to_etree(html_source) | Converts HTML5 from Aloha editor output to a lxml etree. | 10.964132 | 10.07098 | 1.088686 |
xml = aloha_to_etree(html_source)
return etree.tostring(xml, pretty_print=True) | def aloha_to_html(html_source) | Converts HTML5 from Aloha to a more structured HTML5 | 3.007724 | 3.196394 | 0.940974 |
source = _string2io(html_source)
xml = etree.parse(source)
cnxml = etree.parse(_string2io(cnxml_source))
# Run the HTML to CNXML transform on it
xml = _transform('html5-to-cnxml.xsl', xml)
# Replace the original content element with the transformed one.
namespaces = {'c': 'http://cnx.ri... | def html_to_cnxml(html_source, cnxml_source) | Transform the HTML to CNXML. We need the original CNXML content in
order to preserve the metadata in the CNXML document. | 4.205533 | 4.055149 | 1.037085 |
source = _string2io(html_source)
xml = etree.parse(source)
return etree_to_valid_cnxml(xml, pretty_print=True) | def html_to_valid_cnxml(html_source) | Transform the HTML to valid CNXML (used for OERPUB).
No original CNXML is needed. If HTML is from Aloha please use
aloha_to_html before using this method | 4.773991 | 5.064377 | 0.942661 |
return default if self.value is None else self.value | def get_or(self, default: T) -> T | Usage:
>>> TOption(3).get_or(999)
3
>>> TOption(0).get_or(999)
0
>>> TOption(None).get_or(999)
999 | 7.925127 | 10.515812 | 0.753639 |
return self if self.is_none() else TOption(func(self.value)) | def map(self, func: Callable[[T], U]) -> 'TOption[T]' | Usage:
>>> TOption(3).map(lambda x: x+1).get()
4
>>> TOption(None).map(lambda x: x+1).get_or(999)
999 | 4.460931 | 4.671162 | 0.954994 |
return self if self.is_none() else TOption(func(self.value).get()) | def flat_map(self, func: Callable[[T], 'TOption[T]']) -> 'TOption[T]' | Usage:
>>> TOption(3).flat_map(lambda x: TOption(x+1)).get()
4
>>> TOption(3).flat_map(lambda x: TOption(None)).get_or(999)
999
>>> TOption(None).flat_map(lambda x: TOption(x+1)).get_or(999)
999 | 5.443457 | 5.862374 | 0.928541 |
for hex, value in UNICODE_DICTIONARY.items():
num = int(hex[3:-1], 16)
#uni = unichr(num)
decimal = '&#' + str(num) + ';'
for key in [ hex, decimal ]: #uni
text = text.replace(key, value)
return text | def replace(text) | Replace both the hex and decimal versions of symbols in an XML string | 6.358479 | 5.761012 | 1.103709 |
return {
to_snake(keymap.get(k, k)) if force_snake_case else keymap.get(k, k):
v for k, v in d.items()
} | def replace_keys(d, keymap, force_snake_case) | :param dict d:
:param Dict[unicode, unicode] keymap:
:param bool force_snake_case:
:rtype: Dict[unicode, unicode] | 2.9826 | 3.078227 | 0.968934 |
with codecs.open(fpath, encoding=encoding) as f:
return json.load(f) | def load_jsonf(fpath, encoding) | :param unicode fpath:
:param unicode encoding:
:rtype: dict | list | 2.212623 | 2.881124 | 0.767972 |
with codecs.open(fpath, encoding=encoding) as f:
return yaml.safe_load(f) | def load_yamlf(fpath, encoding) | :param unicode fpath:
:param unicode encoding:
:rtype: dict | list | 2.263223 | 2.916808 | 0.775925 |
with open(fpath, mode='r', encoding=encoding) as f:
snippet = f.read(8192)
f.seek(0)
dialect = csv.Sniffer().sniff(snippet)
dialect.skipinitialspace = True
return list(csv.DictReader(f, fieldnames=fieldnames, dialect=dialect)) | def load_csvf(fpath, fieldnames, encoding) | :param unicode fpath:
:param Optional[list[unicode]] fieldnames:
:param unicode encoding:
:rtype: List[dict] | 2.253816 | 2.387649 | 0.943948 |
def force_str(v):
# XXX: Double quotation behaves strangely... so replace (why?)
return dump_json(v).replace('"', "'") if isinstance(v, (dict, list)) else v
with io.StringIO() as sio:
dialect = get_dialect_name(crlf, tsv)
writer = csv.DictWriter(sio, fieldnames=fieldnames,... | def dump_csv(data: List[dict], fieldnames: Sequence[str], with_header: bool = False, crlf: bool = False,
tsv: bool = False) -> str | :param data:
:param fieldnames:
:param with_header:
:param crlf:
:param tsv:
:return: unicode | 3.543205 | 3.320472 | 1.067079 |
with codecs.open(fpath, mode='w', encoding=encoding) as f:
f.write(dump_csv(data, fieldnames, with_header=with_header, crlf=crlf, tsv=tsv))
return fpath | def save_csvf(data: list, fieldnames: Sequence[str], fpath: str, encoding: str, with_header: bool = False,
crlf: bool = False, tsv: bool = False) -> str | :param data:
:param fieldnames:
:param fpath: write path
:param encoding: encoding
:param with_header:
:param crlf:
:param tsv:
:return: written path | 2.46571 | 2.246956 | 1.097356 |
return json.dumps(data,
indent=indent,
ensure_ascii=False,
sort_keys=True,
separators=(',', ': ')) | def dump_json(data, indent=None) | :param list | dict data:
:param Optional[int] indent:
:rtype: unicode | 2.267108 | 2.295074 | 0.987815 |
with codecs.open(fpath, mode='w', encoding=encoding) as f:
f.write(dump_json(data, indent))
return fpath | def save_jsonf(data: Union[list, dict], fpath: str, encoding: str, indent=None) -> str | :param data: list | dict data
:param fpath: write path
:param encoding: encoding
:param indent:
:rtype: written path | 3.413535 | 3.265032 | 1.045483 |
return yaml.dump(data,
indent=2,
encoding=None,
allow_unicode=True,
default_flow_style=False,
Dumper=MyDumper) | def dump_yaml(data) | :param list | dict data:
:rtype: unicode | 2.923859 | 2.927857 | 0.998635 |
with codecs.open(fpath, mode='w', encoding=encoding) as f:
f.write(dump_yaml(data))
return fpath | def save_yamlf(data: Union[list, dict], fpath: str, encoding: str) -> str | :param data: list | dict data
:param fpath: write path
:param encoding: encoding
:rtype: written path | 3.347301 | 3.16902 | 1.056257 |
def min3(num: int) -> int:
return 3 if num < 4 else num
width_by_col: Dict[str, int] = {
f: min3(max([string_width(str(d.get(f))) for d in data] + [string_width(f)])) for f in fieldnames
}
def fill_spaces(word: str, width: int, center=False):
to_fills: int = widt... | def dump_table(data: List[dict], fieldnames: Sequence[str]) -> str | :param data:
:param fieldnames:
:return: Table string | 3.714378 | 3.454834 | 1.075125 |
return sum(map(lambda x: 2 if east_asian_width(x) in 'FWA' else 1, word)) | def string_width(word: str) -> int | :param word:
:return: Widths of word
Usage:
>>> string_width('abc')
3
>>> string_width('Abしー')
7
>>> string_width('')
0 | 4.657678 | 5.07508 | 0.917755 |
xmlfile = open(filename, 'w')
# pretty print
content = etree.tostring(content, pretty_print=True)
xmlfile.write(content)
xmlfile.close() | def writeXMLFile(filename, content) | Used only for debugging to write out intermediate files | 2.492811 | 2.417628 | 1.031098 |
return [x for x in cls.__members__.values() if x.value[0] == value][0] | def from_value(cls, value: str) -> T | Create instance from symbol
:param value: unique symbol
:return: This instance
Usage:
>>> from owlmixin.samples import Animal
>>> Animal.from_value('cat').crow()
mewing | 4.628736 | 7.983595 | 0.579781 |
icefile = opt.thaw_from
if not os.path.exists(icefile):
raise aomi.exceptions.IceFile("%s missing" % icefile)
thaw(vault_client, icefile, opt)
return opt | def auto_thaw(vault_client, opt) | Will thaw into a temporary location | 7.73449 | 7.519884 | 1.028539 |
if opt.thaw_from:
opt.secrets = tempfile.mkdtemp('aomi-thaw')
auto_thaw(vault_client, opt)
Context.load(get_secretfile(opt), opt) \
.fetch(vault_client) \
.sync(vault_client, opt)
if opt.thaw_from:
rmtree(opt.secrets) | def seed(vault_client, opt) | Will provision vault based on the definition within a Secretfile | 8.310349 | 7.566523 | 1.098305 |
if not os.path.exists(directory) and not os.path.isdir(directory):
os.mkdir(directory)
a_secretfile = render_secretfile(opt)
s_path = "%s/Secretfile" % directory
LOG.debug("writing Secretfile to %s", s_path)
open(s_path, 'w').write(a_secretfile)
ctx = Context.load(yaml.safe_load(a_... | def render(directory, opt) | Render any provided template. This includes the Secretfile,
Vault policies, and inline AWS roles | 2.51727 | 2.335114 | 1.078007 |
ctx = Context.load(get_secretfile(opt), opt) \
.fetch(vault_client)
for resource in ctx.resources():
resource.export(opt.directory) | def export(vault_client, opt) | Export contents of a Secretfile from the Vault server
into a specified directory. | 11.711782 | 9.473396 | 1.236281 |
if opt.monochrome:
return msg
return colored(msg, color) | def maybe_colored(msg, color, opt) | Maybe it will render in color maybe it will not! | 7.031977 | 6.827005 | 1.030024 |
if is_unicode(val) and val.isdigit():
return int(val)
elif isinstance(val, list):
return ','.join(val)
elif val is None:
return ''
return val | def normalize_val(val) | Normalize JSON/YAML derived values as they pertain
to Vault resources and comparison operations | 3.696781 | 4.241301 | 0.871615 |
existing = dict_unicodeize(existing)
obj = dict_unicodeize(obj)
for ex_k, ex_v in iteritems(existing):
new_value = normalize_val(obj.get(ex_k))
og_value = normalize_val(ex_v)
if ex_k in obj and og_value != new_value:
print(maybe_colored("-- %s: %s" % (ex_k, og_value)... | def details_dict(obj, existing, ignore_missing, opt) | Output the changes, if any, for a dict | 2.366641 | 2.371239 | 0.998061 |
if opt.verbose == 0:
return
if not resource.present:
return
obj = None
existing = None
if isinstance(resource, Resource):
obj = resource.obj()
existing = resource.existing
elif isinstance(resource, VaultBackend):
obj = resource.config
exist... | def maybe_details(resource, opt) | At the first level of verbosity this will print out detailed
change information on for the specified Vault resource | 2.839897 | 2.777306 | 1.022537 |
changed = thing.diff()
if changed == ADD:
print("%s %s" % (maybe_colored("+", "green", opt), str(thing)))
elif changed == DEL:
print("%s %s" % (maybe_colored("-", "red", opt), str(thing)))
elif changed == CHANGED:
print("%s %s" % (maybe_colored("~", "yellow", opt), str(thing... | def diff_a_thing(thing, opt) | Handle the diff action for a single thing. It may be a Vault backend
implementation or it may be a Vault data resource | 2.459525 | 2.608543 | 0.942873 |
if opt.thaw_from:
opt.secrets = tempfile.mkdtemp('aomi-thaw')
auto_thaw(vault_client, opt)
ctx = Context.load(get_secretfile(opt), opt) \
.fetch(vault_client)
for backend in ctx.mounts():
diff_a_thing(backend, opt)
for resource in ctx.resources():
... | def diff(vault_client, opt) | Derive a comparison between what is represented in the Secretfile
and what is actually live on a Vault instance | 7.212139 | 6.851951 | 1.052567 |
print("aomi v%s" % version)
print('Get started with aomi'
' https://autodesk.github.io/aomi/quickstart')
if opt.verbose == 2:
tf_str = 'Token File,' if token_file() else ''
app_str = 'AppID File,' if appid_file() else ''
approle_str = 'Approle File,' if approle_file() ... | def help_me(parser, opt) | Handle display of help and whatever diagnostics | 4.087317 | 4.060179 | 1.006684 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.