sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def transform_cnxml(cnxml_file): """ Given a module cnxml file (index.cnxml) this returns an HTML version of it """ xml = etree.parse(cnxml_file) xslt = makeXsl('cnxml2xhtml.xsl') xml = xslt(xml) return xml
Given a module cnxml file (index.cnxml) this returns an HTML version of it
entailment
def transform_collection(collection_dir): """ Given an unzipped collection generate a giant HTML file representing the entire collection (including loading and converting individual modules) """ 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 = None # We don't care about version module_dir = os.path.join(collection_dir, module) # By default, use the index_auto_generated.cnxml file for the module module_path = os.path.join(module_dir, 'index_auto_generated.cnxml') if not os.path.exists(module_path): module_path = os.path.join(module_dir, 'index.cnxml') module_html = transform_cnxml(module_path) # Replace the include link with the body of the module module_body = MODULE_BODY_XPATH(module_html) node.getparent().replace(node, module_body[0]) return collxml_html
Given an unzipped collection generate a giant HTML file representing the entire collection (including loading and converting individual modules)
entailment
def from_dict(cls, d: dict, force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> T: """From dict to 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: >>> from owlmixin.samples import Human, Food, Japanese >>> human: Human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].name 'Apple' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel' You can use default value >>> taro: Japanese = Japanese.from_dict({ ... "name": 'taro' ... }) # doctest: +NORMALIZE_WHITESPACE >>> taro.name 'taro' >>> taro.language 'japanese' If you don't set `force_snake=False` explicitly, keys are transformed to snake case as following. >>> human: Human = Human.from_dict({ ... "--id": 1, ... "<name>": "Tom", ... "favorites": [ ... {"name": "Apple", "namesByLang": {"en": "Apple"}} ... ] ... }) >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["en"] 'Apple' You can allow extra parameters (like ``hogehoge``) if you set `restrict=False`. >>> apple: Food = Food.from_dict({ ... "name": "Apple", ... "hogehoge": "ooooooooooooooooooooo", ... }, restrict=False) >>> apple.to_dict() {'name': 'Apple'} You can prohibit extra parameters (like ``hogehoge``) if you set `restrict=True` (which is default). >>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "hogehoge1": "ooooooooooooooooooooo", ... "hogehoge2": ["aaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiii"], ... "favorites": [ ... {"name": "Apple", "namesByLang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.UnknownPropertiesError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Unknown properties error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human` has unknown properties ['hogehoge1', 'hogehoge2']!! <BLANKLINE> * If you want to allow unknown properties, set `restrict=False` * If you want to disallow unknown properties, add `hogehoge1` and `hogehoge2` to owlmixin.samples.Human <BLANKLINE> If you specify wrong type... >>> human: Human = Human.from_dict({ ... "id": 1, ... "name": "ichiro", ... "favorites": ["apple", "orange"] ... }) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.InvalidTypeError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Invalid Type error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human#favorites.0 = apple` doesn't match expected types. Expected type is one of ['Food', 'dict'], but actual type is `str` <BLANKLINE> * If you want to force cast, set `force_cast=True` * If you don't want to force cast, specify value which has correct type <BLANKLINE> If you don't specify required params... (ex. name >>> human: Human = Human.from_dict({ ... "id": 1 ... }) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.RequiredError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Required error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human#name: str` is empty!! <BLANKLINE> * If `name` is certainly required, specify anything. * If `name` is optional, change type from `str` to `TOption[str]` <BLANKLINE> """ if isinstance(d, cls): return d instance: T = cls() d = util.replace_keys(d, {"self": "_self"}, force_snake_case) properties = cls.__annotations__.items() if restrict: assert_extra(properties, d, cls) for n, t in properties: f = cls._methods_dict.get(f'_{cls.__name__}___{n}') arg_v = f(d.get(n)) if f else d.get(n) def_v = getattr(instance, n, None) setattr(instance, n, traverse( type_=t, name=n, value=def_v if arg_v is None else arg_v, cls=cls, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict )) return instance
From dict to 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: >>> from owlmixin.samples import Human, Food, Japanese >>> human: Human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].name 'Apple' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel' You can use default value >>> taro: Japanese = Japanese.from_dict({ ... "name": 'taro' ... }) # doctest: +NORMALIZE_WHITESPACE >>> taro.name 'taro' >>> taro.language 'japanese' If you don't set `force_snake=False` explicitly, keys are transformed to snake case as following. >>> human: Human = Human.from_dict({ ... "--id": 1, ... "<name>": "Tom", ... "favorites": [ ... {"name": "Apple", "namesByLang": {"en": "Apple"}} ... ] ... }) >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["en"] 'Apple' You can allow extra parameters (like ``hogehoge``) if you set `restrict=False`. >>> apple: Food = Food.from_dict({ ... "name": "Apple", ... "hogehoge": "ooooooooooooooooooooo", ... }, restrict=False) >>> apple.to_dict() {'name': 'Apple'} You can prohibit extra parameters (like ``hogehoge``) if you set `restrict=True` (which is default). >>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "hogehoge1": "ooooooooooooooooooooo", ... "hogehoge2": ["aaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiii"], ... "favorites": [ ... {"name": "Apple", "namesByLang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.UnknownPropertiesError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Unknown properties error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human` has unknown properties ['hogehoge1', 'hogehoge2']!! <BLANKLINE> * If you want to allow unknown properties, set `restrict=False` * If you want to disallow unknown properties, add `hogehoge1` and `hogehoge2` to owlmixin.samples.Human <BLANKLINE> If you specify wrong type... >>> human: Human = Human.from_dict({ ... "id": 1, ... "name": "ichiro", ... "favorites": ["apple", "orange"] ... }) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.InvalidTypeError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Invalid Type error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human#favorites.0 = apple` doesn't match expected types. Expected type is one of ['Food', 'dict'], but actual type is `str` <BLANKLINE> * If you want to force cast, set `force_cast=True` * If you don't want to force cast, specify value which has correct type <BLANKLINE> If you don't specify required params... (ex. name >>> human: Human = Human.from_dict({ ... "id": 1 ... }) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.RequiredError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Required error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human#name: str` is empty!! <BLANKLINE> * If `name` is certainly required, specify anything. * If `name` is optional, change type from `str` to `TOption[str]` <BLANKLINE>
entailment
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: >>> from owlmixin.samples import Human >>> Human.from_optional_dict(None).is_none() True >>> Human.from_optional_dict({}).get() # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.RequiredError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Required error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human#id: int` is empty!! <BLANKLINE> * If `id` is certainly required, specify anything. * If `id` is optional, change type from `int` to `TOption[int]` <BLANKLINE> """ 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)
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: >>> from owlmixin.samples import Human >>> Human.from_optional_dict(None).is_none() True >>> Human.from_optional_dict({}).get() # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.RequiredError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Required error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human#id: int` is empty!! <BLANKLINE> * If `id` is certainly required, specify anything. * If `id` is optional, change type from `int` to `TOption[int]` <BLANKLINE>
entailment
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 Usage: >>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_dicts([ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]) >>> humans[0].name 'Tom' >>> humans[1].name 'John' """ return TList([cls.from_dict(d, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict) for d in ds])
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 Usage: >>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_dicts([ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]) >>> humans[0].name 'Tom' >>> humans[1].name 'John'
entailment
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 instance Usage: >>> from owlmixin.samples import Human >>> Human.from_optional_dicts(None).is_none() True >>> Human.from_optional_dicts([]).get() [] """ 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)
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 instance Usage: >>> from owlmixin.samples import Human >>> Human.from_optional_dicts(None).is_none() True >>> Human.from_optional_dicts([]).get() []
entailment
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 Usage: >>> from owlmixin.samples import Human >>> humans_by_name: TDict[Human] = Human.from_dicts_by_key({ ... 'Tom': {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... 'John': {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... }) >>> humans_by_name['Tom'].name 'Tom' >>> humans_by_name['John'].name 'John' """ 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()})
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 Usage: >>> from owlmixin.samples import Human >>> humans_by_name: TDict[Human] = Human.from_dicts_by_key({ ... 'Tom': {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... 'John': {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... }) >>> humans_by_name['Tom'].name 'Tom' >>> humans_by_name['John'].name 'John'
entailment
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 instance Usage: >>> from owlmixin.samples import Human >>> Human.from_optional_dicts_by_key(None).is_none() True >>> Human.from_optional_dicts_by_key({}).get() {} """ 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)
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 instance Usage: >>> from owlmixin.samples import Human >>> Human.from_optional_dicts_by_key(None).is_none() True >>> Human.from_optional_dicts_by_key({}).get() {}
entailment
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: >>> from owlmixin.samples import Human >>> human: Human = Human.from_json('''{ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }''') >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel' """ return cls.from_dict(util.load_json(data), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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: >>> from owlmixin.samples import Human >>> human: Human = Human.from_json('''{ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }''') >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel'
entailment
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 True :return: Instance """ return cls.from_dict(util.load_jsonf(fpath, encoding), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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 True :return: Instance
entailment
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 Usage: >>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_json_to_list('''[ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]''') >>> humans[0].name 'Tom' >>> humans[1].name 'John' """ return cls.from_dicts(util.load_json(data), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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 Usage: >>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_json_to_list('''[ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]''') >>> humans[0].name 'Tom' >>> humans[1].name 'John'
entailment
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 parameters if True :return: List of instance """ return cls.from_dicts(util.load_jsonf(fpath, encoding), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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 parameters if True :return: List of instance
entailment
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: >>> from owlmixin.samples import Human >>> human: Human = Human.from_yaml(''' ... id: 1 ... name: Tom ... favorites: ... - name: Apple ... names_by_lang: ... en: Apple ... de: Apfel ... - name: Orange ... ''') >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel' """ return cls.from_dict(util.load_yaml(data), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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: >>> from owlmixin.samples import Human >>> human: Human = Human.from_yaml(''' ... id: 1 ... name: Tom ... favorites: ... - name: Apple ... names_by_lang: ... en: Apple ... de: Apfel ... - name: Orange ... ''') >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel'
entailment
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 True :return: Instance """ return cls.from_dict(util.load_yamlf(fpath, encoding), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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 True :return: Instance
entailment
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 Usage: >>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_yaml_to_list(''' ... - id: 1 ... name: Tom ... favorites: ... - name: Apple ... - id: 2 ... name: John ... favorites: ... - name: Orange ... ''') >>> humans[0].name 'Tom' >>> humans[1].name 'John' >>> humans[0].favorites[0].name 'Apple' """ return cls.from_dicts(util.load_yaml(data), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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 Usage: >>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_yaml_to_list(''' ... - id: 1 ... name: Tom ... favorites: ... - name: Apple ... - id: 2 ... name: John ... favorites: ... - name: Orange ... ''') >>> humans[0].name 'Tom' >>> humans[1].name 'John' >>> humans[0].favorites[0].name 'Apple'
entailment
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 parameters if True :return: List of instance """ return cls.from_dicts(util.load_yamlf(fpath, encoding), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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 parameters if True :return: List of instance
entailment
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 restrict: Prohibit extra parameters if True :return: List of Instance """ return cls.from_dicts(util.load_csvf(fpath, fieldnames, encoding), force_snake_case=force_snake_case, force_cast=True, restrict=restrict)
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 restrict: Prohibit extra parameters if True :return: List of Instance
entailment
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 """ return cls.from_dict(util.load_json_url(url), force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict)
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
entailment
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 """ return TOption(self[index]) if len(self) > index else TOption(None)
:param index: Usage: >>> TList([1, 2, 3, 4, 5]).get(3) Option --> 4 >>> TList([1, 2, 3, 4, 5]).get(5) Option --> None
entailment
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)] """ return TList([func(x, i) for i, x in enumerate(self)])
: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)]
entailment
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] """ r = TList() for x in self: if not func(x): return r else: r.append(x) return r
:param func: :type func: T -> bool Usage: >>> TList([1, 2, 30, 4, 50]).head_while(lambda x: x < 10) [1, 2]
entailment
def uniq(self) -> 'TList[T]': """ Usage: >>> TList([1, 2, 3, 2, 1]).uniq() [1, 2, 3] """ rs = TList() for e in self: if e not in rs: rs.append(e) return rs
Usage: >>> TList([1, 2, 3, 2, 1]).uniq() [1, 2, 3]
entailment
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] """ rs = TList() for e in self: if func(e) not in rs.map(func): rs.append(e) return rs
Usage: >>> TList([1, 2, 3, -2, -1]).uniq_by(lambda x: x**2) [1, 2, 3]
entailment
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]}' """ ret = TDict() for v in self: k = to_key(v) ret.setdefault(k, TList()) ret[k].append(v) return ret
: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]}'
entailment
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}' """ return TDict({to_key(x): x for x in self})
: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}'
entailment
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, 40, 57]).order_by(lambda x: x % 10, reverse=True) [57, 25, 12, 31, 40] """ return TList(sorted(self, key=func, reverse=reverse))
: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, 40, 57]).order_by(lambda x: x % 10, reverse=True) [57, 25, 12, 31, 40]
entailment
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] """ return values + self if first else self + values
: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]
entailment
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 """ for x in self: if func(x): return TOption(x) return TOption(None)
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
entailment
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 """ return TOption(self[key]) if key in self else TOption(None)
: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
entailment
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] """ return TList([func(k, v) for k, v in self.items()])
: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]
entailment
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 """ return TDict({k: func(v) for k, v in self.items()})
: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
entailment
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 """ return TDict({k: func(k, v) for k, v in self.items()})
: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
entailment
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] """ return TList([v for k, v in self.items() if func(k, v)])
: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]
entailment
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] """ return TList([v for k, v in self.items() if not func(k, v)])
: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]
entailment
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 """ for k, v in self.items(): if func(k, v): return TOption(v) return TOption(None)
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
entailment
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 """ return all([func(k, v) for k, v in self.items()])
: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
entailment
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 """ return any([func(k, v) for k, v in self.items()])
: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
entailment
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} """ return TDict({k: v for k, v in self.items() if func(k, v)})
Usage: >>> TDict(k1=1, k2=2, k3=3).pick_by(lambda k, v: v > 2) {'k3': 3}
entailment
def storeSectionState(self, level): """ Takes a header tagname (e.g. 'h1') and adjusts the stack that remembers the headers seen. """ # 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 reached a point # where all sections need to be closed. EG </office:body> or </text:section>, # both of which are hierarchical => scope closure for all open <section> tags bClosedAllSections = ( level == u'0' ) if bClosedAllSections: # have reached a point where all sections need to be closed iSectionsClosed = len(self.header_stack) while len(self.header_stack) > 0: del(self.header_stack[-1]) return iSectionsClosed if len(self.header_stack) == 0: # no open section tags iSectionsClosed = 0 self.header_stack.append(level) else: iLastLevel = self.header_stack[-1] if level > iLastLevel: # open sections tags AND no sections need closing iSectionsClosed = 0 self.header_stack.append(level) elif level == iLastLevel: # open sections tags AND need to closed one of the sections iSectionsClosed = 1 # imagine deleting the last level and then re-adding it elif level < iLastLevel: # open sections tags AND need to closed some of the sections del(self.header_stack[-1]) iSectionsClosed = 1 iSectionsClosed += self.storeSectionState(level) return iSectionsClosed except IndexError: print level raise
Takes a header tagname (e.g. 'h1') and adjusts the stack that remembers the headers seen.
entailment
def endSections(self, level=u'0'): """Closes all sections of level >= sectnum. Defaults to closing all open sections""" iSectionsClosed = self.storeSectionState(level) self.document.append("</section>\n" * iSectionsClosed)
Closes all sections of level >= sectnum. Defaults to closing all open sections
entailment
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 Usage: >>> from owlmixin.samples import Human, Food >>> human_dict = { ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple"}} ... ] ... } >>> Human.from_dict(human_dict).to_dict() == human_dict True You can include None properties by specifying False for ignore_none >>> f = Food.from_dict({"name": "Apple"}).to_dict(ignore_none=False) >>> f["name"] 'Apple' >>> "names_by_lang" in f True >>> f["names_by_lang"] As default >>> f = Food.from_dict({"name": "Apple"}).to_dict() >>> f["name"] 'Apple' >>> "names_by_lang" in f False You can exclude Empty properties by specifying True for ignore_empty >>> f = Human.from_dict({"id": 1, "name": "Ichiro", "favorites": []}).to_dict() >>> f["favorites"] [] >>> f = Human.from_dict({"id": 1, "name": "Ichiro", "favorites": []}).to_dict(ignore_empty=True) >>> "favorites" in f False """ return traverse_dict(self._dict, ignore_none, force_value, ignore_empty)
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 Usage: >>> from owlmixin.samples import Human, Food >>> human_dict = { ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple"}} ... ] ... } >>> Human.from_dict(human_dict).to_dict() == human_dict True You can include None properties by specifying False for ignore_none >>> f = Food.from_dict({"name": "Apple"}).to_dict(ignore_none=False) >>> f["name"] 'Apple' >>> "names_by_lang" in f True >>> f["names_by_lang"] As default >>> f = Food.from_dict({"name": "Apple"}).to_dict() >>> f["name"] 'Apple' >>> "names_by_lang" in f False You can exclude Empty properties by specifying True for ignore_empty >>> f = Human.from_dict({"id": 1, "name": "Ichiro", "favorites": []}).to_dict() >>> f["favorites"] [] >>> f = Human.from_dict({"id": 1, "name": "Ichiro", "favorites": []}).to_dict(ignore_empty=True) >>> "favorites" in f False
entailment
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[Dict] Usage: >>> from owlmixin.samples import Human, Food >>> human_dicts = [ ... { ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple"}} ... ] ... }, ... { ... "id": 2, ... "name": "John", ... "favorites": [ ... {"name": "Orange", "names_by_lang": {"en": "Orange"}} ... ] ... } ... ] >>> Human.from_dicts(human_dicts).to_dicts() == human_dicts True You can include None properties by specifying False for ignore_none >>> f = Food.from_dicts([{"name": "Apple"}]).to_dicts(ignore_none=False) >>> f[0]["name"] 'Apple' >>> "names_by_lang" in f[0] True >>> f[0]["names_by_lang"] As default >>> f = Food.from_dicts([{"name": "Apple"}]).to_dicts() >>> f[0]["name"] 'Apple' >>> "names_by_lang" in f[0] False You can exclude Empty properties by specifying True for ignore_empty >>> f = Human.from_dicts([{"id": 1, "name": "Ichiro", "favorites": []}]).to_dicts() >>> f[0]["favorites"] [] >>> f = Human.from_dicts([{"id": 1, "name": "Ichiro", "favorites": []}]).to_dicts(ignore_empty=True) >>> "favorites" in f[0] False """ return traverse_list(self, ignore_none, force_value, ignore_empty)
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[Dict] Usage: >>> from owlmixin.samples import Human, Food >>> human_dicts = [ ... { ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple"}} ... ] ... }, ... { ... "id": 2, ... "name": "John", ... "favorites": [ ... {"name": "Orange", "names_by_lang": {"en": "Orange"}} ... ] ... } ... ] >>> Human.from_dicts(human_dicts).to_dicts() == human_dicts True You can include None properties by specifying False for ignore_none >>> f = Food.from_dicts([{"name": "Apple"}]).to_dicts(ignore_none=False) >>> f[0]["name"] 'Apple' >>> "names_by_lang" in f[0] True >>> f[0]["names_by_lang"] As default >>> f = Food.from_dicts([{"name": "Apple"}]).to_dicts() >>> f[0]["name"] 'Apple' >>> "names_by_lang" in f[0] False You can exclude Empty properties by specifying True for ignore_empty >>> f = Human.from_dicts([{"id": 1, "name": "Ichiro", "favorites": []}]).to_dicts() >>> f[0]["favorites"] [] >>> f = Human.from_dicts([{"id": 1, "name": "Ichiro", "favorites": []}]).to_dicts(ignore_empty=True) >>> "favorites" in f[0] False
entailment
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 Human >>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> human.to_json() '{"favorites": [{"name": "Apple","names_by_lang": {"de": "Apfel","en": "Apple"}},{"name": "Orange"}],"id": 1,"name": "Tom"}' """ return util.dump_json(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), indent)
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 Human >>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> human.to_json() '{"favorites": [{"name": "Apple","names_by_lang": {"de": "Apfel","en": "Apple"}},{"name": "Orange"}],"id": 1,"name": "Tom"}'
entailment
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: Json file path """ return util.save_jsonf(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), fpath, encoding, indent)
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: Json file path
entailment
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_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> print(human.to_pretty_json()) { "favorites": [ { "name": "Apple", "names_by_lang": { "de": "Apfel", "en": "Apple" } }, { "name": "Orange" } ], "id": 1, "name": "Tom" } """ return self.to_json(4, ignore_none, ignore_empty)
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_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> print(human.to_pretty_json()) { "favorites": [ { "name": "Apple", "names_by_lang": { "de": "Apfel", "en": "Apple" } }, { "name": "Orange" } ], "id": 1, "name": "Tom" }
entailment
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({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> print(human.to_yaml()) favorites: - name: Apple names_by_lang: de: Apfel en: Apple - name: Orange id: 1 name: Tom <BLANKLINE> """ return util.dump_yaml(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty))
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({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> print(human.to_yaml()) favorites: - name: Apple names_by_lang: de: Apfel en: Apple - name: Orange id: 1 name: Tom <BLANKLINE>
entailment
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 """ return util.save_yamlf(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), fpath, encoding)
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
entailment
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 :return: Csv string Usage: >>> from owlmixin.samples import Human >>> humans = Human.from_dicts([ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]) >>> print(humans.to_csv(fieldnames=['name', 'id', 'favorites'])) Tom,1,[{'name': 'Apple'}] John,2,[{'name': 'Orange'}] <BLANKLINE> >>> print(humans.to_csv(fieldnames=['name', 'id', 'favorites'], with_header=True)) name,id,favorites Tom,1,[{'name': 'Apple'}] John,2,[{'name': 'Orange'}] <BLANKLINE> """ return util.dump_csv(traverse(self, force_value=True), fieldnames, with_header, crlf, tsv)
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 :return: Csv string Usage: >>> from owlmixin.samples import Human >>> humans = Human.from_dicts([ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]) >>> print(humans.to_csv(fieldnames=['name', 'id', 'favorites'])) Tom,1,[{'name': 'Apple'}] John,2,[{'name': 'Orange'}] <BLANKLINE> >>> print(humans.to_csv(fieldnames=['name', 'id', 'favorites'], with_header=True)) name,id,favorites Tom,1,[{'name': 'Apple'}] John,2,[{'name': 'Orange'}] <BLANKLINE>
entailment
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 :param tsv: Use tabs as separator if True, else use comma :return: Csv file path """ return util.save_csvf(traverse(self, force_value=True), fieldnames, fpath, encoding, with_header, crlf, tsv)
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 :param tsv: Use tabs as separator if True, else use comma :return: Csv file path
entailment
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"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]) >>> print(humans.to_table(fieldnames=['name', 'id', 'favorites'])) | name | id | favorites | | ---- | --- | -------------------- | | Tom | 1 | [{'name': 'Apple'}] | | John | 2 | [{'name': 'Orange'}] | <BLANKLINE> """ return util.dump_table(traverse(self, force_value=True), fieldnames)
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"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]) >>> print(humans.to_table(fieldnames=['name', 'id', 'favorites'])) | name | id | favorites | | ---- | --- | -------------------- | | Tom | 1 | [{'name': 'Apple'}] | | John | 2 | [{'name': 'Orange'}] | <BLANKLINE>
entailment
def _pre_tidy(html): """ This method transforms a few things before tidy runs. When we get rid of tidy, this can go away. """ 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)
This method transforms a few things before tidy runs. When we get rid of tidy, this can go away.
entailment
def _post_tidy(html): """ This method transforms post tidy. Will go away when tidy goes away. """ 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://www.w3.org/1999/xhtml}u' if c: el.attrib['class'] = ' '.join(c) elif 'class' in el.attrib: del(el.attrib['class']) return tree
This method transforms post tidy. Will go away when tidy goes away.
entailment
def _tidy2xhtml5(html): """Tidy up a html4/5 soup to a parsable valid XHTML5. Requires tidy-html5 from https://github.com/w3c/tidy-html5 Installation: http://goo.gl/FG27n """ html = _io2string(html) html = _pre_tidy(html) # Pre-process xhtml5, errors =\ tidy_document(html, options={ # do not merge nested div elements # - preserve semantic block structrues 'merge-divs': 0, # create xml output 'output-xml': 1, # Don't use indent, adds extra linespace or linefeed # which are big problems 'indent': 0, # No tidy meta tag in output 'tidy-mark': 0, # No wrapping 'wrap': 0, # Help ensure validation 'alt-text': '', # No sense in transitional for tool-generated markup 'doctype': 'strict', # May not get what you expect, # but you will get something 'force-output': 1, # remove HTML entities like e.g. nbsp 'numeric-entities': 1, # remove 'clean': 1, 'bare': 1, 'word-2000': 1, 'drop-proprietary-attributes': 1, # enclose text in body always with <p>...</p> 'enclose-text': 1, # transforms <i> and <b> to <em> and <strong> 'logical-emphasis': 1, # do not tidy all MathML elements! # List of MathML 3.0 elements from # http://www.w3.org/TR/MathML3/appendixi.html#index.elem 'new-inline-tags': 'abs, and, annotation, ' 'annotation-xml, apply, approx, arccos, arccosh, ' 'arccot, arccoth, arccsc, arccsch, arcsec, arcsech, ' 'arcsin, arcsinh, arctan, arctanh, arg, bind, bvar, ' 'card, cartesianproduct, cbytes, ceiling, cerror, ' 'ci, cn, codomain, complexes, compose, condition, ' 'conjugate, cos, cosh, cot, coth, cs, csc, csch, ' 'csymbol, curl, declare, degree, determinant, diff, ' 'divergence, divide, domain, domainofapplication, ' 'el, emptyset, eq, equivalent, eulergamma, exists, ' 'exp, exponentiale, factorial, factorof, false, ' 'floor, fn, forall, gcd, geq, grad, gt, ident, ' 'image, imaginary, imaginaryi, implies, in, ' 'infinity, int, integers, intersect, interval, ' 'inverse, lambda, laplacian, lcm, leq, limit, list, ' 'ln, log, logbase, lowlimit, lt, maction, malign, ' 'maligngroup, malignmark, malignscope, math, ' 'matrix, matrixrow, max, mean, median, menclose, ' 'merror, mfenced, mfrac, mfraction, mglyph, mi, ' 'min, minus, mlabeledtr, mlongdiv, mmultiscripts, ' 'mn, mo, mode, moment, momentabout, mover, mpadded, ' 'mphantom, mprescripts, mroot, mrow, ms, mscarries, ' 'mscarry, msgroup, msline, mspace, msqrt, msrow, ' 'mstack, mstyle, msub, msubsup, msup, mtable, mtd, ' 'mtext, mtr, munder, munderover, naturalnumbers, ' 'neq, none, not, notanumber, note, notin, ' 'notprsubset, notsubset, or, otherwise, ' 'outerproduct, partialdiff, pi, piece, piecewise, ' 'plus, power, primes, product, prsubset, quotient, ' 'rationals, real, reals, reln, rem, root, ' 'scalarproduct, sdev, sec, sech, selector, ' 'semantics, sep, set, setdiff, share, sin, sinh, ' 'subset, sum, tan, tanh, tendsto, times, transpose, ' 'true, union, uplimit, variance, vector, ' 'vectorproduct, xor', 'doctype': 'html5', }) # return xhtml5 # return the tree itself, there is another modification below to avoid # another parse return _post_tidy(xhtml5)
Tidy up a html4/5 soup to a parsable valid XHTML5. Requires tidy-html5 from https://github.com/w3c/tidy-html5 Installation: http://goo.gl/FG27n
entailment
def _make_xsl(filename): """Helper that creates a XSLT stylesheet """ path = pkg_resources.resource_filename('rhaptos.cnxmlutils.xsl', filename) xml = etree.parse(path) return etree.XSLT(xml)
Helper that creates a XSLT stylesheet
entailment
def _transform(xsl_filename, xml, **kwargs): """Transforms the xml using the specifiec xsl file.""" xslt = _make_xsl(xsl_filename) xml = xslt(xml, **kwargs) return xml
Transforms the xml using the specifiec xsl file.
entailment
def _unescape_math(xml): """Unescapes Math from Mathjax to MathML.""" 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 math = unescape(unescape(math)) mathscript.clear() mathscript.set('type', 'math/mml') new_math = etree.fromstring(math) mathscript.append(new_math) return xml
Unescapes Math from Mathjax to MathML.
entailment
def cnxml_to_html(cnxml_source): """Transform the CNXML source to HTML""" 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])
Transform the CNXML source to HTML
entailment
def aloha_to_etree(html_source): """ Converts HTML5 from Aloha editor output to a lxml etree. """ xml = _tidy2xhtml5(html_source) for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE): xml = transform(xml) return xml
Converts HTML5 from Aloha editor output to a lxml etree.
entailment
def aloha_to_html(html_source): """Converts HTML5 from Aloha to a more structured HTML5""" xml = aloha_to_etree(html_source) return etree.tostring(xml, pretty_print=True)
Converts HTML5 from Aloha to a more structured HTML5
entailment
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. """ 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.rice.edu/cnxml'} xpath = etree.XPath('//c:content', namespaces=namespaces) replaceable_node = xpath(cnxml)[0] replaceable_node.getparent().replace(replaceable_node, xml.getroot()) # Set the content into the existing cnxml source return etree.tostring(cnxml)
Transform the HTML to CNXML. We need the original CNXML content in order to preserve the metadata in the CNXML document.
entailment
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 """ source = _string2io(html_source) xml = etree.parse(source) return etree_to_valid_cnxml(xml, pretty_print=True)
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
entailment
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 """ return default if self.value is None else self.value
Usage: >>> TOption(3).get_or(999) 3 >>> TOption(0).get_or(999) 0 >>> TOption(None).get_or(999) 999
entailment
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 """ return self if self.is_none() else TOption(func(self.value))
Usage: >>> TOption(3).map(lambda x: x+1).get() 4 >>> TOption(None).map(lambda x: x+1).get_or(999) 999
entailment
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 """ return self if self.is_none() else TOption(func(self.value).get())
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
entailment
def replace(text): """Replace both the hex and decimal versions of symbols in an XML string""" 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
Replace both the hex and decimal versions of symbols in an XML string
entailment
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] """ return { to_snake(keymap.get(k, k)) if force_snake_case else keymap.get(k, k): v for k, v in d.items() }
:param dict d: :param Dict[unicode, unicode] keymap: :param bool force_snake_case: :rtype: Dict[unicode, unicode]
entailment
def load_jsonf(fpath, encoding): """ :param unicode fpath: :param unicode encoding: :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return json.load(f)
:param unicode fpath: :param unicode encoding: :rtype: dict | list
entailment
def load_yamlf(fpath, encoding): """ :param unicode fpath: :param unicode encoding: :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return yaml.safe_load(f)
:param unicode fpath: :param unicode encoding: :rtype: dict | list
entailment
def load_csvf(fpath, fieldnames, encoding): """ :param unicode fpath: :param Optional[list[unicode]] fieldnames: :param unicode encoding: :rtype: List[dict] """ 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))
:param unicode fpath: :param Optional[list[unicode]] fieldnames: :param unicode encoding: :rtype: List[dict]
entailment
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 """ 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, dialect=dialect, extrasaction='ignore') if with_header: writer.writeheader() for x in data: writer.writerow({k: force_str(v) for k, v in x.items()}) sio.seek(0) return sio.read()
:param data: :param fieldnames: :param with_header: :param crlf: :param tsv: :return: unicode
entailment
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 """ 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
:param data: :param fieldnames: :param fpath: write path :param encoding: encoding :param with_header: :param crlf: :param tsv: :return: written path
entailment
def dump_json(data, indent=None): """ :param list | dict data: :param Optional[int] indent: :rtype: unicode """ return json.dumps(data, indent=indent, ensure_ascii=False, sort_keys=True, separators=(',', ': '))
:param list | dict data: :param Optional[int] indent: :rtype: unicode
entailment
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 """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(dump_json(data, indent)) return fpath
:param data: list | dict data :param fpath: write path :param encoding: encoding :param indent: :rtype: written path
entailment
def dump_yaml(data): """ :param list | dict data: :rtype: unicode """ return yaml.dump(data, indent=2, encoding=None, allow_unicode=True, default_flow_style=False, Dumper=MyDumper)
:param list | dict data: :rtype: unicode
entailment
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 """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(dump_yaml(data)) return fpath
:param data: list | dict data :param fpath: write path :param encoding: encoding :rtype: written path
entailment
def dump_table(data: List[dict], fieldnames: Sequence[str]) -> str: """ :param data: :param fieldnames: :return: Table string """ 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): """ aaa, 4 => ' aaa ' """ to_fills: int = width - string_width(word) return f" {' ' * floor(to_fills / 2)}{word}{' ' * ceil(to_fills / 2)} " if center \ else f" {word}{' ' * to_fills} " def to_record(r: dict) -> str: return f"|{'|'.join([fill_spaces(str(r.get(f)), width_by_col.get(f)) for f in fieldnames])}|" return f""" |{'|'.join([fill_spaces(x, width_by_col.get(x), center=True) for x in fieldnames])}| |{'|'.join([fill_spaces(width_by_col.get(x) * "-", width_by_col.get(x)) for x in fieldnames])}| {os.linesep.join([to_record(x) for x in data])} """.lstrip()
:param data: :param fieldnames: :return: Table string
entailment
def string_width(word: str) -> int: """ :param word: :return: Widths of word Usage: >>> string_width('abc') 3 >>> string_width('Abしー') 7 >>> string_width('') 0 """ return sum(map(lambda x: 2 if east_asian_width(x) in 'FWA' else 1, word))
:param word: :return: Widths of word Usage: >>> string_width('abc') 3 >>> string_width('Abしー') 7 >>> string_width('') 0
entailment
def writeXMLFile(filename, content): """ Used only for debugging to write out intermediate files""" xmlfile = open(filename, 'w') # pretty print content = etree.tostring(content, pretty_print=True) xmlfile.write(content) xmlfile.close()
Used only for debugging to write out intermediate files
entailment
def transform(odtfile, debug=False, parsable=False, outputdir=None): """ Given an ODT file this returns a tuple containing the cnxml, a dictionary of filename -> data, and a list of errors """ # Store mapping of images extracted from the ODT file (and their bits) images = {} # Log of Errors and Warnings generated # For example, the text produced by XSLT should be: # {'level':'WARNING', # 'msg' :'Headings without text between them are not allowed', # 'id' :'import-auto-id2376'} # That way we can put a little * near all the cnxml where issues arose errors = [] zip = zipfile.ZipFile(odtfile, 'r') content = zip.read('content.xml') xml = etree.fromstring(content) def appendLog(xslDoc): if hasattr(xslDoc, 'error_log'): for entry in xslDoc.error_log: # Entries are of the form: # {'level':'ERROR','id':'id1234','msg':'Descriptive message'} text = entry.message try: dict = json.loads(text) errors.append(dict) except ValueError: errors.append({ u'level':u'CRITICAL', u'id' :u'(none)', u'msg' :unicode(text) }) def injectStyles(xml): # HACK - need to find the object location from the manifest ... strStyles = zip.read('styles.xml') parser = etree.XMLParser() parser.feed(strStyles) stylesXml = parser.close() for i, obj in enumerate(STYLES_XPATH(stylesXml)): xml.append(obj) return xml # All MathML is stored in separate files "Object #/content.xml" # This converter includes the MathML by looking up the file in the zip def mathIncluder(xml): for i, obj in enumerate(MATH_XPATH(xml)): strMathPath = MATH_HREF_XPATH(obj)[0] # Or obj.get('{%s}href' % XLINK_NS) if strMathPath[0] == '#': strMathPath = strMathPath[1:] # Remove leading './' Zip doesn't like it if strMathPath[0] == '.': strMathPath = strMathPath[2:] # HACK - need to find the object location from the manifest ... strMathPath = os.path.join(strMathPath, 'content.xml') strMath = zip.read(strMathPath) #parser = etree.XMLParser(encoding='utf-8') #parser.feed(strMath) #math = parser.close() math = etree.parse(StringIO(strMath)).getroot() # Replace the reference to the Math with the actual MathML obj.getparent().replace(obj, math) return xml def imagePuller(xml): for i, obj in enumerate(IMAGE_XPATH(xml)): strPath = IMAGE_HREF_XPATH(obj)[0] strName = IMAGE_NAME_XPATH(obj)[0] fileNeedEnding = ( strName.find('.') == -1 ) if fileNeedEnding: strName = strName + strPath[strPath.index('.'):] if strPath[0] == '#': strPath = strPath[1:] # Remove leading './' Zip doesn't like it if strPath[0] == '.': strPath = strPath[2:] image = zip.read(strPath) images[strName] = image # Later on, an XSL pass will convert the draw:frame to a c:image and # set the @src correctly return xml def drawPuller(xml): styles = DRAW_STYLES_XPATH(xml) empty_odg_dirname = os.path.join(dirname, 'empty_odg_template') temp_dirname = tempfile.mkdtemp() for i, obj in enumerate(DRAW_XPATH(xml)): # Copy everything except content.xml from the empty ODG (OOo Draw) template into a new zipfile odg_filename = DRAW_FILENAME_PREFIX + str(i) + '.odg' png_filename = DRAW_FILENAME_PREFIX + str(i) + '.png' # add PNG filename as attribute to parent node. The good thing is: The child (obj) will get lost! :-) parent = obj.getparent() parent.attrib['ooo_drawing'] = png_filename odg_zip = zipfile.ZipFile(os.path.join(temp_dirname, odg_filename), 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(empty_odg_dirname): for name in files: if name not in ('content.xml', 'styles.xml'): # copy everything inside ZIP except content.xml or styles.xml sourcename = os.path.join(root, name) # http://stackoverflow.com/a/1193171/756056 arcname = os.path.join(root[len(empty_odg_dirname):], name) # Path name inside the ZIP file, empty_odg_template is the root folder odg_zip.write(sourcename, arcname) content = etree.parse(os.path.join(empty_odg_dirname, 'content.xml')) # Inject content styles in empty OOo Draw content.xml content_style_xpath = etree.XPath('/office:document-content/office:automatic-styles', namespaces=NAMESPACES) content_styles = content_style_xpath(content) for style in styles: content_styles[0].append(deepcopy(style)) # Inject drawing in empty OOo Draw content.xml content_page_xpath = etree.XPath('/office:document-content/office:body/office:drawing/draw:page', namespaces=NAMESPACES) content_page = content_page_xpath(content) content_page[0].append(obj) # write modified content.xml odg_zip.writestr('content.xml', etree.tostring(content, xml_declaration=True, encoding='UTF-8')) # copy styles.xml from odt to odg without modification styles_xml = zip.read('styles.xml') odg_zip.writestr('styles.xml', styles_xml) odg_zip.close() # TODO: Better error handling in the future. try: # convert every odg to png command = '/usr/bin/soffice -headless -nologo -nofirststartwizard "macro:///Standard.Module1.SaveAsPNG(%s,%s)"' % (os.path.join(temp_dirname, odg_filename),os.path.join(temp_dirname, png_filename)) os.system(command) # save every image to memory image = open(os.path.join(temp_dirname, png_filename), 'r').read() images[png_filename] = image if outputdir is not None: shutil.copy (os.path.join(temp_dirname, odg_filename), os.path.join(outputdir, odg_filename)) shutil.copy (os.path.join(temp_dirname, png_filename), os.path.join(outputdir, png_filename)) except: pass # delete temporary directory shutil.rmtree(temp_dirname) return xml # Reparse after XSL because the RED-escape pass injects arbitrary XML def redParser(xml): xsl = makeXsl('pass1_odt2red-escape.xsl') result = xsl(xml) appendLog(xsl) try: xml = etree.fromstring(etree.tostring(result)) except etree.XMLSyntaxError, e: msg = str(e) xml = makeXsl('pass1_odt2red-failed.xsl')(xml, message="'%s'" % msg.replace("'", '"')) xml = xml.getroot() return xml def replaceSymbols(xml): xmlstr = etree.tostring(xml) xmlstr = symbols.replace(xmlstr) return etree.fromstring(xmlstr) PIPELINE = [ drawPuller, # gets OOo Draw objects out of odt and generate odg (OOo Draw) files replaceSymbols, injectStyles, # include the styles.xml file because it contains list numbering info makeXsl('pass2_odt-normalize.xsl'), # This needs to be done 2x to fix headings makeXsl('pass2_odt-normalize.xsl'), # In the worst case all headings are 9 # and need to be 1. See (testbed) southwood__Lesson_2.doc makeXsl('pass2_odt-collapse-spans.xsl'), # Collapse adjacent spans (for RED) redParser, # makeXsl('pass1_odt2red-escape.xsl'), makeXsl('pass4_odt-headers.xsl'), imagePuller, # Need to run before math because both have a <draw:image> (see xpath) mathIncluder, makeXsl('pass7_odt2cnxml.xsl'), makeXsl('pass8_cnxml-cleanup.xsl'), makeXsl('pass8.5_cnxml-cleanup.xsl'), makeXsl('pass9_id-generation.xsl'), makeXsl('pass10_processing-instruction-logger.xsl'), ] # "xml" variable gets replaced during each iteration passNum = 0 for xslDoc in PIPELINE: if debug: errors.append("DEBUG: Starting pass %d" % passNum) xml = xslDoc(xml) appendLog(xslDoc) if outputdir is not None: writeXMLFile(os.path.join(outputdir, 'pass%d.xml' % passNum), xml) passNum += 1 # In most cases (EIP) Invalid XML is preferable over valid but Escaped XML if not parsable: xml = (makeXsl('pass11_red-unescape.xsl'))(xml) return (xml, images, errors)
Given an ODT file this returns a tuple containing the cnxml, a dictionary of filename -> data, and a list of errors
entailment
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 """ return [x for x in cls.__members__.values() if x.value[0] == value][0]
Create instance from symbol :param value: unique symbol :return: This instance Usage: >>> from owlmixin.samples import Animal >>> Animal.from_value('cat').crow() mewing
entailment
def auto_thaw(vault_client, opt): """Will thaw into a temporary location""" icefile = opt.thaw_from if not os.path.exists(icefile): raise aomi.exceptions.IceFile("%s missing" % icefile) thaw(vault_client, icefile, opt) return opt
Will thaw into a temporary location
entailment
def seed(vault_client, opt): """Will provision vault based on the definition within a Secretfile""" 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)
Will provision vault based on the definition within a Secretfile
entailment
def render(directory, opt): """Render any provided template. This includes the Secretfile, Vault policies, and inline AWS roles""" 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_secretfile), opt) for resource in ctx.resources(): if not resource.present: continue if issubclass(type(resource), Policy): if not os.path.isdir("%s/policy" % directory): os.mkdir("%s/policy" % directory) filename = "%s/policy/%s" % (directory, resource.path) open(filename, 'w').write(resource.obj()) LOG.debug("writing %s to %s", resource, filename) elif issubclass(type(resource), AWSRole): if not os.path.isdir("%s/aws" % directory): os.mkdir("%s/aws" % directory) if 'policy' in resource.obj(): filename = "%s/aws/%s" % (directory, os.path.basename(resource.path)) r_obj = resource.obj() if 'policy' in r_obj: LOG.debug("writing %s to %s", resource, filename) open(filename, 'w').write(r_obj['policy'])
Render any provided template. This includes the Secretfile, Vault policies, and inline AWS roles
entailment
def export(vault_client, opt): """Export contents of a Secretfile from the Vault server into a specified directory.""" ctx = Context.load(get_secretfile(opt), opt) \ .fetch(vault_client) for resource in ctx.resources(): resource.export(opt.directory)
Export contents of a Secretfile from the Vault server into a specified directory.
entailment
def maybe_colored(msg, color, opt): """Maybe it will render in color maybe it will not!""" if opt.monochrome: return msg return colored(msg, color)
Maybe it will render in color maybe it will not!
entailment
def normalize_val(val): """Normalize JSON/YAML derived values as they pertain to Vault resources and comparison operations """ if is_unicode(val) and val.isdigit(): return int(val) elif isinstance(val, list): return ','.join(val) elif val is None: return '' return val
Normalize JSON/YAML derived values as they pertain to Vault resources and comparison operations
entailment
def details_dict(obj, existing, ignore_missing, opt): """Output the changes, if any, for a dict""" 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), 'red', opt)) print(maybe_colored("++ %s: %s" % (ex_k, new_value), 'green', opt)) if (not ignore_missing) and (ex_k not in obj): print(maybe_colored("-- %s: %s" % (ex_k, og_value), 'red', opt)) for ob_k, ob_v in iteritems(obj): val = normalize_val(ob_v) if ob_k not in existing: print(maybe_colored("++ %s: %s" % (ob_k, val), 'green', opt)) return
Output the changes, if any, for a dict
entailment
def maybe_details(resource, opt): """At the first level of verbosity this will print out detailed change information on for the specified Vault resource""" 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 existing = resource.existing if not obj: return if is_unicode(existing) and is_unicode(obj): a_diff = difflib.unified_diff(existing.splitlines(), obj.splitlines(), lineterm='') for line in a_diff: if line.startswith('+++') or line.startswith('---'): continue if line[0] == '+': print(maybe_colored("++ %s" % line[1:], 'green', opt)) elif line[0] == '-': print(maybe_colored("-- %s" % line[1:], 'red', opt)) else: print(line) elif isinstance(existing, dict): ignore_missing = isinstance(resource, VaultBackend) details_dict(obj, existing, ignore_missing, opt)
At the first level of verbosity this will print out detailed change information on for the specified Vault resource
entailment
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""" 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))) elif changed == OVERWRITE: print("%s %s" % (maybe_colored("+", "yellow", opt), str(thing))) elif changed == CONFLICT: print("%s %s" % (maybe_colored("!", "red", opt), str(thing))) if changed != OVERWRITE and changed != NOOP: maybe_details(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
entailment
def diff(vault_client, opt): """Derive a comparison between what is represented in the Secretfile and what is actually live on a Vault instance""" 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(): diff_a_thing(resource, opt) if opt.thaw_from: rmtree(opt.secrets)
Derive a comparison between what is represented in the Secretfile and what is actually live on a Vault instance
entailment
def help_me(parser, opt): """Handle display of help and whatever diagnostics""" 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() else '' tfe_str = 'Token Env,' if 'VAULT_TOKEN' in os.environ else '' appre_str = 'App Role Env,' if 'VAULT_ROLE_ID' in os.environ and \ 'VAULT_SECRET_ID' in os.environ else '' appe_str = 'AppID Env,' if 'VAULT_USER_ID' in os.environ and \ 'VAULT_APP_ID' in os.environ else '' LOG.info(("Auth Hints Present : %s%s%s%s%s%s" % (tf_str, app_str, approle_str, tfe_str, appre_str, appe_str))[:-1]) LOG.info("Vault Server %s" % os.environ['VAULT_ADDR'] if 'VAULT_ADDR' in os.environ else '??') parser.print_help() sys.exit(0)
Handle display of help and whatever diagnostics
entailment
def extract_file_args(subparsers): """Add the command line options for the extract_file operation""" extract_parser = subparsers.add_parser('extract_file', help='Extract a single secret from' 'Vault to a local file') extract_parser.add_argument('vault_path', help='Full path (including key) to secret') extract_parser.add_argument('destination', help='Location of destination file') base_args(extract_parser)
Add the command line options for the extract_file operation
entailment
def mapping_args(parser): """Add various variable mapping command line options to the parser""" parser.add_argument('--add-prefix', dest='add_prefix', help='Specify a prefix to use when ' 'generating secret key names') parser.add_argument('--add-suffix', dest='add_suffix', help='Specify a suffix to use when ' 'generating secret key names') parser.add_argument('--merge-path', dest='merge_path', action='store_true', default=True, help='merge vault path and key name') parser.add_argument('--no-merge-path', dest='merge_path', action='store_false', default=True, help='do not merge vault path and key name') parser.add_argument('--key-map', dest='key_map', action='append', type=str, default=[])
Add various variable mapping command line options to the parser
entailment
def aws_env_args(subparsers): """Add command line options for the aws_environment operation""" env_parser = subparsers.add_parser('aws_environment') env_parser.add_argument('vault_path', help='Full path(s) to the AWS secret') export_arg(env_parser) base_args(env_parser)
Add command line options for the aws_environment operation
entailment
def environment_args(subparsers): """Add command line options for the environment operation""" env_parser = subparsers.add_parser('environment') env_parser.add_argument('vault_paths', help='Full path(s) to secret', nargs='+') env_parser.add_argument('--prefix', dest='prefix', help='Old style prefix to use when' 'generating secret key names') export_arg(env_parser) mapping_args(env_parser) base_args(env_parser)
Add command line options for the environment operation
entailment
def template_args(subparsers): """Add command line options for the template operation""" template_parser = subparsers.add_parser('template') template_parser.add_argument('template', help='Template source', nargs='?') template_parser.add_argument('destination', help='Path to write rendered template', nargs='?') template_parser.add_argument('vault_paths', help='Full path(s) to secret', nargs='*') template_parser.add_argument('--builtin-list', dest='builtin_list', help='Display a list of builtin templates', action='store_true', default=False) template_parser.add_argument('--builtin-info', dest='builtin_info', help='Display information on a ' 'particular builtin template') vars_args(template_parser) mapping_args(template_parser) base_args(template_parser)
Add command line options for the template operation
entailment
def secretfile_args(parser): """Add Secretfile management command line arguments to parser""" parser.add_argument('--secrets', dest='secrets', help='Path where secrets are stored', default=os.path.join(os.getcwd(), ".secrets")) parser.add_argument('--policies', dest='policies', help='Path where policies are stored', default=os.path.join(os.getcwd(), "vault", "")) parser.add_argument('--secretfile', dest='secretfile', help='Secretfile to use', default=os.path.join(os.getcwd(), "Secretfile")) parser.add_argument('--tags', dest='tags', help='Tags of things to seed', default=[], type=str, action='append') parser.add_argument('--include', dest='include', help='Specify paths to include', default=[], type=str, action='append') parser.add_argument('--exclude', dest='exclude', help='Specify paths to exclude', default=[], type=str, action='append')
Add Secretfile management command line arguments to parser
entailment
def base_args(parser): """Add the generic command line options""" generic_args(parser) parser.add_argument('--monochrome', dest='monochrome', help='Whether or not to use colors', action='store_true') parser.add_argument('--metadata', dest='metadata', help='A series of key=value pairs for token metadata.', default='') parser.add_argument('--lease', dest='lease', help='Lease time for intermediary token.', default='10s') parser.add_argument('--reuse-token', dest='reuse_token', help='Whether to reuse the existing token. Note' ' this will cause metadata to not be preserved', action='store_true')
Add the generic command line options
entailment
def export_args(subparsers): """Add command line options for the export operation""" export_parser = subparsers.add_parser('export') export_parser.add_argument('directory', help='Path where secrets will be exported into') secretfile_args(export_parser) vars_args(export_parser) base_args(export_parser)
Add command line options for the export operation
entailment
def render_args(subparsers): """Add command line options for the render operation""" render_parser = subparsers.add_parser('render') render_parser.add_argument('directory', help='Path where Secrefile and accoutrement' ' will be rendered into') secretfile_args(render_parser) vars_args(render_parser) base_args(render_parser) thaw_from_args(render_parser)
Add command line options for the render operation
entailment